diff --git a/.prettierignore b/.prettierignore index 96dbc4e03eb0..77ce5a4be263 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1251,6 +1251,7 @@ browser/extensions/translations/extension/ # "scaffolding" used by uniffi which isn't valid JS in its original form. toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/ toolkit/components/uniffi-bindgen-gecko-js/components/generated/* +toolkit/components/uniffi-bindgen-gecko-js/tests/generated/* ############################################################################## # The list below is copied from ThirdPartyPaths.txt. Prettier doesn't currently diff --git a/Cargo.lock b/Cargo.lock index cad4df976903..5219e66df313 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2584,7 +2584,6 @@ dependencies = [ "gecko_logger", "geckoservo", "gkrust-uniffi-components", - "gkrust-uniffi-fixtures", "gkrust_utils", "http_sfv", "idna_glue", @@ -2635,6 +2634,7 @@ dependencies = [ "unic-langid-ffi", "unicode-bidi", "unicode-bidi-ffi", + "uniffi-bindgen-gecko-js-test-fixtures", "url", "viaduct", "webext-storage", @@ -2657,24 +2657,6 @@ dependencies = [ "webext-storage", ] -[[package]] -name = "gkrust-uniffi-fixtures" -version = "0.1.0" -dependencies = [ - "uniffi", - "uniffi-example-arithmetic", - "uniffi-example-custom-types", - "uniffi-example-geometry", - "uniffi-example-rondpoint", - "uniffi-example-sprites", - "uniffi-example-todolist", - "uniffi-fixture-callbacks", - "uniffi-fixture-external-types", - "uniffi-fixture-futures", - "uniffi-fixture-refcounts", - "uniffi-trait-interfaces", -] - [[package]] name = "gkrust_utils" version = "0.1.0" @@ -6992,101 +6974,21 @@ dependencies = [ "clap", "extend", "heck", + "indexmap", "serde", "textwrap", "toml", "uniffi", "uniffi_bindgen", + "uniffi_pipeline", ] [[package]] -name = "uniffi-example-arithmetic" -version = "0.22.0" +name = "uniffi-bindgen-gecko-js-test-fixtures" +version = "0.29.0" dependencies = [ - "thiserror 1.999.999", - "uniffi", -] - -[[package]] -name = "uniffi-example-custom-types" -version = "0.19.6" -dependencies = [ - "anyhow", - "bytes", - "serde_json", - "uniffi", - "url", -] - -[[package]] -name = "uniffi-example-geometry" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-example-rondpoint" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-example-sprites" -version = "0.22.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-example-todolist" -version = "0.22.0" -dependencies = [ - "once_cell", - "thiserror 1.999.999", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-callbacks" -version = "0.21.0" -dependencies = [ - "thiserror 1.999.999", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-external-types" -version = "0.21.0" -dependencies = [ - "thiserror 1.999.999", - "uniffi", - "uniffi-example-geometry", - "uniffi-example-sprites", -] - -[[package]] -name = "uniffi-fixture-futures" -version = "0.21.0" -dependencies = [ - "log", - "moz_task", - "uniffi", -] - -[[package]] -name = "uniffi-fixture-refcounts" -version = "0.21.0" -dependencies = [ - "uniffi", -] - -[[package]] -name = "uniffi-trait-interfaces" -version = "0.22.0" -dependencies = [ - "uniffi", + "uniffi_bindings_tests", + "uniffi_bindings_tests_external_types", ] [[package]] @@ -7116,6 +7018,23 @@ dependencies = [ "uniffi_udl", ] +[[package]] +name = "uniffi_bindings_tests" +version = "0.29.0" +dependencies = [ + "thiserror 1.999.999", + "uniffi", +] + +[[package]] +name = "uniffi_bindings_tests_external_types" +version = "0.29.0" +dependencies = [ + "thiserror 1.999.999", + "uniffi", + "uniffi_bindings_tests", +] + [[package]] name = "uniffi_build" version = "0.29.2" diff --git a/Cargo.toml b/Cargo.toml index 48ae3b4f9540..d7dbc5cb1701 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,6 +65,7 @@ rust-version = "1.82.0" # Shared across multiple UniFFI consumers. uniffi = "0.29.2" uniffi_bindgen = "0.29.2" +uniffi_pipeline = "0.29.2" # Shared across multiple application-services consumers. rusqlite = "0.33.0" # Shared across multiple glean consumers. diff --git a/docs/rust-components/api/js/context_id.md b/docs/rust-components/api/js/context_id.md index acd02459b42a..afffa6eb1092 100644 --- a/docs/rust-components/api/js/context_id.md +++ b/docs/rust-components/api/js/context_id.md @@ -1,5 +1,4 @@ # RustContextId.sys.mjs - ```{js:autoclass} RustContextId.sys.ContextIdComponent :members: :exclude-members: ContextIdComponent diff --git a/docs/rust-components/api/js/errorsupport.md b/docs/rust-components/api/js/errorsupport.md index 4a204fa7eebe..73a3e203fbf9 100644 --- a/docs/rust-components/api/js/errorsupport.md +++ b/docs/rust-components/api/js/errorsupport.md @@ -1,5 +1,4 @@ # RustErrorsupport.sys.mjs - ```{js:autofunction} RustErrorsupport.sys.setApplicationErrorReporter ``` ```{js:autofunction} RustErrorsupport.sys.unsetApplicationErrorReporter diff --git a/docs/rust-components/api/js/relevancy.md b/docs/rust-components/api/js/relevancy.md index 5b9a3cb12194..1518152c7ebf 100644 --- a/docs/rust-components/api/js/relevancy.md +++ b/docs/rust-components/api/js/relevancy.md @@ -1,5 +1,8 @@ # RustRelevancy.sys.mjs - +```{js:autoclass} RustRelevancy.sys.Interest + :members: + :exclude-members: Interest +``` ```{js:autoclass} RustRelevancy.sys.InterestMetrics :members: :exclude-members: InterestMetrics @@ -8,10 +11,6 @@ :members: :exclude-members: InterestVector ``` -```{js:autoclass} RustRelevancy.sys.Interest - :members: - :exclude-members: Interest -``` ```{js:autoclass} RustRelevancy.sys.RelevancyApiError :members: :exclude-members: RelevancyApiError diff --git a/docs/rust-components/api/js/remote_settings.md b/docs/rust-components/api/js/remote_settings.md index 2331763b7373..d3c46a65343b 100644 --- a/docs/rust-components/api/js/remote_settings.md +++ b/docs/rust-components/api/js/remote_settings.md @@ -1,17 +1,24 @@ # RustRemoteSettings.sys.mjs - -```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsClient - :members: - :exclude-members: RemoteSettingsClient -``` -```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsService - :members: - :exclude-members: RemoteSettingsService -``` ```{js:autoclass} RustRemoteSettings.sys.Attachment :members: :exclude-members: Attachment ``` +```{js:autoclass} RustRemoteSettings.sys.Backoff + :members: + :exclude-members: Backoff +``` +```{js:autoclass} RustRemoteSettings.sys.Network + :members: + :exclude-members: Network +``` +```{js:autoclass} RustRemoteSettings.sys.Other + :members: + :exclude-members: Other +``` +```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsClient + :members: + :exclude-members: RemoteSettingsClient +``` ```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsConfig :members: :exclude-members: RemoteSettingsConfig @@ -24,6 +31,10 @@ :members: :exclude-members: RemoteSettingsContext ``` +```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsError + :members: + :exclude-members: RemoteSettingsError +``` ```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsRecord :members: :exclude-members: RemoteSettingsRecord @@ -32,23 +43,11 @@ :members: :exclude-members: RemoteSettingsResponse ``` -```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsError - :members: - :exclude-members: RemoteSettingsError -``` ```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsServer :members: :exclude-members: RemoteSettingsServer ``` -```{js:autoclass} RustRemoteSettings.sys.Network +```{js:autoclass} RustRemoteSettings.sys.RemoteSettingsService :members: - :exclude-members: Network -``` -```{js:autoclass} RustRemoteSettings.sys.Backoff - :members: - :exclude-members: Backoff -``` -```{js:autoclass} RustRemoteSettings.sys.Other - :members: - :exclude-members: Other + :exclude-members: RemoteSettingsService ``` diff --git a/docs/rust-components/api/js/search.md b/docs/rust-components/api/js/search.md index 8bc17e0cf31f..badd5cdd558b 100644 --- a/docs/rust-components/api/js/search.md +++ b/docs/rust-components/api/js/search.md @@ -1,8 +1,7 @@ # RustSearch.sys.mjs - -```{js:autoclass} RustSearch.sys.SearchEngineSelector +```{js:autoclass} RustSearch.sys.JsonEngineMethod :members: - :exclude-members: SearchEngineSelector + :exclude-members: JsonEngineMethod ``` ```{js:autoclass} RustSearch.sys.JsonEngineUrl :members: @@ -12,34 +11,14 @@ :members: :exclude-members: JsonEngineUrls ``` +```{js:autoclass} RustSearch.sys.Other + :members: + :exclude-members: Other +``` ```{js:autoclass} RustSearch.sys.RefinedSearchConfig :members: :exclude-members: RefinedSearchConfig ``` -```{js:autoclass} RustSearch.sys.SearchEngineDefinition - :members: - :exclude-members: SearchEngineDefinition -``` -```{js:autoclass} RustSearch.sys.SearchEngineUrl - :members: - :exclude-members: SearchEngineUrl -``` -```{js:autoclass} RustSearch.sys.SearchEngineUrls - :members: - :exclude-members: SearchEngineUrls -``` -```{js:autoclass} RustSearch.sys.SearchUrlParam - :members: - :exclude-members: SearchUrlParam -``` -```{js:autoclass} RustSearch.sys.SearchUserEnvironment - :members: - :exclude-members: SearchUserEnvironment -``` -```{js:autoclass} RustSearch.sys.JsonEngineMethod - :members: - :exclude-members: JsonEngineMethod -``` ```{js:autoclass} RustSearch.sys.SearchApplicationName :members: :exclude-members: SearchApplicationName @@ -48,11 +27,31 @@ :members: :exclude-members: SearchEngineClassification ``` +```{js:autoclass} RustSearch.sys.SearchEngineDefinition + :members: + :exclude-members: SearchEngineDefinition +``` +```{js:autoclass} RustSearch.sys.SearchEngineSelector + :members: + :exclude-members: SearchEngineSelector +``` +```{js:autoclass} RustSearch.sys.SearchEngineUrl + :members: + :exclude-members: SearchEngineUrl +``` +```{js:autoclass} RustSearch.sys.SearchEngineUrls + :members: + :exclude-members: SearchEngineUrls +``` ```{js:autoclass} RustSearch.sys.SearchUpdateChannel :members: :exclude-members: SearchUpdateChannel ``` -```{js:autoclass} RustSearch.sys.Other +```{js:autoclass} RustSearch.sys.SearchUrlParam :members: - :exclude-members: Other + :exclude-members: SearchUrlParam +``` +```{js:autoclass} RustSearch.sys.SearchUserEnvironment + :members: + :exclude-members: SearchUserEnvironment ``` diff --git a/docs/rust-components/api/js/suggest.md b/docs/rust-components/api/js/suggest.md index 470c195e80c7..61b05488f53e 100644 --- a/docs/rust-components/api/js/suggest.md +++ b/docs/rust-components/api/js/suggest.md @@ -1,12 +1,7 @@ # RustSuggest.sys.mjs - -```{js:autoclass} RustSuggest.sys.SuggestStore +```{js:autoclass} RustSuggest.sys.Backoff :members: - :exclude-members: SuggestStore -``` -```{js:autoclass} RustSuggest.sys.SuggestStoreBuilder - :members: - :exclude-members: SuggestStoreBuilder + :exclude-members: Backoff ``` ```{js:autoclass} RustSuggest.sys.FtsMatchInfo :members: @@ -20,10 +15,34 @@ :members: :exclude-members: GeonameMatch ``` +```{js:autoclass} RustSuggest.sys.GeonameType + :members: + :exclude-members: GeonameType +``` +```{js:autoclass} RustSuggest.sys.InterruptKind + :members: + :exclude-members: InterruptKind +``` +```{js:autoclass} RustSuggest.sys.Interrupted + :members: + :exclude-members: Interrupted +``` ```{js:autoclass} RustSuggest.sys.LabeledTimingSample :members: :exclude-members: LabeledTimingSample ``` +```{js:autoclass} RustSuggest.sys.Network + :members: + :exclude-members: Network +``` +```{js:autoclass} RustSuggest.sys.Other + :members: + :exclude-members: Other +``` +```{js:autoclass} RustSuggest.sys.SuggestApiError + :members: + :exclude-members: SuggestApiError +``` ```{js:autoclass} RustSuggest.sys.SuggestGlobalConfig :members: :exclude-members: SuggestGlobalConfig @@ -36,30 +55,18 @@ :members: :exclude-members: SuggestIngestionMetrics ``` -```{js:autoclass} RustSuggest.sys.SuggestionProviderConstraints - :members: - :exclude-members: SuggestionProviderConstraints -``` -```{js:autoclass} RustSuggest.sys.SuggestionQuery - :members: - :exclude-members: SuggestionQuery -``` -```{js:autoclass} RustSuggest.sys.GeonameType - :members: - :exclude-members: GeonameType -``` -```{js:autoclass} RustSuggest.sys.InterruptKind - :members: - :exclude-members: InterruptKind -``` -```{js:autoclass} RustSuggest.sys.SuggestApiError - :members: - :exclude-members: SuggestApiError -``` ```{js:autoclass} RustSuggest.sys.SuggestProviderConfig :members: :exclude-members: SuggestProviderConfig ``` +```{js:autoclass} RustSuggest.sys.SuggestStore + :members: + :exclude-members: SuggestStore +``` +```{js:autoclass} RustSuggest.sys.SuggestStoreBuilder + :members: + :exclude-members: SuggestStoreBuilder +``` ```{js:autoclass} RustSuggest.sys.Suggestion :members: :exclude-members: Suggestion @@ -68,25 +75,17 @@ :members: :exclude-members: SuggestionProvider ``` +```{js:autoclass} RustSuggest.sys.SuggestionProviderConstraints + :members: + :exclude-members: SuggestionProviderConstraints +``` +```{js:autoclass} RustSuggest.sys.SuggestionQuery + :members: + :exclude-members: SuggestionQuery +``` ```{js:autoclass} RustSuggest.sys.YelpSubjectType :members: :exclude-members: YelpSubjectType ``` -```{js:autoclass} RustSuggest.sys.Network - :members: - :exclude-members: Network -``` -```{js:autoclass} RustSuggest.sys.Backoff - :members: - :exclude-members: Backoff -``` -```{js:autoclass} RustSuggest.sys.Interrupted - :members: - :exclude-members: Interrupted -``` -```{js:autoclass} RustSuggest.sys.Other - :members: - :exclude-members: Other -``` ```{js:autofunction} RustSuggest.sys.rawSuggestionUrlMatches ``` diff --git a/docs/rust-components/api/js/sync15.md b/docs/rust-components/api/js/sync15.md index 07f7b3ad90d1..0b493736b5de 100644 --- a/docs/rust-components/api/js/sync15.md +++ b/docs/rust-components/api/js/sync15.md @@ -1,5 +1,4 @@ # RustSync15.sys.mjs - ```{js:autoclass} RustSync15.sys.DeviceType :members: :exclude-members: DeviceType diff --git a/docs/rust-components/api/js/tabs.md b/docs/rust-components/api/js/tabs.md index 40895c377bd8..504ffc12700c 100644 --- a/docs/rust-components/api/js/tabs.md +++ b/docs/rust-components/api/js/tabs.md @@ -1,9 +1,4 @@ # RustTabs.sys.mjs - -```{js:autoclass} RustTabs.sys.TabsBridgedEngine - :members: - :exclude-members: TabsBridgedEngine -``` ```{js:autoclass} RustTabs.sys.PendingCommand :members: :exclude-members: PendingCommand @@ -12,13 +7,17 @@ :members: :exclude-members: RemoteCommand ``` +```{js:autoclass} RustTabs.sys.SqlError + :members: + :exclude-members: SqlError +``` ```{js:autoclass} RustTabs.sys.SyncError :members: :exclude-members: SyncError ``` -```{js:autoclass} RustTabs.sys.SqlError +```{js:autoclass} RustTabs.sys.TabsBridgedEngine :members: - :exclude-members: SqlError + :exclude-members: TabsBridgedEngine ``` ```{js:autoclass} RustTabs.sys.UnexpectedTabsError :members: diff --git a/docs/rust-components/api/js/webextstorage.md b/docs/rust-components/api/js/webextstorage.md index 2edad2ce3f89..86e62f862a47 100644 --- a/docs/rust-components/api/js/webextstorage.md +++ b/docs/rust-components/api/js/webextstorage.md @@ -1,9 +1,4 @@ # RustWebextstorage.sys.mjs - -```{js:autoclass} RustWebextstorage.sys.UnexpectedError - :members: - :exclude-members: UnexpectedError -``` ```{js:autoclass} RustWebextstorage.sys.JsonError :members: :exclude-members: JsonError @@ -12,3 +7,7 @@ :members: :exclude-members: QuotaError ``` +```{js:autoclass} RustWebextstorage.sys.UnexpectedError + :members: + :exclude-members: UnexpectedError +``` diff --git a/toolkit/components/moz.build b/toolkit/components/moz.build index 754c63f7c175..dcf865c53941 100644 --- a/toolkit/components/moz.build +++ b/toolkit/components/moz.build @@ -143,7 +143,7 @@ if CONFIG["MOZ_BACKGROUNDTASKS"]: DIRS += ["backgroundtasks"] if CONFIG["MOZ_UNIFFI_FIXTURES"]: - DIRS += ["uniffi-bindgen-gecko-js/fixtures"] + DIRS += ["uniffi-bindgen-gecko-js/tests"] if CONFIG["NIGHTLY_BUILD"]: DIRS += ["aboutinference"] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/Cargo.toml index 6282c425611e..bc5c911ae6de 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/Cargo.toml +++ b/toolkit/components/uniffi-bindgen-gecko-js/Cargo.toml @@ -15,9 +15,11 @@ clap = { version = "4", default-features = false, features = ["std", "derive", " cargo_metadata = "0.19" extend = "1.1" heck = "0.5" +indexmap = { version = "2.2", features = ["serde"] } textwrap = { version = "0.16", features = ["smawk"], default-features = false } uniffi = { workspace = true } uniffi_bindgen = { workspace = true } +uniffi_pipeline = { workspace = true } serde = "1" toml = "0.5" camino = "1.0.8" diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/README.md b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/README.md deleted file mode 100644 index 4e4267acd4a3..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/README.md +++ /dev/null @@ -1,6 +0,0 @@ -This directory is where modules generated by UniFFI will be created. - -All files in this directory, other than this one, are generated and should -not be hand-edited. - -To update these files, execute `./mach uniffi generate` diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustContextId.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustContextId.sys.mjs index 9bc5eaccd285..e5289efe502d 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustContextId.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustContextId.sys.mjs @@ -1,294 +1,10 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } - - // Reads a ContextIdComponent pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerContextIdComponent() { - const pointerId = 0; // context_id:ContextIDComponent - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a ContextIdComponent pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerContextIdComponent(value) { - const pointerId = 0; // context_id:ContextIDComponent - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - - /** * Handler for a single UniFFI CallbackInterface * @@ -482,82 +198,284 @@ class UniFFICallbackHandleMapEntry { } } -// Export the FFIConverter object to make external types work. -export class FfiConverterU8 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 256) { - throw new UniFFITypeError(`${value} exceeds the U8 bounds`); - } + +let lazy = {}; + +ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); +ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); + +// Write/Read data to/from an ArrayBuffer +class ArrayBufferDataStream { + constructor(arrayBuffer) { + this.dataView = new DataView(arrayBuffer); + this.pos = 0; } - static computeSize(_value) { - return 1; + + readUint8() { + let rv = this.dataView.getUint8(this.pos); + this.pos += 1; + return rv; } - static lift(value) { - return value; + + writeUint8(value) { + this.dataView.setUint8(this.pos, value); + this.pos += 1; } - static lower(value) { - return value; + + readUint16() { + let rv = this.dataView.getUint16(this.pos); + this.pos += 2; + return rv; } - static write(dataStream, value) { - dataStream.writeUint8(value) + + writeUint16(value) { + this.dataView.setUint16(this.pos, value); + this.pos += 2; } - static read(dataStream) { - return dataStream.readUint8() + + readUint32() { + let rv = this.dataView.getUint32(this.pos); + this.pos += 4; + return rv; + } + + writeUint32(value) { + this.dataView.setUint32(this.pos, value); + this.pos += 4; + } + + readUint64() { + let rv = this.dataView.getBigUint64(this.pos); + this.pos += 8; + return Number(rv); + } + + writeUint64(value) { + this.dataView.setBigUint64(this.pos, BigInt(value)); + this.pos += 8; + } + + + readInt8() { + let rv = this.dataView.getInt8(this.pos); + this.pos += 1; + return rv; + } + + writeInt8(value) { + this.dataView.setInt8(this.pos, value); + this.pos += 1; + } + + readInt16() { + let rv = this.dataView.getInt16(this.pos); + this.pos += 2; + return rv; + } + + writeInt16(value) { + this.dataView.setInt16(this.pos, value); + this.pos += 2; + } + + readInt32() { + let rv = this.dataView.getInt32(this.pos); + this.pos += 4; + return rv; + } + + writeInt32(value) { + this.dataView.setInt32(this.pos, value); + this.pos += 4; + } + + readInt64() { + let rv = this.dataView.getBigInt64(this.pos); + this.pos += 8; + return Number(rv); + } + + writeInt64(value) { + this.dataView.setBigInt64(this.pos, BigInt(value)); + this.pos += 8; + } + + readFloat32() { + let rv = this.dataView.getFloat32(this.pos); + this.pos += 4; + return rv; + } + + writeFloat32(value) { + this.dataView.setFloat32(this.pos, value); + this.pos += 4; + } + + readFloat64() { + let rv = this.dataView.getFloat64(this.pos); + this.pos += 8; + return rv; + } + + writeFloat64(value) { + this.dataView.setFloat64(this.pos, value); + this.pos += 8; + } + + + writeString(value) { + // Note: in order to efficiently write this data, we first write the + // string data, reserving 4 bytes for the size. + const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); + const encodeResult = lazy.encoder.encodeInto(value, dest); + if (encodeResult.read != value.length) { + throw new UniFFIError( + "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" + ); + } + const size = encodeResult.written; + // Next, go back and write the size before the string data + this.dataView.setUint32(this.pos, size); + // Finally, advance our position past both the size and string data + this.pos += size + 4; + } + + readString() { + const size = this.readUint32(); + const source = new Uint8Array(this.dataView.buffer, this.pos, size) + const value = lazy.decoder.decode(source); + this.pos += size; + return value; + } + + readBytes() { + const size = this.readInt32(); + const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); + this.pos += size; + return bytes + } + + writeBytes(value) { + this.writeUint32(value.length); + value.forEach((elt) => { + this.writeUint8(elt); + }) + } + + // Reads a pointer from the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + readPointer(pointerId) { + const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); + this.pos += 8; + return res; + } + + // Writes a pointer into the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + writePointer(pointerId, value) { + UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); + this.pos += 8; } } -// Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt64(value) - } - static read(dataStream) { - return dataStream.readInt64() +function handleRustResult(result, liftCallback, liftErrCallback) { + switch (result.code) { + case "success": + return liftCallback(result.data); + + case "error": + throw liftErrCallback(result.data); + + case "internal-error": + if (result.data) { + throw new UniFFIInternalError(FfiConverterString.lift(result.data)); + } else { + throw new UniFFIInternalError("Unknown error"); + } + + default: + throw new UniFFIError(`Unexpected status code: ${result.code}`); } } -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; +class UniFFIError { + constructor(message) { + this.message = message; } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) + + toString() { + return `UniFFIError: ${this.message}` } } +class UniFFIInternalError extends UniFFIError {} + +// Base class for FFI converters +class FfiConverter { + // throw `UniFFITypeError` if a value to be converted has an invalid type + static checkType(value) { + if (value === undefined ) { + throw new UniFFITypeError(`undefined`); + } + if (value === null ) { + throw new UniFFITypeError(`null`); + } + } +} + +// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer +class FfiConverterArrayBuffer extends FfiConverter { + static lift(buf) { + return this.read(new ArrayBufferDataStream(buf)); + } + + static lower(value) { + const buf = new ArrayBuffer(this.computeSize(value)); + const dataStream = new ArrayBufferDataStream(buf); + this.write(dataStream, value); + return buf; + } + + /** + * Computes the size of the value. + * + * @param {*} _value + * @return {number} + */ + static computeSize(_value) { + throw new UniFFIInternalError("computeSize() should be declared in the derived class"); + } + + /** + * Reads the type from a data stream. + * + * @param {ArrayBufferDataStream} _dataStream + * @returns {any} + */ + static read(_dataStream) { + throw new UniFFIInternalError("read() should be declared in the derived class"); + } + + /** + * Writes the type to a data stream. + * + * @param {ArrayBufferDataStream} _dataStream + * @param {any} _value + */ + static write(_dataStream, _value) { + throw new UniFFIInternalError("write() should be declared in the derived class"); + } + +} + +// Symbols that are used to ensure that Object constructors +// can only be used with a proper UniFFI pointer +const uniffiObjectPtr = Symbol("uniffiObjectPtr"); +const constructUniffiObject = Symbol("constructUniffiObject"); +UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; + // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -588,176 +506,6 @@ export class FfiConverterString extends FfiConverter { } } -/** - * Top-level API for the context_id component - */ -export class ContextIdComponent { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * Construct a new [ContextIDComponent]. - * - * If no creation timestamp is provided, the current time will be used. - * @returns {ContextIdComponent} - */ - static init(initContextId,creationTimestampS,runningInTestAutomation,callback) { - const liftResult = (result) => FfiConverterTypeContextIdComponent.lift(result); - const liftError = (data) => FfiConverterTypeApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(initContextId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("initContextId"); - } - throw e; - } - try { - FfiConverterI64.checkType(creationTimestampS) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("creationTimestampS"); - } - throw e; - } - try { - FfiConverterBool.checkType(runningInTestAutomation) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("runningInTestAutomation"); - } - throw e; - } - try { - FfiConverterTypeContextIdCallback.checkType(callback) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("callback"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 3, // context_id:uniffi_context_id_fn_constructor_contextidcomponent_new - FfiConverterString.lower(initContextId), - FfiConverterI64.lower(creationTimestampS), - FfiConverterBool.lower(runningInTestAutomation), - FfiConverterTypeContextIdCallback.lower(callback), - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Regenerate the context ID. - */ - forceRotation() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 0, // context_id:uniffi_context_id_fn_method_contextidcomponent_force_rotation - FfiConverterTypeContextIdComponent.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Return the current context ID string. - * @returns {string} - */ - request(rotationDaysInS) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeApiError.lift(data); - const functionCall = () => { - try { - FfiConverterU8.checkType(rotationDaysInS) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("rotationDaysInS"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 1, // context_id:uniffi_context_id_fn_method_contextidcomponent_request - FfiConverterTypeContextIdComponent.lower(this), - FfiConverterU8.lower(rotationDaysInS), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Unset the callbacks set during construction, and use a default - * no-op ContextIdCallback instead. - */ - unsetCallback() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 2, // context_id:uniffi_context_id_fn_method_contextidcomponent_unset_callback - FfiConverterTypeContextIdComponent.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeContextIdComponent extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new ContextIdComponent(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'ContextIdComponent' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerContextIdComponent()); - } - - static write(dataStream, value) { - dataStream.writePointerContextIdComponent(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - - - - /** * ApiError */ @@ -814,16 +562,188 @@ export class FfiConverterTypeApiError extends FfiConverterArrayBuffer { static errorClass = ApiError; } +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } +} +/** + * Top-level API for the context_id component + */ +export class ContextIdComponent { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + initContextId, + creationTimestampS, + runningInTestAutomation, + callback) { + + FfiConverterString.checkType(initContextId); + FfiConverterInt64.checkType(creationTimestampS); + FfiConverterBoolean.checkType(runningInTestAutomation); + FfiConverterTypeContextIdCallback.checkType(callback); + const result = UniFFIScaffolding.callSync( + 1, // uniffi_context_id_fn_constructor_contextidcomponent_new + FfiConverterString.lower(initContextId), + FfiConverterInt64.lower(creationTimestampS), + FfiConverterBoolean.lower(runningInTestAutomation), + FfiConverterTypeContextIdCallback.lower(callback), + ) + return handleRustResult( + result, + FfiConverterTypeContextIDComponent.lift.bind(FfiConverterTypeContextIDComponent), + FfiConverterTypeApiError.lift.bind(FfiConverterTypeApiError), + ) + } + /** + * Regenerate the context ID. + */ + async forceRotation() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 2, // uniffi_context_id_fn_method_contextidcomponent_force_rotation + FfiConverterTypeContextIDComponent.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeApiError.lift.bind(FfiConverterTypeApiError), + ) + } + /** + * Return the current context ID string. + */ + async request( + rotationDaysInS) { + + FfiConverterUInt8.checkType(rotationDaysInS); + const result = await UniFFIScaffolding.callAsyncWrapper( + 3, // uniffi_context_id_fn_method_contextidcomponent_request + FfiConverterTypeContextIDComponent.lower(this), + FfiConverterUInt8.lower(rotationDaysInS), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + FfiConverterTypeApiError.lift.bind(FfiConverterTypeApiError), + ) + } + + /** + * Unset the callbacks set during construction, and use a default + * no-op ContextIdCallback instead. + */ + async unsetCallback() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 4, // uniffi_context_id_fn_method_contextidcomponent_unset_callback + FfiConverterTypeContextIDComponent.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeApiError.lift.bind(FfiConverterTypeApiError), + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeContextIDComponent extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new ContextIdComponent(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'ContextIdComponent' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(1)); + } + + static write(dataStream, value) { + dataStream.writePointer(1, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt64(value) + } + static read(dataStream) { + return dataStream.readInt64() + } +} // Export the FFIConverter object to make external types work. export class FfiConverterTypeContextIdCallback extends FfiConverter { static lower(callbackObj) { - return callbackHandlerContextIdCallback.storeCallbackObj(callbackObj) + return uniffiCallbackHandlerContextIdCallback.storeCallbackObj(callbackObj) } static lift(handleId) { - return callbackHandlerContextIdCallback.getCallbackObj(handleId) + return uniffiCallbackHandlerContextIdCallback.getCallbackObj(handleId) } static read(dataStream) { @@ -839,18 +759,15 @@ export class FfiConverterTypeContextIdCallback extends FfiConverter { } } - -// Define callback interface handlers, this must come after the type loop since they reference the FfiConverters defined above. - -const callbackHandlerContextIdCallback = new UniFFICallbackHandler( - "context_id:ContextIdCallback", - 0, +const uniffiCallbackHandlerContextIdCallback = new UniFFICallbackHandler( + "ContextIdCallback", + 1, [ new UniFFICallbackMethodHandler( "persist", [ FfiConverterString, - FfiConverterI64, + FfiConverterInt64, ], ), new UniFFICallbackMethodHandler( @@ -863,8 +780,26 @@ const callbackHandlerContextIdCallback = new UniFFICallbackHandler( ); // Allow the shutdown-related functionality to be tested in the unit tests -UnitTestObjs.callbackHandlerContextIdCallback = callbackHandlerContextIdCallback; - - - - +UnitTestObjs.uniffiCallbackHandlerContextIdCallback = uniffiCallbackHandlerContextIdCallback; +// Export the FFIConverter object to make external types work. +export class FfiConverterBoolean extends FfiConverter { + static computeSize(_value) { + return 1; + } + static lift(value) { + return value == 1; + } + static lower(value) { + if (value) { + return 1; + } else { + return 0; + } + } + static write(dataStream, value) { + dataStream.writeUint8(this.lower(value)) + } + static read(dataStream) { + return this.lift(dataStream.readUint8()) + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustErrorsupport.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustErrorsupport.sys.mjs index 735013b49009..7a98208c5ec4 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustErrorsupport.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustErrorsupport.sys.mjs @@ -1,274 +1,10 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - - /** * Handler for a single UniFFI CallbackInterface * @@ -462,34 +198,318 @@ class UniFFICallbackHandleMapEntry { } } -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } + +let lazy = {}; + +ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); +ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); + +// Write/Read data to/from an ArrayBuffer +class ArrayBufferDataStream { + constructor(arrayBuffer) { + this.dataView = new DataView(arrayBuffer); + this.pos = 0; } - static computeSize(_value) { - return 4; + + readUint8() { + let rv = this.dataView.getUint8(this.pos); + this.pos += 1; + return rv; } - static lift(value) { - return value; + + writeUint8(value) { + this.dataView.setUint8(this.pos, value); + this.pos += 1; } - static lower(value) { - return value; + + readUint16() { + let rv = this.dataView.getUint16(this.pos); + this.pos += 2; + return rv; } - static write(dataStream, value) { - dataStream.writeUint32(value) + + writeUint16(value) { + this.dataView.setUint16(this.pos, value); + this.pos += 2; } - static read(dataStream) { - return dataStream.readUint32() + + readUint32() { + let rv = this.dataView.getUint32(this.pos); + this.pos += 4; + return rv; + } + + writeUint32(value) { + this.dataView.setUint32(this.pos, value); + this.pos += 4; + } + + readUint64() { + let rv = this.dataView.getBigUint64(this.pos); + this.pos += 8; + return Number(rv); + } + + writeUint64(value) { + this.dataView.setBigUint64(this.pos, BigInt(value)); + this.pos += 8; + } + + + readInt8() { + let rv = this.dataView.getInt8(this.pos); + this.pos += 1; + return rv; + } + + writeInt8(value) { + this.dataView.setInt8(this.pos, value); + this.pos += 1; + } + + readInt16() { + let rv = this.dataView.getInt16(this.pos); + this.pos += 2; + return rv; + } + + writeInt16(value) { + this.dataView.setInt16(this.pos, value); + this.pos += 2; + } + + readInt32() { + let rv = this.dataView.getInt32(this.pos); + this.pos += 4; + return rv; + } + + writeInt32(value) { + this.dataView.setInt32(this.pos, value); + this.pos += 4; + } + + readInt64() { + let rv = this.dataView.getBigInt64(this.pos); + this.pos += 8; + return Number(rv); + } + + writeInt64(value) { + this.dataView.setBigInt64(this.pos, BigInt(value)); + this.pos += 8; + } + + readFloat32() { + let rv = this.dataView.getFloat32(this.pos); + this.pos += 4; + return rv; + } + + writeFloat32(value) { + this.dataView.setFloat32(this.pos, value); + this.pos += 4; + } + + readFloat64() { + let rv = this.dataView.getFloat64(this.pos); + this.pos += 8; + return rv; + } + + writeFloat64(value) { + this.dataView.setFloat64(this.pos, value); + this.pos += 8; + } + + + writeString(value) { + // Note: in order to efficiently write this data, we first write the + // string data, reserving 4 bytes for the size. + const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); + const encodeResult = lazy.encoder.encodeInto(value, dest); + if (encodeResult.read != value.length) { + throw new UniFFIError( + "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" + ); + } + const size = encodeResult.written; + // Next, go back and write the size before the string data + this.dataView.setUint32(this.pos, size); + // Finally, advance our position past both the size and string data + this.pos += size + 4; + } + + readString() { + const size = this.readUint32(); + const source = new Uint8Array(this.dataView.buffer, this.pos, size) + const value = lazy.decoder.decode(source); + this.pos += size; + return value; + } + + readBytes() { + const size = this.readInt32(); + const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); + this.pos += size; + return bytes + } + + writeBytes(value) { + this.writeUint32(value.length); + value.forEach((elt) => { + this.writeUint8(elt); + }) + } + + // Reads a pointer from the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + readPointer(pointerId) { + const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); + this.pos += 8; + return res; + } + + // Writes a pointer into the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + writePointer(pointerId, value) { + UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); + this.pos += 8; } } +function handleRustResult(result, liftCallback, liftErrCallback) { + switch (result.code) { + case "success": + return liftCallback(result.data); + + case "error": + throw liftErrCallback(result.data); + + case "internal-error": + if (result.data) { + throw new UniFFIInternalError(FfiConverterString.lift(result.data)); + } else { + throw new UniFFIInternalError("Unknown error"); + } + + default: + throw new UniFFIError(`Unexpected status code: ${result.code}`); + } +} + +class UniFFIError { + constructor(message) { + this.message = message; + } + + toString() { + return `UniFFIError: ${this.message}` + } +} + +class UniFFIInternalError extends UniFFIError {} + +// Base class for FFI converters +class FfiConverter { + // throw `UniFFITypeError` if a value to be converted has an invalid type + static checkType(value) { + if (value === undefined ) { + throw new UniFFITypeError(`undefined`); + } + if (value === null ) { + throw new UniFFITypeError(`null`); + } + } +} + +// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer +class FfiConverterArrayBuffer extends FfiConverter { + static lift(buf) { + return this.read(new ArrayBufferDataStream(buf)); + } + + static lower(value) { + const buf = new ArrayBuffer(this.computeSize(value)); + const dataStream = new ArrayBufferDataStream(buf); + this.write(dataStream, value); + return buf; + } + + /** + * Computes the size of the value. + * + * @param {*} _value + * @return {number} + */ + static computeSize(_value) { + throw new UniFFIInternalError("computeSize() should be declared in the derived class"); + } + + /** + * Reads the type from a data stream. + * + * @param {ArrayBufferDataStream} _dataStream + * @returns {any} + */ + static read(_dataStream) { + throw new UniFFIInternalError("read() should be declared in the derived class"); + } + + /** + * Writes the type to a data stream. + * + * @param {ArrayBufferDataStream} _dataStream + * @param {any} _value + */ + static write(_dataStream, _value) { + throw new UniFFIInternalError("write() should be declared in the derived class"); + } + +} + +// Symbols that are used to ensure that Object constructors +// can only be used with a proper UniFFI pointer +const uniffiObjectPtr = Symbol("uniffiObjectPtr"); +const constructUniffiObject = Symbol("constructUniffiObject"); +UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; +/** + * Set the global error reporter. This is typically done early in startup. + */ +export async function setApplicationErrorReporter( + errorReporter) { + +FfiConverterTypeApplicationErrorReporter.checkType(errorReporter); +const result = await UniFFIScaffolding.callAsyncWrapper( + 5, // uniffi_error_support_fn_func_set_application_error_reporter + FfiConverterTypeApplicationErrorReporter.lower(errorReporter), +) +return handleRustResult( + result, + (result) => undefined, + null, +) +} + +/** + * Unset the global error reporter. This is typically done at shutdown for + * platforms that want to cleanup references like Desktop. + */ +export async function unsetApplicationErrorReporter() { + +const result = await UniFFIScaffolding.callAsyncWrapper( + 6, // uniffi_error_support_fn_func_unset_application_error_reporter +) +return handleRustResult( + result, + (result) => undefined, + null, +) +} + + // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -519,16 +539,41 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - - +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt32 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 4294967295) { + throw new UniFFITypeError(`${value} exceeds the U32 bounds`); + } + } + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint32(value) + } + static read(dataStream) { + return dataStream.readUint32() + } +} // Export the FFIConverter object to make external types work. export class FfiConverterTypeApplicationErrorReporter extends FfiConverter { static lower(callbackObj) { - return callbackHandlerApplicationErrorReporter.storeCallbackObj(callbackObj) + return uniffiCallbackHandlerApplicationErrorReporter.storeCallbackObj(callbackObj) } static lift(handleId) { - return callbackHandlerApplicationErrorReporter.getCallbackObj(handleId) + return uniffiCallbackHandlerApplicationErrorReporter.getCallbackObj(handleId) } static read(dataStream) { @@ -544,12 +589,9 @@ export class FfiConverterTypeApplicationErrorReporter extends FfiConverter { } } - -// Define callback interface handlers, this must come after the type loop since they reference the FfiConverters defined above. - -const callbackHandlerApplicationErrorReporter = new UniFFICallbackHandler( - "errorsupport:ApplicationErrorReporter", - 1, +const uniffiCallbackHandlerApplicationErrorReporter = new UniFFICallbackHandler( + "ApplicationErrorReporter", + 2, [ new UniFFICallbackMethodHandler( "reportError", @@ -563,64 +605,39 @@ const callbackHandlerApplicationErrorReporter = new UniFFICallbackHandler( [ FfiConverterString, FfiConverterString, - FfiConverterU32, - FfiConverterU32, + FfiConverterUInt32, + FfiConverterUInt32, ], ), ] ); // Allow the shutdown-related functionality to be tested in the unit tests -UnitTestObjs.callbackHandlerApplicationErrorReporter = callbackHandlerApplicationErrorReporter; - - - - - -/** - * Set the global error reporter. This is typically done early in startup. - */ -export function setApplicationErrorReporter(errorReporter) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeApplicationErrorReporter.checkType(errorReporter) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("errorReporter"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 4, // errorsupport:uniffi_error_support_fn_func_set_application_error_reporter - FfiConverterTypeApplicationErrorReporter.lower(errorReporter), - ) +UnitTestObjs.uniffiCallbackHandlerApplicationErrorReporter = uniffiCallbackHandlerApplicationErrorReporter; +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * Unset the global error reporter. This is typically done at shutdown for - * platforms that want to cleanup references like Desktop. - */ -export function unsetApplicationErrorReporter() { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 5, // errorsupport:uniffi_error_support_fn_func_unset_application_error_reporter - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRelevancy.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRelevancy.sys.mjs index 3c15b2cd7480..512b581e8d42 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRelevancy.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRelevancy.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,25 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a RelevancyStore pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerRelevancyStore() { - const pointerId = 1; // relevancy:RelevancyStore + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a RelevancyStore pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerRelevancyStore(value) { - const pointerId = 1; // relevancy:RelevancyStore + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -287,104 +282,38 @@ class FfiConverterArrayBuffer extends FfiConverter { const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint32(value) - } - static read(dataStream) { - return dataStream.readUint32() - } +/** + * Calculate score for a piece of categorized content based on a user interest vector. + * + * This scoring function is of the following properties: + * - The score ranges from 0.0 to 1.0 + * - The score is monotonically increasing for the accumulated interest count + * + * # Params: + * - `interest_vector`: a user interest vector that can be fetched via + * `RelevancyStore::user_interest_vector()`. + * - `content_categories`: a list of categories (interests) of the give content. + * # Return: + * - A score ranges in [0, 1]. + */ +export function score( + interestVector, + contentCategories) { + +FfiConverterTypeInterestVector.checkType(interestVector); +FfiConverterSequenceTypeInterest.checkType(contentCategories); +const result = UniFFIScaffolding.callSync( + 7, // uniffi_relevancy_fn_func_score + FfiConverterTypeInterestVector.lower(interestVector), + FfiConverterSequenceTypeInterest.lower(contentCategories), +) +return handleRustResult( + result, + FfiConverterFloat64.lift.bind(FfiConverterFloat64), + null, +) } -// Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint64(value) - } - static read(dataStream) { - return dataStream.readUint64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { @@ -415,382 +344,54 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - -/** - * RelevancyStore - */ -export class RelevancyStore { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * Construct a new RelevancyStore - * - * This is non-blocking since databases and other resources are lazily opened. - * @returns {RelevancyStore} - */ - static init(dbPath,remoteSettings) { - const liftResult = (result) => FfiConverterTypeRelevancyStore.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(dbPath) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("dbPath"); - } - throw e; - } - try { - FfiConverterTypeRemoteSettingsService.checkType(remoteSettings) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("remoteSettings"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 16, // relevancy:uniffi_relevancy_fn_constructor_relevancystore_new - FfiConverterString.lower(dbPath), - FfiConverterTypeRemoteSettingsService.lower(remoteSettings), - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Initializes probability distributions for any uninitialized items (arms) within a bandit model. - * - * This method takes a `bandit` identifier and a list of `arms` (items) and ensures that each arm - * in the list has an initialized probability distribution in the database. For each arm, if the - * probability distribution does not already exist, it will be created, using Beta(1,1) as default, - * which represents uniform distribution. - */ - banditInit(bandit,arms) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(bandit) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("bandit"); - } - throw e; - } - try { - FfiConverterSequencestring.checkType(arms) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("arms"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 7, // relevancy:uniffi_relevancy_fn_method_relevancystore_bandit_init - FfiConverterTypeRelevancyStore.lower(this), - FfiConverterString.lower(bandit), - FfiConverterSequencestring.lower(arms), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Selects the optimal item (arm) to display to the user based on a multi-armed bandit model. - * - * This method takes in a `bandit` identifier and a list of possible `arms` (items) and uses a - * Thompson sampling approach to select the arm with the highest probability of success. - * For each arm, it retrieves the Beta distribution parameters (alpha and beta) from the - * database, creates a Beta distribution, and samples from it to estimate the arm's probability - * of success. The arm with the highest sampled probability is selected and returned. - * @returns {string} - */ - banditSelect(bandit,arms) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(bandit) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("bandit"); - } - throw e; - } - try { - FfiConverterSequencestring.checkType(arms) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("arms"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 8, // relevancy:uniffi_relevancy_fn_method_relevancystore_bandit_select - FfiConverterTypeRelevancyStore.lower(this), - FfiConverterString.lower(bandit), - FfiConverterSequencestring.lower(arms), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Updates the bandit model's arm data based on user interaction (selection or non-selection). - * - * This method takes in a `bandit` identifier, an `arm` identifier, and a `selected` flag. - * If `selected` is true, it updates the model to reflect a successful selection of the arm, - * reinforcing its positive reward probability. If `selected` is false, it updates the - * beta (failure) distribution of the arm, reflecting a lack of selection and reinforcing - * its likelihood of a negative outcome. - */ - banditUpdate(bandit,arm,selected) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(bandit) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("bandit"); - } - throw e; - } - try { - FfiConverterString.checkType(arm) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("arm"); - } - throw e; - } - try { - FfiConverterBool.checkType(selected) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("selected"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 9, // relevancy:uniffi_relevancy_fn_method_relevancystore_bandit_update - FfiConverterTypeRelevancyStore.lower(this), - FfiConverterString.lower(bandit), - FfiConverterString.lower(arm), - FfiConverterBool.lower(selected), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Close any open resources (for example databases) - * - * Calling `close` will interrupt any in-progress queries on other threads. - */ - close() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 10, // relevancy:uniffi_relevancy_fn_method_relevancystore_close - FfiConverterTypeRelevancyStore.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Download the interest data from remote settings if needed - */ - ensureInterestDataPopulated() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 11, // relevancy:uniffi_relevancy_fn_method_relevancystore_ensure_interest_data_populated - FfiConverterTypeRelevancyStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Retrieves the data for a specific bandit and arm. - * @returns {BanditData} - */ - getBanditData(bandit,arm) { - const liftResult = (result) => FfiConverterTypeBanditData.lift(result); - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(bandit) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("bandit"); - } - throw e; - } - try { - FfiConverterString.checkType(arm) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("arm"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 12, // relevancy:uniffi_relevancy_fn_method_relevancystore_get_bandit_data - FfiConverterTypeRelevancyStore.lower(this), - FfiConverterString.lower(bandit), - FfiConverterString.lower(arm), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Ingest top URLs to build the user's interest vector. - * - * Consumer should pass a list of the user's top URLs by frecency to this method. It will - * then: - * - * - Download the URL interest data from remote settings. Eventually this should be cached / - * stored in the database, but for now it would be fine to download fresh data each time. - * - Match the user's top URls against the interest data to build up their interest vector. - * - Store the user's interest vector in the database. - * - * This method may execute for a long time and should only be called from a worker thread. - * @returns {InterestVector} - */ - ingest(topUrlsByFrecency) { - const liftResult = (result) => FfiConverterTypeInterestVector.lift(result); - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - try { - FfiConverterSequencestring.checkType(topUrlsByFrecency) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("topUrlsByFrecency"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 13, // relevancy:uniffi_relevancy_fn_method_relevancystore_ingest - FfiConverterTypeRelevancyStore.lower(this), - FfiConverterSequencestring.lower(topUrlsByFrecency), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Interrupt any current database queries - */ - interrupt() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 14, // relevancy:uniffi_relevancy_fn_method_relevancystore_interrupt - FfiConverterTypeRelevancyStore.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Get the user's interest vector directly. - * - * This runs after [Self::ingest]. It returns the interest vector directly so that the - * consumer can show it in an `about:` page. - * @returns {InterestVector} - */ - userInterestVector() { - const liftResult = (result) => FfiConverterTypeInterestVector.lift(result); - const liftError = (data) => FfiConverterTypeRelevancyApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 15, // relevancy:uniffi_relevancy_fn_method_relevancystore_user_interest_vector - FfiConverterTypeRelevancyStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeRelevancyStore extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new RelevancyStore(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'RelevancyStore' instance"); +export class FfiConverterUInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); } - return ptr; } - - static read(dataStream) { - return this.lift(dataStream.readPointerRelevancyStore()); - } - - static write(dataStream, value) { - dataStream.writePointerRelevancyStore(value[uniffiObjectPtr]); - } - - static computeSize(value) { + static computeSize(_value) { return 8; } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint64(value) + } + static read(dataStream) { + return dataStream.readUint64() + } } - /** * BanditData */ export class BanditData { - constructor({ bandit, arm, impressions, clicks, alpha, beta } = { bandit: undefined, arm: undefined, impressions: undefined, clicks: undefined, alpha: undefined, beta: undefined }) { + constructor( + { + bandit, + arm, + impressions, + clicks, + alpha, + beta + } = { + bandit: undefined, + arm: undefined, + impressions: undefined, + clicks: undefined, + alpha: undefined, + beta: undefined + } + ) { try { FfiConverterString.checkType(bandit) } catch (e) { @@ -808,7 +409,7 @@ export class BanditData { throw e; } try { - FfiConverterU64.checkType(impressions) + FfiConverterUInt64.checkType(impressions) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("impressions"); @@ -816,7 +417,7 @@ export class BanditData { throw e; } try { - FfiConverterU64.checkType(clicks) + FfiConverterUInt64.checkType(clicks) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("clicks"); @@ -824,7 +425,7 @@ export class BanditData { throw e; } try { - FfiConverterU64.checkType(alpha) + FfiConverterUInt64.checkType(alpha) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("alpha"); @@ -832,7 +433,7 @@ export class BanditData { throw e; } try { - FfiConverterU64.checkType(beta) + FfiConverterUInt64.checkType(beta) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("beta"); @@ -840,39 +441,39 @@ export class BanditData { throw e; } /** - * @type {string} + * bandit */ this.bandit = bandit; /** - * @type {string} + * arm */ this.arm = arm; /** - * @type {number} + * impressions */ this.impressions = impressions; /** - * @type {number} + * clicks */ this.clicks = clicks; /** - * @type {number} + * alpha */ this.alpha = alpha; /** - * @type {number} + * beta */ this.beta = beta; } equals(other) { return ( - this.bandit == other.bandit && - this.arm == other.arm && - this.impressions == other.impressions && - this.clicks == other.clicks && - this.alpha == other.alpha && - this.beta == other.beta + this.bandit == other.bandit + && this.arm == other.arm + && this.impressions == other.impressions + && this.clicks == other.clicks + && this.alpha == other.alpha + && this.beta == other.beta ) } } @@ -883,29 +484,29 @@ export class FfiConverterTypeBanditData extends FfiConverterArrayBuffer { return new BanditData({ bandit: FfiConverterString.read(dataStream), arm: FfiConverterString.read(dataStream), - impressions: FfiConverterU64.read(dataStream), - clicks: FfiConverterU64.read(dataStream), - alpha: FfiConverterU64.read(dataStream), - beta: FfiConverterU64.read(dataStream), + impressions: FfiConverterUInt64.read(dataStream), + clicks: FfiConverterUInt64.read(dataStream), + alpha: FfiConverterUInt64.read(dataStream), + beta: FfiConverterUInt64.read(dataStream), }); } static write(dataStream, value) { FfiConverterString.write(dataStream, value.bandit); FfiConverterString.write(dataStream, value.arm); - FfiConverterU64.write(dataStream, value.impressions); - FfiConverterU64.write(dataStream, value.clicks); - FfiConverterU64.write(dataStream, value.alpha); - FfiConverterU64.write(dataStream, value.beta); + FfiConverterUInt64.write(dataStream, value.impressions); + FfiConverterUInt64.write(dataStream, value.clicks); + FfiConverterUInt64.write(dataStream, value.alpha); + FfiConverterUInt64.write(dataStream, value.beta); } static computeSize(value) { let totalSize = 0; totalSize += FfiConverterString.computeSize(value.bandit); totalSize += FfiConverterString.computeSize(value.arm); - totalSize += FfiConverterU64.computeSize(value.impressions); - totalSize += FfiConverterU64.computeSize(value.clicks); - totalSize += FfiConverterU64.computeSize(value.alpha); - totalSize += FfiConverterU64.computeSize(value.beta); + totalSize += FfiConverterUInt64.computeSize(value.impressions); + totalSize += FfiConverterUInt64.computeSize(value.clicks); + totalSize += FfiConverterUInt64.computeSize(value.alpha); + totalSize += FfiConverterUInt64.computeSize(value.beta); return totalSize } @@ -931,7 +532,7 @@ export class FfiConverterTypeBanditData extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU64.checkType(value.impressions); + FfiConverterUInt64.checkType(value.impressions); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".impressions"); @@ -939,7 +540,7 @@ export class FfiConverterTypeBanditData extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU64.checkType(value.clicks); + FfiConverterUInt64.checkType(value.clicks); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".clicks"); @@ -947,7 +548,7 @@ export class FfiConverterTypeBanditData extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU64.checkType(value.alpha); + FfiConverterUInt64.checkType(value.alpha); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".alpha"); @@ -955,7 +556,7 @@ export class FfiConverterTypeBanditData extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU64.checkType(value.beta); + FfiConverterUInt64.checkType(value.beta); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".beta"); @@ -964,23 +565,59 @@ export class FfiConverterTypeBanditData extends FfiConverterArrayBuffer { } } } - +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt32 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 4294967295) { + throw new UniFFITypeError(`${value} exceeds the U32 bounds`); + } + } + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint32(value) + } + static read(dataStream) { + return dataStream.readUint32() + } +} /** * Interest metrics that we want to send to Glean as part of the validation process. These contain * the cosine similarity when comparing the user's interest against various interest vectors that * consumers may use. - * + * * Cosine similarly was chosen because it seems easy to calculate. This was then matched against * some semi-plausible real-world interest vectors that consumers might use. This is all up for * debate and we may decide to switch to some other metrics. - * + * * Similarity values are transformed to integers by multiplying the floating point value by 1000 and * rounding. This is to make them compatible with Glean's distribution metrics. */ export class InterestMetrics { - constructor({ topSingleInterestSimilarity, top2interestSimilarity, top3interestSimilarity } = { topSingleInterestSimilarity: undefined, top2interestSimilarity: undefined, top3interestSimilarity: undefined }) { + constructor( + { + topSingleInterestSimilarity, + top2interestSimilarity, + top3interestSimilarity + } = { + topSingleInterestSimilarity: undefined, + top2interestSimilarity: undefined, + top3interestSimilarity: undefined + } + ) { try { - FfiConverterU32.checkType(topSingleInterestSimilarity) + FfiConverterUInt32.checkType(topSingleInterestSimilarity) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("topSingleInterestSimilarity"); @@ -988,7 +625,7 @@ export class InterestMetrics { throw e; } try { - FfiConverterU32.checkType(top2interestSimilarity) + FfiConverterUInt32.checkType(top2interestSimilarity) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("top2interestSimilarity"); @@ -996,7 +633,7 @@ export class InterestMetrics { throw e; } try { - FfiConverterU32.checkType(top3interestSimilarity) + FfiConverterUInt32.checkType(top3interestSimilarity) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("top3interestSimilarity"); @@ -1008,7 +645,6 @@ export class InterestMetrics { * the user's top interest is copied, but all other interests are set to zero. This measures * the highest possible similarity with consumers that used interest vectors with a single * interest set. - * @type {number} */ this.topSingleInterestSimilarity = topSingleInterestSimilarity; /** @@ -1016,21 +652,19 @@ export class InterestMetrics { * similarity with consumers that used interest vectors with a two interests (note: this means * they would need to choose the user's top two interests and have the exact same proportion * between them as the user). - * @type {number} */ this.top2interestSimilarity = top2interestSimilarity; /** * The same as before, but the top 3 interests are copied. - * @type {number} */ this.top3interestSimilarity = top3interestSimilarity; } equals(other) { return ( - this.topSingleInterestSimilarity == other.topSingleInterestSimilarity && - this.top2interestSimilarity == other.top2interestSimilarity && - this.top3interestSimilarity == other.top3interestSimilarity + this.topSingleInterestSimilarity == other.topSingleInterestSimilarity + && this.top2interestSimilarity == other.top2interestSimilarity + && this.top3interestSimilarity == other.top3interestSimilarity ) } } @@ -1039,22 +673,22 @@ export class InterestMetrics { export class FfiConverterTypeInterestMetrics extends FfiConverterArrayBuffer { static read(dataStream) { return new InterestMetrics({ - topSingleInterestSimilarity: FfiConverterU32.read(dataStream), - top2interestSimilarity: FfiConverterU32.read(dataStream), - top3interestSimilarity: FfiConverterU32.read(dataStream), + topSingleInterestSimilarity: FfiConverterUInt32.read(dataStream), + top2interestSimilarity: FfiConverterUInt32.read(dataStream), + top3interestSimilarity: FfiConverterUInt32.read(dataStream), }); } static write(dataStream, value) { - FfiConverterU32.write(dataStream, value.topSingleInterestSimilarity); - FfiConverterU32.write(dataStream, value.top2interestSimilarity); - FfiConverterU32.write(dataStream, value.top3interestSimilarity); + FfiConverterUInt32.write(dataStream, value.topSingleInterestSimilarity); + FfiConverterUInt32.write(dataStream, value.top2interestSimilarity); + FfiConverterUInt32.write(dataStream, value.top3interestSimilarity); } static computeSize(value) { let totalSize = 0; - totalSize += FfiConverterU32.computeSize(value.topSingleInterestSimilarity); - totalSize += FfiConverterU32.computeSize(value.top2interestSimilarity); - totalSize += FfiConverterU32.computeSize(value.top3interestSimilarity); + totalSize += FfiConverterUInt32.computeSize(value.topSingleInterestSimilarity); + totalSize += FfiConverterUInt32.computeSize(value.top2interestSimilarity); + totalSize += FfiConverterUInt32.computeSize(value.top3interestSimilarity); return totalSize } @@ -1064,7 +698,7 @@ export class FfiConverterTypeInterestMetrics extends FfiConverterArrayBuffer { throw new UniFFITypeError(`Expected 'InterestMetrics', found '${typeof value}'`); } try { - FfiConverterU32.checkType(value.topSingleInterestSimilarity); + FfiConverterUInt32.checkType(value.topSingleInterestSimilarity); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".topSingleInterestSimilarity"); @@ -1072,7 +706,7 @@ export class FfiConverterTypeInterestMetrics extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.top2interestSimilarity); + FfiConverterUInt32.checkType(value.top2interestSimilarity); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".top2interestSimilarity"); @@ -1080,7 +714,7 @@ export class FfiConverterTypeInterestMetrics extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.top3interestSimilarity); + FfiConverterUInt32.checkType(value.top3interestSimilarity); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".top3interestSimilarity"); @@ -1089,17 +723,58 @@ export class FfiConverterTypeInterestMetrics extends FfiConverterArrayBuffer { } } } - /** * Vector storing a count value for each interest - * + * * Here "vector" refers to the mathematical object, not a Rust `Vec`. It always has a fixed * number of elements. */ export class InterestVector { - constructor({ inconclusive, animals, arts, autos, business, career, education, fashion, finance, food, government, hobbies, home, news, realEstate, society, sports, tech, travel } = { inconclusive: undefined, animals: undefined, arts: undefined, autos: undefined, business: undefined, career: undefined, education: undefined, fashion: undefined, finance: undefined, food: undefined, government: undefined, hobbies: undefined, home: undefined, news: undefined, realEstate: undefined, society: undefined, sports: undefined, tech: undefined, travel: undefined }) { + constructor( + { + inconclusive, + animals, + arts, + autos, + business, + career, + education, + fashion, + finance, + food, + government, + hobbies, + home, + news, + realEstate, + society, + sports, + tech, + travel + } = { + inconclusive: undefined, + animals: undefined, + arts: undefined, + autos: undefined, + business: undefined, + career: undefined, + education: undefined, + fashion: undefined, + finance: undefined, + food: undefined, + government: undefined, + hobbies: undefined, + home: undefined, + news: undefined, + realEstate: undefined, + society: undefined, + sports: undefined, + tech: undefined, + travel: undefined + } + ) { try { - FfiConverterU32.checkType(inconclusive) + FfiConverterUInt32.checkType(inconclusive) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("inconclusive"); @@ -1107,7 +782,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(animals) + FfiConverterUInt32.checkType(animals) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("animals"); @@ -1115,7 +790,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(arts) + FfiConverterUInt32.checkType(arts) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("arts"); @@ -1123,7 +798,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(autos) + FfiConverterUInt32.checkType(autos) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("autos"); @@ -1131,7 +806,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(business) + FfiConverterUInt32.checkType(business) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("business"); @@ -1139,7 +814,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(career) + FfiConverterUInt32.checkType(career) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("career"); @@ -1147,7 +822,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(education) + FfiConverterUInt32.checkType(education) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("education"); @@ -1155,7 +830,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(fashion) + FfiConverterUInt32.checkType(fashion) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("fashion"); @@ -1163,7 +838,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(finance) + FfiConverterUInt32.checkType(finance) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("finance"); @@ -1171,7 +846,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(food) + FfiConverterUInt32.checkType(food) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("food"); @@ -1179,7 +854,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(government) + FfiConverterUInt32.checkType(government) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("government"); @@ -1187,7 +862,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(hobbies) + FfiConverterUInt32.checkType(hobbies) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("hobbies"); @@ -1195,7 +870,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(home) + FfiConverterUInt32.checkType(home) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("home"); @@ -1203,7 +878,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(news) + FfiConverterUInt32.checkType(news) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("news"); @@ -1211,7 +886,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(realEstate) + FfiConverterUInt32.checkType(realEstate) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("realEstate"); @@ -1219,7 +894,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(society) + FfiConverterUInt32.checkType(society) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("society"); @@ -1227,7 +902,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(sports) + FfiConverterUInt32.checkType(sports) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("sports"); @@ -1235,7 +910,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(tech) + FfiConverterUInt32.checkType(tech) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("tech"); @@ -1243,7 +918,7 @@ export class InterestVector { throw e; } try { - FfiConverterU32.checkType(travel) + FfiConverterUInt32.checkType(travel) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("travel"); @@ -1251,104 +926,104 @@ export class InterestVector { throw e; } /** - * @type {number} + * inconclusive */ this.inconclusive = inconclusive; /** - * @type {number} + * animals */ this.animals = animals; /** - * @type {number} + * arts */ this.arts = arts; /** - * @type {number} + * autos */ this.autos = autos; /** - * @type {number} + * business */ this.business = business; /** - * @type {number} + * career */ this.career = career; /** - * @type {number} + * education */ this.education = education; /** - * @type {number} + * fashion */ this.fashion = fashion; /** - * @type {number} + * finance */ this.finance = finance; /** - * @type {number} + * food */ this.food = food; /** - * @type {number} + * government */ this.government = government; /** - * @type {number} + * hobbies */ this.hobbies = hobbies; /** - * @type {number} + * home */ this.home = home; /** - * @type {number} + * news */ this.news = news; /** - * @type {number} + * realEstate */ this.realEstate = realEstate; /** - * @type {number} + * society */ this.society = society; /** - * @type {number} + * sports */ this.sports = sports; /** - * @type {number} + * tech */ this.tech = tech; /** - * @type {number} + * travel */ this.travel = travel; } equals(other) { return ( - this.inconclusive == other.inconclusive && - this.animals == other.animals && - this.arts == other.arts && - this.autos == other.autos && - this.business == other.business && - this.career == other.career && - this.education == other.education && - this.fashion == other.fashion && - this.finance == other.finance && - this.food == other.food && - this.government == other.government && - this.hobbies == other.hobbies && - this.home == other.home && - this.news == other.news && - this.realEstate == other.realEstate && - this.society == other.society && - this.sports == other.sports && - this.tech == other.tech && - this.travel == other.travel + this.inconclusive == other.inconclusive + && this.animals == other.animals + && this.arts == other.arts + && this.autos == other.autos + && this.business == other.business + && this.career == other.career + && this.education == other.education + && this.fashion == other.fashion + && this.finance == other.finance + && this.food == other.food + && this.government == other.government + && this.hobbies == other.hobbies + && this.home == other.home + && this.news == other.news + && this.realEstate == other.realEstate + && this.society == other.society + && this.sports == other.sports + && this.tech == other.tech + && this.travel == other.travel ) } } @@ -1357,70 +1032,70 @@ export class InterestVector { export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { static read(dataStream) { return new InterestVector({ - inconclusive: FfiConverterU32.read(dataStream), - animals: FfiConverterU32.read(dataStream), - arts: FfiConverterU32.read(dataStream), - autos: FfiConverterU32.read(dataStream), - business: FfiConverterU32.read(dataStream), - career: FfiConverterU32.read(dataStream), - education: FfiConverterU32.read(dataStream), - fashion: FfiConverterU32.read(dataStream), - finance: FfiConverterU32.read(dataStream), - food: FfiConverterU32.read(dataStream), - government: FfiConverterU32.read(dataStream), - hobbies: FfiConverterU32.read(dataStream), - home: FfiConverterU32.read(dataStream), - news: FfiConverterU32.read(dataStream), - realEstate: FfiConverterU32.read(dataStream), - society: FfiConverterU32.read(dataStream), - sports: FfiConverterU32.read(dataStream), - tech: FfiConverterU32.read(dataStream), - travel: FfiConverterU32.read(dataStream), + inconclusive: FfiConverterUInt32.read(dataStream), + animals: FfiConverterUInt32.read(dataStream), + arts: FfiConverterUInt32.read(dataStream), + autos: FfiConverterUInt32.read(dataStream), + business: FfiConverterUInt32.read(dataStream), + career: FfiConverterUInt32.read(dataStream), + education: FfiConverterUInt32.read(dataStream), + fashion: FfiConverterUInt32.read(dataStream), + finance: FfiConverterUInt32.read(dataStream), + food: FfiConverterUInt32.read(dataStream), + government: FfiConverterUInt32.read(dataStream), + hobbies: FfiConverterUInt32.read(dataStream), + home: FfiConverterUInt32.read(dataStream), + news: FfiConverterUInt32.read(dataStream), + realEstate: FfiConverterUInt32.read(dataStream), + society: FfiConverterUInt32.read(dataStream), + sports: FfiConverterUInt32.read(dataStream), + tech: FfiConverterUInt32.read(dataStream), + travel: FfiConverterUInt32.read(dataStream), }); } static write(dataStream, value) { - FfiConverterU32.write(dataStream, value.inconclusive); - FfiConverterU32.write(dataStream, value.animals); - FfiConverterU32.write(dataStream, value.arts); - FfiConverterU32.write(dataStream, value.autos); - FfiConverterU32.write(dataStream, value.business); - FfiConverterU32.write(dataStream, value.career); - FfiConverterU32.write(dataStream, value.education); - FfiConverterU32.write(dataStream, value.fashion); - FfiConverterU32.write(dataStream, value.finance); - FfiConverterU32.write(dataStream, value.food); - FfiConverterU32.write(dataStream, value.government); - FfiConverterU32.write(dataStream, value.hobbies); - FfiConverterU32.write(dataStream, value.home); - FfiConverterU32.write(dataStream, value.news); - FfiConverterU32.write(dataStream, value.realEstate); - FfiConverterU32.write(dataStream, value.society); - FfiConverterU32.write(dataStream, value.sports); - FfiConverterU32.write(dataStream, value.tech); - FfiConverterU32.write(dataStream, value.travel); + FfiConverterUInt32.write(dataStream, value.inconclusive); + FfiConverterUInt32.write(dataStream, value.animals); + FfiConverterUInt32.write(dataStream, value.arts); + FfiConverterUInt32.write(dataStream, value.autos); + FfiConverterUInt32.write(dataStream, value.business); + FfiConverterUInt32.write(dataStream, value.career); + FfiConverterUInt32.write(dataStream, value.education); + FfiConverterUInt32.write(dataStream, value.fashion); + FfiConverterUInt32.write(dataStream, value.finance); + FfiConverterUInt32.write(dataStream, value.food); + FfiConverterUInt32.write(dataStream, value.government); + FfiConverterUInt32.write(dataStream, value.hobbies); + FfiConverterUInt32.write(dataStream, value.home); + FfiConverterUInt32.write(dataStream, value.news); + FfiConverterUInt32.write(dataStream, value.realEstate); + FfiConverterUInt32.write(dataStream, value.society); + FfiConverterUInt32.write(dataStream, value.sports); + FfiConverterUInt32.write(dataStream, value.tech); + FfiConverterUInt32.write(dataStream, value.travel); } static computeSize(value) { let totalSize = 0; - totalSize += FfiConverterU32.computeSize(value.inconclusive); - totalSize += FfiConverterU32.computeSize(value.animals); - totalSize += FfiConverterU32.computeSize(value.arts); - totalSize += FfiConverterU32.computeSize(value.autos); - totalSize += FfiConverterU32.computeSize(value.business); - totalSize += FfiConverterU32.computeSize(value.career); - totalSize += FfiConverterU32.computeSize(value.education); - totalSize += FfiConverterU32.computeSize(value.fashion); - totalSize += FfiConverterU32.computeSize(value.finance); - totalSize += FfiConverterU32.computeSize(value.food); - totalSize += FfiConverterU32.computeSize(value.government); - totalSize += FfiConverterU32.computeSize(value.hobbies); - totalSize += FfiConverterU32.computeSize(value.home); - totalSize += FfiConverterU32.computeSize(value.news); - totalSize += FfiConverterU32.computeSize(value.realEstate); - totalSize += FfiConverterU32.computeSize(value.society); - totalSize += FfiConverterU32.computeSize(value.sports); - totalSize += FfiConverterU32.computeSize(value.tech); - totalSize += FfiConverterU32.computeSize(value.travel); + totalSize += FfiConverterUInt32.computeSize(value.inconclusive); + totalSize += FfiConverterUInt32.computeSize(value.animals); + totalSize += FfiConverterUInt32.computeSize(value.arts); + totalSize += FfiConverterUInt32.computeSize(value.autos); + totalSize += FfiConverterUInt32.computeSize(value.business); + totalSize += FfiConverterUInt32.computeSize(value.career); + totalSize += FfiConverterUInt32.computeSize(value.education); + totalSize += FfiConverterUInt32.computeSize(value.fashion); + totalSize += FfiConverterUInt32.computeSize(value.finance); + totalSize += FfiConverterUInt32.computeSize(value.food); + totalSize += FfiConverterUInt32.computeSize(value.government); + totalSize += FfiConverterUInt32.computeSize(value.hobbies); + totalSize += FfiConverterUInt32.computeSize(value.home); + totalSize += FfiConverterUInt32.computeSize(value.news); + totalSize += FfiConverterUInt32.computeSize(value.realEstate); + totalSize += FfiConverterUInt32.computeSize(value.society); + totalSize += FfiConverterUInt32.computeSize(value.sports); + totalSize += FfiConverterUInt32.computeSize(value.tech); + totalSize += FfiConverterUInt32.computeSize(value.travel); return totalSize } @@ -1430,7 +1105,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw new UniFFITypeError(`Expected 'InterestVector', found '${typeof value}'`); } try { - FfiConverterU32.checkType(value.inconclusive); + FfiConverterUInt32.checkType(value.inconclusive); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".inconclusive"); @@ -1438,7 +1113,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.animals); + FfiConverterUInt32.checkType(value.animals); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".animals"); @@ -1446,7 +1121,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.arts); + FfiConverterUInt32.checkType(value.arts); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".arts"); @@ -1454,7 +1129,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.autos); + FfiConverterUInt32.checkType(value.autos); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".autos"); @@ -1462,7 +1137,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.business); + FfiConverterUInt32.checkType(value.business); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".business"); @@ -1470,7 +1145,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.career); + FfiConverterUInt32.checkType(value.career); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".career"); @@ -1478,7 +1153,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.education); + FfiConverterUInt32.checkType(value.education); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".education"); @@ -1486,7 +1161,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.fashion); + FfiConverterUInt32.checkType(value.fashion); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".fashion"); @@ -1494,7 +1169,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.finance); + FfiConverterUInt32.checkType(value.finance); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".finance"); @@ -1502,7 +1177,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.food); + FfiConverterUInt32.checkType(value.food); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".food"); @@ -1510,7 +1185,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.government); + FfiConverterUInt32.checkType(value.government); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".government"); @@ -1518,7 +1193,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.hobbies); + FfiConverterUInt32.checkType(value.hobbies); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".hobbies"); @@ -1526,7 +1201,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.home); + FfiConverterUInt32.checkType(value.home); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".home"); @@ -1534,7 +1209,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.news); + FfiConverterUInt32.checkType(value.news); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".news"); @@ -1542,7 +1217,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.realEstate); + FfiConverterUInt32.checkType(value.realEstate); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".realEstate"); @@ -1550,7 +1225,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.society); + FfiConverterUInt32.checkType(value.society); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".society"); @@ -1558,7 +1233,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.sports); + FfiConverterUInt32.checkType(value.sports); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".sports"); @@ -1566,7 +1241,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.tech); + FfiConverterUInt32.checkType(value.tech); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".tech"); @@ -1574,7 +1249,7 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU32.checkType(value.travel); + FfiConverterUInt32.checkType(value.travel); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".travel"); @@ -1584,7 +1259,6 @@ export class FfiConverterTypeInterestVector extends FfiConverterArrayBuffer { } } - /** * List of possible interests for a domain. Domains can have be associated with one or multiple * interests. `Inconclusive` is used for domains in the user's top sites that we can't classify @@ -1594,88 +1268,85 @@ export const Interest = { /** * INCONCLUSIVE */ - INCONCLUSIVE:0, + INCONCLUSIVE: 1, /** * ANIMALS */ - ANIMALS:1, + ANIMALS: 2, /** * ARTS */ - ARTS:2, + ARTS: 3, /** * AUTOS */ - AUTOS:3, + AUTOS: 4, /** * BUSINESS */ - BUSINESS:4, + BUSINESS: 5, /** * CAREER */ - CAREER:5, + CAREER: 6, /** * EDUCATION */ - EDUCATION:6, + EDUCATION: 7, /** * FASHION */ - FASHION:7, + FASHION: 8, /** * FINANCE */ - FINANCE:8, + FINANCE: 9, /** * FOOD */ - FOOD:9, + FOOD: 10, /** * GOVERNMENT */ - GOVERNMENT:10, + GOVERNMENT: 11, /** * HOBBIES */ - HOBBIES:12, + HOBBIES: 12, /** * HOME */ - HOME:13, + HOME: 13, /** * NEWS */ - NEWS:14, + NEWS: 14, /** * REAL_ESTATE */ - REAL_ESTATE:15, + REAL_ESTATE: 15, /** * SOCIETY */ - SOCIETY:16, + SOCIETY: 16, /** * SPORTS */ - SPORTS:17, + SPORTS: 17, /** * TECH */ - TECH:18, + TECH: 18, /** * TRAVEL */ - TRAVEL:19, + TRAVEL: 19, }; - Object.freeze(Interest); + // Export the FFIConverter object to make external types work. export class FfiConverterTypeInterest extends FfiConverterArrayBuffer { - static #validValues = Object.values(Interest); - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { case 1: return Interest.INCONCLUSIVE @@ -1805,17 +1476,12 @@ export class FfiConverterTypeInterest extends FfiConverterArrayBuffer { } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { + if (!Number.isInteger(value) || value < 1 || value > 19) { throw new UniFFITypeError(`${value} is not a valid value for Interest`); } } } - - - - /** * Errors we return via the public interface. */ @@ -1872,9 +1538,8 @@ export class FfiConverterTypeRelevancyApiError extends FfiConverterArrayBuffer { static errorClass = RelevancyApiError; } - // Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { +export class FfiConverterSequenceString extends FfiConverterArrayBuffer { static read(dataStream) { const len = dataStream.readInt32(); const arr = []; @@ -1916,7 +1581,299 @@ export class FfiConverterSequencestring extends FfiConverterArrayBuffer { }) } } +// Export the FFIConverter object to make external types work. +export class FfiConverterBoolean extends FfiConverter { + static computeSize(_value) { + return 1; + } + static lift(value) { + return value == 1; + } + static lower(value) { + if (value) { + return 1; + } else { + return 0; + } + } + static write(dataStream, value) { + dataStream.writeUint8(this.lower(value)) + } + static read(dataStream) { + return this.lift(dataStream.readUint8()) + } +} +/** + * RelevancyStore + */ +export class RelevancyStore { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + dbPath, + remoteSettings) { + + FfiConverterString.checkType(dbPath); + FfiConverterTypeRemoteSettingsService.checkType(remoteSettings); + const result = UniFFIScaffolding.callSync( + 8, // uniffi_relevancy_fn_constructor_relevancystore_new + FfiConverterString.lower(dbPath), + FfiConverterTypeRemoteSettingsService.lower(remoteSettings), + ) + return handleRustResult( + result, + FfiConverterTypeRelevancyStore.lift.bind(FfiConverterTypeRelevancyStore), + null, + ) + } + /** + * Initializes probability distributions for any uninitialized items (arms) within a bandit model. + * + * This method takes a `bandit` identifier and a list of `arms` (items) and ensures that each arm + * in the list has an initialized probability distribution in the database. For each arm, if the + * probability distribution does not already exist, it will be created, using Beta(1,1) as default, + * which represents uniform distribution. + */ + async banditInit( + bandit, + arms) { + + FfiConverterString.checkType(bandit); + FfiConverterSequenceString.checkType(arms); + const result = await UniFFIScaffolding.callAsyncWrapper( + 9, // uniffi_relevancy_fn_method_relevancystore_bandit_init + FfiConverterTypeRelevancyStore.lower(this), + FfiConverterString.lower(bandit), + FfiConverterSequenceString.lower(arms), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + + /** + * Selects the optimal item (arm) to display to the user based on a multi-armed bandit model. + * + * This method takes in a `bandit` identifier and a list of possible `arms` (items) and uses a + * Thompson sampling approach to select the arm with the highest probability of success. + * For each arm, it retrieves the Beta distribution parameters (alpha and beta) from the + * database, creates a Beta distribution, and samples from it to estimate the arm's probability + * of success. The arm with the highest sampled probability is selected and returned. + */ + async banditSelect( + bandit, + arms) { + + FfiConverterString.checkType(bandit); + FfiConverterSequenceString.checkType(arms); + const result = await UniFFIScaffolding.callAsyncWrapper( + 10, // uniffi_relevancy_fn_method_relevancystore_bandit_select + FfiConverterTypeRelevancyStore.lower(this), + FfiConverterString.lower(bandit), + FfiConverterSequenceString.lower(arms), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + + /** + * Updates the bandit model's arm data based on user interaction (selection or non-selection). + * + * This method takes in a `bandit` identifier, an `arm` identifier, and a `selected` flag. + * If `selected` is true, it updates the model to reflect a successful selection of the arm, + * reinforcing its positive reward probability. If `selected` is false, it updates the + * beta (failure) distribution of the arm, reflecting a lack of selection and reinforcing + * its likelihood of a negative outcome. + */ + async banditUpdate( + bandit, + arm, + selected) { + + FfiConverterString.checkType(bandit); + FfiConverterString.checkType(arm); + FfiConverterBoolean.checkType(selected); + const result = await UniFFIScaffolding.callAsyncWrapper( + 11, // uniffi_relevancy_fn_method_relevancystore_bandit_update + FfiConverterTypeRelevancyStore.lower(this), + FfiConverterString.lower(bandit), + FfiConverterString.lower(arm), + FfiConverterBoolean.lower(selected), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + + /** + * Close any open resources (for example databases) + * + * Calling `close` will interrupt any in-progress queries on other threads. + */ + close() { + + const result = UniFFIScaffolding.callSync( + 12, // uniffi_relevancy_fn_method_relevancystore_close + FfiConverterTypeRelevancyStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + + /** + * Download the interest data from remote settings if needed + */ + async ensureInterestDataPopulated() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 13, // uniffi_relevancy_fn_method_relevancystore_ensure_interest_data_populated + FfiConverterTypeRelevancyStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + + /** + * Retrieves the data for a specific bandit and arm. + */ + async getBanditData( + bandit, + arm) { + + FfiConverterString.checkType(bandit); + FfiConverterString.checkType(arm); + const result = await UniFFIScaffolding.callAsyncWrapper( + 14, // uniffi_relevancy_fn_method_relevancystore_get_bandit_data + FfiConverterTypeRelevancyStore.lower(this), + FfiConverterString.lower(bandit), + FfiConverterString.lower(arm), + ) + return handleRustResult( + result, + FfiConverterTypeBanditData.lift.bind(FfiConverterTypeBanditData), + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + + /** + * Ingest top URLs to build the user's interest vector. + * + * Consumer should pass a list of the user's top URLs by frecency to this method. It will + * then: + * + * - Download the URL interest data from remote settings. Eventually this should be cached / + * stored in the database, but for now it would be fine to download fresh data each time. + * - Match the user's top URls against the interest data to build up their interest vector. + * - Store the user's interest vector in the database. + * + * This method may execute for a long time and should only be called from a worker thread. + */ + async ingest( + topUrlsByFrecency) { + + FfiConverterSequenceString.checkType(topUrlsByFrecency); + const result = await UniFFIScaffolding.callAsyncWrapper( + 15, // uniffi_relevancy_fn_method_relevancystore_ingest + FfiConverterTypeRelevancyStore.lower(this), + FfiConverterSequenceString.lower(topUrlsByFrecency), + ) + return handleRustResult( + result, + FfiConverterTypeInterestVector.lift.bind(FfiConverterTypeInterestVector), + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + + /** + * Interrupt any current database queries + */ + interrupt() { + + const result = UniFFIScaffolding.callSync( + 16, // uniffi_relevancy_fn_method_relevancystore_interrupt + FfiConverterTypeRelevancyStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + + /** + * Get the user's interest vector directly. + * + * This runs after [Self::ingest]. It returns the interest vector directly so that the + * consumer can show it in an `about:` page. + */ + async userInterestVector() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 17, // uniffi_relevancy_fn_method_relevancystore_user_interest_vector + FfiConverterTypeRelevancyStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeInterestVector.lift.bind(FfiConverterTypeInterestVector), + FfiConverterTypeRelevancyApiError.lift.bind(FfiConverterTypeRelevancyApiError), + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRelevancyStore extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new RelevancyStore(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'RelevancyStore' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(2)); + } + + static write(dataStream, value) { + dataStream.writePointer(2, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} // Export the FFIConverter object to make external types work. export class FfiConverterSequenceTypeInterest extends FfiConverterArrayBuffer { static read(dataStream) { @@ -1960,58 +1917,54 @@ export class FfiConverterSequenceTypeInterest extends FfiConverterArrayBuffer { }) } } - +// Export the FFIConverter object to make external types work. +export class FfiConverterFloat64 extends FfiConverter { + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeFloat64(value) + } + static read(dataStream) { + return dataStream.readFloat64() + } +} import { FfiConverterTypeRemoteSettingsService, - RemoteSettingsService, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs"; +} from "./RustRemoteSettings.sys.mjs"; // Export the FFIConverter object to make external types work. -export { FfiConverterTypeRemoteSettingsService, RemoteSettingsService }; - - - -/** - * Calculate score for a piece of categorized content based on a user interest vector. - * - * This scoring function is of the following properties: - * - The score ranges from 0.0 to 1.0 - * - The score is monotonically increasing for the accumulated interest count - * - * # Params: - * - `interest_vector`: a user interest vector that can be fetched via - * `RelevancyStore::user_interest_vector()`. - * - `content_categories`: a list of categories (interests) of the give content. - * # Return: - * - A score ranges in [0, 1]. - * @returns {number} - */ -export function score(interestVector,contentCategories) { - - const liftResult = (result) => FfiConverterF64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeInterestVector.checkType(interestVector) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("interestVector"); - } - throw e; - } - try { - FfiConverterSequenceTypeInterest.checkType(contentCategories) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("contentCategories"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 6, // relevancy:uniffi_relevancy_fn_func_score - FfiConverterTypeInterestVector.lower(interestVector), - FfiConverterSequenceTypeInterest.lower(contentCategories), - ) +export { FfiConverterTypeRemoteSettingsService }; +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); } - return handleRustResult(functionCall(), liftResult, liftError); + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs index 0859dfbdf5bc..a0fdef2c466d 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,65 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a RemoteSettings pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerRemoteSettings() { - const pointerId = 2; // remote_settings:RemoteSettings + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a RemoteSettings pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerRemoteSettings(value) { - const pointerId = 2; // remote_settings:RemoteSettings + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - - - // Reads a RemoteSettingsClient pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerRemoteSettingsClient() { - const pointerId = 3; // remote_settings:RemoteSettingsClient - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a RemoteSettingsClient pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerRemoteSettingsClient(value) { - const pointerId = 3; // remote_settings:RemoteSettingsClient - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a RemoteSettingsService pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerRemoteSettingsService() { - const pointerId = 4; // remote_settings:RemoteSettingsService - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a RemoteSettingsService pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerRemoteSettingsService(value) { - const pointerId = 4; // remote_settings:RemoteSettingsService - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -328,57 +283,6 @@ const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; -// Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint64(value) - } - static read(dataStream) { - return dataStream.readUint64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -408,589 +312,53 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - // Export the FFIConverter object to make external types work. -export class FfiConverterBytes extends FfiConverterArrayBuffer { - static read(dataStream) { - return dataStream.readBytes() - } - - static write(dataStream, value) { - dataStream.writeBytes(value) - } - - static computeSize(value) { - // The size of the length + 1 byte / item - return 4 + value.length - } - +export class FfiConverterUInt64 extends FfiConverter { static checkType(value) { - if (!value instanceof Uint8Array) { - throw new UniFFITypeError(`${value} is not an Uint8Array`); + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); } } -} - -/** - * RemoteSettings - */ -export class RemoteSettings { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * Construct a new Remote Settings client with the given configuration. - * @returns {RemoteSettings} - */ - static init(remoteSettingsConfig) { - const liftResult = (result) => FfiConverterTypeRemoteSettings.lift(result); - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeRemoteSettingsConfig.checkType(remoteSettingsConfig) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("remoteSettingsConfig"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 20, // remote_settings:uniffi_remote_settings_fn_constructor_remotesettings_new - FfiConverterTypeRemoteSettingsConfig.lower(remoteSettingsConfig), - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Download an attachment with the provided id to the provided path. - */ - downloadAttachmentToPath(attachmentId,path) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(attachmentId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("attachmentId"); - } - throw e; - } - try { - FfiConverterString.checkType(path) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("path"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 17, // remote_settings:uniffi_remote_settings_fn_method_remotesettings_download_attachment_to_path - FfiConverterTypeRemoteSettings.lower(this), - FfiConverterString.lower(attachmentId), - FfiConverterString.lower(path), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Fetch all records for the configuration this client was initialized with. - * @returns {RemoteSettingsResponse} - */ - getRecords() { - const liftResult = (result) => FfiConverterTypeRemoteSettingsResponse.lift(result); - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 18, // remote_settings:uniffi_remote_settings_fn_method_remotesettings_get_records - FfiConverterTypeRemoteSettings.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Fetch all records added to the server since the provided timestamp, - * using the configuration this client was initialized with. - * @returns {RemoteSettingsResponse} - */ - getRecordsSince(timestamp) { - const liftResult = (result) => FfiConverterTypeRemoteSettingsResponse.lift(result); - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - try { - FfiConverterU64.checkType(timestamp) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("timestamp"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 19, // remote_settings:uniffi_remote_settings_fn_method_remotesettings_get_records_since - FfiConverterTypeRemoteSettings.lower(this), - FfiConverterU64.lower(timestamp), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteSettings extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new RemoteSettings(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'RemoteSettings' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerRemoteSettings()); - } - - static write(dataStream, value) { - dataStream.writePointerRemoteSettings(value[uniffiObjectPtr]); - } - - static computeSize(value) { + static computeSize(_value) { return 8; } -} - -/** - * Client for a single Remote Settings collection - * - * Use [RemoteSettingsService::make_client] to create these. - */ -export class RemoteSettingsClient { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * Collection this client is for - * @returns {string} - */ - collectionName() { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 21, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsclient_collection_name - FfiConverterTypeRemoteSettingsClient.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Get attachment data for a remote settings record - * - * Attachments are large binary blobs used for data that doesn't fit in a normal record. They - * are handled differently than other record data: - * - * - Attachments are not downloaded in [RemoteSettingsService::sync] - * - This method will make network requests if the attachment is not cached - * - This method will throw if there is a network or other error when fetching the - * attachment data. - * @returns {string} - */ - getAttachment(record) { - const liftResult = (result) => FfiConverterBytes.lift(result); - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeRemoteSettingsRecord.checkType(record) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("record"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 22, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsclient_get_attachment - FfiConverterTypeRemoteSettingsClient.lower(this), - FfiConverterTypeRemoteSettingsRecord.lower(record), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Get the current set of records. - * - * This method normally fetches records from the last sync. This means that it returns fast - * and does not make any network requests. - * - * If records have not yet been synced it will return None. Use `sync_if_empty = true` to - * change this behavior and perform a network request in this case. That this is probably a - * bad idea if you want to fetch the setting in application startup or when building the UI. - * - * None will also be returned on disk IO errors or other unexpected errors. The reason for - * this is that there is not much an application can do in this situation other than fall back - * to the same default handling as if records have not been synced. - * - * Application-services schedules regular dumps of the server data for specific collections. - * For these collections, `get_records` will never return None. If you would like to add your - * collection to this list, please reach out to the DISCO team. - * @returns {?Array.} - */ - getRecords(syncIfEmpty = false) { - const liftResult = (result) => FfiConverterOptionalSequenceTypeRemoteSettingsRecord.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterBool.checkType(syncIfEmpty) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("syncIfEmpty"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 23, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsclient_get_records - FfiConverterTypeRemoteSettingsClient.lower(this), - FfiConverterBool.lower(syncIfEmpty), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Get the current set of records as a map of record_id -> record. - * - * See [Self::get_records] for an explanation of when this makes network requests, error - * handling, and how the `sync_if_empty` param works. - * @returns {?object} - */ - getRecordsMap(syncIfEmpty = false) { - const liftResult = (result) => FfiConverterOptionalMapStringTypeRemoteSettingsRecord.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterBool.checkType(syncIfEmpty) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("syncIfEmpty"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 24, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsclient_get_records_map - FfiConverterTypeRemoteSettingsClient.lower(this), - FfiConverterBool.lower(syncIfEmpty), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Shutdown the client, releasing the SQLite connection used to cache records. - */ - shutdown() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 25, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsclient_shutdown - FfiConverterTypeRemoteSettingsClient.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sync - */ - sync() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 26, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsclient_sync - FfiConverterTypeRemoteSettingsClient.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteSettingsClient extends FfiConverter { static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new RemoteSettingsClient(opts); + return value; } - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'RemoteSettingsClient' instance"); - } - return ptr; + return value; } - - static read(dataStream) { - return this.lift(dataStream.readPointerRemoteSettingsClient()); - } - static write(dataStream, value) { - dataStream.writePointerRemoteSettingsClient(value[uniffiObjectPtr]); + dataStream.writeUint64(value) } - - static computeSize(value) { - return 8; - } -} - -/** - * Application-level Remote Settings manager. - * - * This handles application-level operations, like syncing all the collections, and acts as a - * factory for creating clients. - */ -export class RemoteSettingsService { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * Construct a [RemoteSettingsService] - * - * This is typically done early in the application-startup process. - * - * This method performs no IO or network requests and is safe to run in a main thread that - * can't be blocked. - * - * `storage_dir` is a directory to store SQLite files in -- one per collection. If the - * directory does not exist, it will be created when the storage is first used. Only the - * directory and the SQLite files will be created, any parent directories must already exist. - * @returns {RemoteSettingsService} - */ - static init(storageDir,config) { - const liftResult = (result) => FfiConverterTypeRemoteSettingsService.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(storageDir) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("storageDir"); - } - throw e; - } - try { - FfiConverterTypeRemoteSettingsConfig2.checkType(config) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("config"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 30, // remote_settings:uniffi_remote_settings_fn_constructor_remotesettingsservice_new - FfiConverterString.lower(storageDir), - FfiConverterTypeRemoteSettingsConfig2.lower(config), - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Create a new Remote Settings client - * - * This method performs no IO or network requests and is safe to run in a main thread that can't be blocked. - * @returns {RemoteSettingsClient} - */ - makeClient(collectionName) { - const liftResult = (result) => FfiConverterTypeRemoteSettingsClient.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(collectionName) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("collectionName"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 27, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsservice_make_client - FfiConverterTypeRemoteSettingsService.lower(this), - FfiConverterString.lower(collectionName), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Sync collections for all active clients - * @returns {Array.} - */ - sync() { - const liftResult = (result) => FfiConverterSequencestring.lift(result); - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 28, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsservice_sync - FfiConverterTypeRemoteSettingsService.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Update the remote settings config - * - * This will cause all current and future clients to use new config and will delete any stored - * records causing the clients to return new results from the new config. - * - * Only intended for QA/debugging. Swapping the remote settings server in the middle of - * execution can cause weird effects. - */ - updateConfig(config) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeRemoteSettingsError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeRemoteSettingsConfig2.checkType(config) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("config"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 29, // remote_settings:uniffi_remote_settings_fn_method_remotesettingsservice_update_config - FfiConverterTypeRemoteSettingsService.lower(this), - FfiConverterTypeRemoteSettingsConfig2.lower(config), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteSettingsService extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new RemoteSettingsService(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'RemoteSettingsService' instance"); - } - return ptr; - } - static read(dataStream) { - return this.lift(dataStream.readPointerRemoteSettingsService()); - } - - static write(dataStream, value) { - dataStream.writePointerRemoteSettingsService(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; + return dataStream.readUint64() } } - /** * Attachment metadata that can be optionally attached to a [Record]. The [location] should * included in calls to [Client::get_attachment]. */ export class Attachment { - constructor({ filename, mimetype, location, hash, size } = { filename: undefined, mimetype: undefined, location: undefined, hash: undefined, size: undefined }) { + constructor( + { + filename, + mimetype, + location, + hash, + size + } = { + filename: undefined, + mimetype: undefined, + location: undefined, + hash: undefined, + size: undefined + } + ) { try { FfiConverterString.checkType(filename) } catch (e) { @@ -1024,7 +392,7 @@ export class Attachment { throw e; } try { - FfiConverterU64.checkType(size) + FfiConverterUInt64.checkType(size) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("size"); @@ -1032,34 +400,34 @@ export class Attachment { throw e; } /** - * @type {string} + * filename */ this.filename = filename; /** - * @type {string} + * mimetype */ this.mimetype = mimetype; /** - * @type {string} + * location */ this.location = location; /** - * @type {string} + * hash */ this.hash = hash; /** - * @type {number} + * size */ this.size = size; } equals(other) { return ( - this.filename == other.filename && - this.mimetype == other.mimetype && - this.location == other.location && - this.hash == other.hash && - this.size == other.size + this.filename == other.filename + && this.mimetype == other.mimetype + && this.location == other.location + && this.hash == other.hash + && this.size == other.size ) } } @@ -1072,7 +440,7 @@ export class FfiConverterTypeAttachment extends FfiConverterArrayBuffer { mimetype: FfiConverterString.read(dataStream), location: FfiConverterString.read(dataStream), hash: FfiConverterString.read(dataStream), - size: FfiConverterU64.read(dataStream), + size: FfiConverterUInt64.read(dataStream), }); } static write(dataStream, value) { @@ -1080,7 +448,7 @@ export class FfiConverterTypeAttachment extends FfiConverterArrayBuffer { FfiConverterString.write(dataStream, value.mimetype); FfiConverterString.write(dataStream, value.location); FfiConverterString.write(dataStream, value.hash); - FfiConverterU64.write(dataStream, value.size); + FfiConverterUInt64.write(dataStream, value.size); } static computeSize(value) { @@ -1089,7 +457,7 @@ export class FfiConverterTypeAttachment extends FfiConverterArrayBuffer { totalSize += FfiConverterString.computeSize(value.mimetype); totalSize += FfiConverterString.computeSize(value.location); totalSize += FfiConverterString.computeSize(value.hash); - totalSize += FfiConverterU64.computeSize(value.size); + totalSize += FfiConverterUInt64.computeSize(value.size); return totalSize } @@ -1131,7 +499,7 @@ export class FfiConverterTypeAttachment extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU64.checkType(value.size); + FfiConverterUInt64.checkType(value.size); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".size"); @@ -1140,7 +508,190 @@ export class FfiConverterTypeAttachment extends FfiConverterArrayBuffer { } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterString.checkType(value) + } + } + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterString.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterString.computeSize(value) + } +} + +/** + * The Remote Settings server that the client should use. + */ +export class RemoteSettingsServer {} +/** + * Prod + */ +RemoteSettingsServer.Prod = class extends RemoteSettingsServer{ + constructor( + ) { + super(); + } +} +/** + * Stage + */ +RemoteSettingsServer.Stage = class extends RemoteSettingsServer{ + constructor( + ) { + super(); + } +} +/** + * Dev + */ +RemoteSettingsServer.Dev = class extends RemoteSettingsServer{ + constructor( + ) { + super(); + } +} +/** + * Custom + */ +RemoteSettingsServer.Custom = class extends RemoteSettingsServer{ + constructor( + url + ) { + super(); + this.url = url; + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRemoteSettingsServer extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new RemoteSettingsServer.Prod( + ); + case 2: + return new RemoteSettingsServer.Stage( + ); + case 3: + return new RemoteSettingsServer.Dev( + ); + case 4: + return new RemoteSettingsServer.Custom( + FfiConverterString.read(dataStream) + ); + default: + throw new UniFFITypeError("Unknown RemoteSettingsServer variant"); + } + } + + static write(dataStream, value) { + if (value instanceof RemoteSettingsServer.Prod) { + dataStream.writeInt32(1); + return; + } + if (value instanceof RemoteSettingsServer.Stage) { + dataStream.writeInt32(2); + return; + } + if (value instanceof RemoteSettingsServer.Dev) { + dataStream.writeInt32(3); + return; + } + if (value instanceof RemoteSettingsServer.Custom) { + dataStream.writeInt32(4); + FfiConverterString.write(dataStream, value.url); + return; + } + throw new UniFFITypeError("Unknown RemoteSettingsServer variant"); + } + + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof RemoteSettingsServer.Prod) { + return totalSize; + } + if (value instanceof RemoteSettingsServer.Stage) { + return totalSize; + } + if (value instanceof RemoteSettingsServer.Dev) { + return totalSize; + } + if (value instanceof RemoteSettingsServer.Custom) { + totalSize += FfiConverterString.computeSize(value.url); + return totalSize; + } + throw new UniFFITypeError("Unknown RemoteSettingsServer variant"); + } + + static checkType(value) { + if (!(value instanceof RemoteSettingsServer)) { + throw new UniFFITypeError(`${value} is not a subclass instance of RemoteSettingsServer`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeRemoteSettingsServer extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeRemoteSettingsServer.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeRemoteSettingsServer.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeRemoteSettingsServer.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeRemoteSettingsServer.computeSize(value) + } +} /** * Custom configuration for the client. * Currently includes the following: @@ -1150,7 +701,19 @@ export class FfiConverterTypeAttachment extends FfiConverterArrayBuffer { * - `collection_name`: The name of the collection for the settings server. */ export class RemoteSettingsConfig { - constructor({ collectionName, bucketName = null, serverUrl = null, server = null } = { collectionName: undefined, bucketName: undefined, serverUrl: undefined, server: undefined }) { + constructor( + { + collectionName, + bucketName= null, + serverUrl= null, + server= null + } = { + collectionName: undefined, + bucketName: undefined, + serverUrl: undefined, + server: undefined + } + ) { try { FfiConverterString.checkType(collectionName) } catch (e) { @@ -1160,7 +723,7 @@ export class RemoteSettingsConfig { throw e; } try { - FfiConverterOptionalstring.checkType(bucketName) + FfiConverterOptionalString.checkType(bucketName) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("bucketName"); @@ -1168,7 +731,7 @@ export class RemoteSettingsConfig { throw e; } try { - FfiConverterOptionalstring.checkType(serverUrl) + FfiConverterOptionalString.checkType(serverUrl) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("serverUrl"); @@ -1184,29 +747,29 @@ export class RemoteSettingsConfig { throw e; } /** - * @type {string} + * collectionName */ this.collectionName = collectionName; /** - * @type {?string} + * bucketName */ this.bucketName = bucketName; /** - * @type {?string} + * serverUrl */ this.serverUrl = serverUrl; /** - * @type {?RemoteSettingsServer} + * server */ this.server = server; } equals(other) { return ( - this.collectionName == other.collectionName && - this.bucketName == other.bucketName && - this.serverUrl == other.serverUrl && - this.server == other.server + this.collectionName == other.collectionName + && this.bucketName == other.bucketName + && this.serverUrl == other.serverUrl + && this.server == other.server ) } } @@ -1216,23 +779,23 @@ export class FfiConverterTypeRemoteSettingsConfig extends FfiConverterArrayBuffe static read(dataStream) { return new RemoteSettingsConfig({ collectionName: FfiConverterString.read(dataStream), - bucketName: FfiConverterOptionalstring.read(dataStream), - serverUrl: FfiConverterOptionalstring.read(dataStream), + bucketName: FfiConverterOptionalString.read(dataStream), + serverUrl: FfiConverterOptionalString.read(dataStream), server: FfiConverterOptionalTypeRemoteSettingsServer.read(dataStream), }); } static write(dataStream, value) { FfiConverterString.write(dataStream, value.collectionName); - FfiConverterOptionalstring.write(dataStream, value.bucketName); - FfiConverterOptionalstring.write(dataStream, value.serverUrl); + FfiConverterOptionalString.write(dataStream, value.bucketName); + FfiConverterOptionalString.write(dataStream, value.serverUrl); FfiConverterOptionalTypeRemoteSettingsServer.write(dataStream, value.server); } static computeSize(value) { let totalSize = 0; totalSize += FfiConverterString.computeSize(value.collectionName); - totalSize += FfiConverterOptionalstring.computeSize(value.bucketName); - totalSize += FfiConverterOptionalstring.computeSize(value.serverUrl); + totalSize += FfiConverterOptionalString.computeSize(value.bucketName); + totalSize += FfiConverterOptionalString.computeSize(value.serverUrl); totalSize += FfiConverterOptionalTypeRemoteSettingsServer.computeSize(value.server); return totalSize } @@ -1251,7 +814,7 @@ export class FfiConverterTypeRemoteSettingsConfig extends FfiConverterArrayBuffe throw e; } try { - FfiConverterOptionalstring.checkType(value.bucketName); + FfiConverterOptionalString.checkType(value.bucketName); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".bucketName"); @@ -1259,7 +822,7 @@ export class FfiConverterTypeRemoteSettingsConfig extends FfiConverterArrayBuffe throw e; } try { - FfiConverterOptionalstring.checkType(value.serverUrl); + FfiConverterOptionalString.checkType(value.serverUrl); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".serverUrl"); @@ -1276,16 +839,439 @@ export class FfiConverterTypeRemoteSettingsConfig extends FfiConverterArrayBuffe } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterMapStringString extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const map = new Map(); + for (let i = 0; i < len; i++) { + const key = FfiConverterString.read(dataStream); + const value = FfiConverterString.read(dataStream); + map.set(key, value); + } + return map; + } + + static write(dataStream, map) { + dataStream.writeInt32(map.size); + for (const [key, value] of map) { + FfiConverterString.write(dataStream, key); + FfiConverterString.write(dataStream, value); + } + } + + static computeSize(map) { + // The size of the length + let size = 4; + for (const [key, value] of map) { + size += FfiConverterString.computeSize(key); + size += FfiConverterString.computeSize(value); + } + return size; + } + + static checkType(map) { + for (const [key, value] of map) { + try { + FfiConverterString.checkType(key); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("(key)"); + } + throw e; + } + + try { + FfiConverterString.checkType(value); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${key}]`); + } + throw e; + } + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalMapStringString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterMapStringString.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterMapStringString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterMapStringString.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterMapStringString.computeSize(value) + } +} +/** + * Remote settings context object + * + * This is used to filter the records returned. We always fetch all `records` from the + * remote-settings storage. Some records could have a `filter_expression`. If this is passed in + * and the record has a `filter_expression`, then only returns where the expression is true will + * be returned. + * + * See https://remote-settings.readthedocs.io/en/latest/target-filters.html for details. + */ +export class RemoteSettingsContext { + constructor( + { + channel= null, + appVersion= null, + appId= null, + locale= null, + os= null, + osVersion= null, + formFactor= null, + country= null, + customTargettingAttributes= null + } = { + channel: undefined, + appVersion: undefined, + appId: undefined, + locale: undefined, + os: undefined, + osVersion: undefined, + formFactor: undefined, + country: undefined, + customTargettingAttributes: undefined + } + ) { + try { + FfiConverterOptionalString.checkType(channel) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("channel"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(appVersion) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("appVersion"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(appId) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("appId"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(locale) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("locale"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(os) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("os"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(osVersion) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("osVersion"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(formFactor) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("formFactor"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(country) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("country"); + } + throw e; + } + try { + FfiConverterOptionalMapStringString.checkType(customTargettingAttributes) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("customTargettingAttributes"); + } + throw e; + } + /** + * The delivery channel of the application (e.g "nightly") + */ + this.channel = channel; + /** + * User visible version string (e.g. "1.0.3") + */ + this.appVersion = appVersion; + /** + * String containing the XUL application app_id + */ + this.appId = appId; + /** + * The locale of the application during initialization (e.g. "es-ES") + */ + this.locale = locale; + /** + * The name of the operating system (e.g. "Android", "iOS", "Darwin", "WINNT") + */ + this.os = os; + /** + * The user-visible version of the operating system (e.g. "1.2.3") + */ + this.osVersion = osVersion; + /** + * Form-factor of the device ("phone", "tablet", or "desktop") + */ + this.formFactor = formFactor; + /** + * Country of the user. + * + * This is usually populated in one of two ways: + * - The second component of the locale + * - By using a geolocation service, which determines country via the user's IP. + * Firefox apps usually have a module that integrates with these services, + * for example `Region` on Desktop and `RegionMiddleware` on Android. + */ + this.country = country; + /** + * Extra attributes to add to the env for JEXL filtering. + * + * Use this for prototyping / testing new features. In the long-term, new fields should be + * added to the official list and supported by both the Rust and Gecko clients. + */ + this.customTargettingAttributes = customTargettingAttributes; + } + + equals(other) { + return ( + this.channel == other.channel + && this.appVersion == other.appVersion + && this.appId == other.appId + && this.locale == other.locale + && this.os == other.os + && this.osVersion == other.osVersion + && this.formFactor == other.formFactor + && this.country == other.country + && this.customTargettingAttributes == other.customTargettingAttributes + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRemoteSettingsContext extends FfiConverterArrayBuffer { + static read(dataStream) { + return new RemoteSettingsContext({ + channel: FfiConverterOptionalString.read(dataStream), + appVersion: FfiConverterOptionalString.read(dataStream), + appId: FfiConverterOptionalString.read(dataStream), + locale: FfiConverterOptionalString.read(dataStream), + os: FfiConverterOptionalString.read(dataStream), + osVersion: FfiConverterOptionalString.read(dataStream), + formFactor: FfiConverterOptionalString.read(dataStream), + country: FfiConverterOptionalString.read(dataStream), + customTargettingAttributes: FfiConverterOptionalMapStringString.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterOptionalString.write(dataStream, value.channel); + FfiConverterOptionalString.write(dataStream, value.appVersion); + FfiConverterOptionalString.write(dataStream, value.appId); + FfiConverterOptionalString.write(dataStream, value.locale); + FfiConverterOptionalString.write(dataStream, value.os); + FfiConverterOptionalString.write(dataStream, value.osVersion); + FfiConverterOptionalString.write(dataStream, value.formFactor); + FfiConverterOptionalString.write(dataStream, value.country); + FfiConverterOptionalMapStringString.write(dataStream, value.customTargettingAttributes); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterOptionalString.computeSize(value.channel); + totalSize += FfiConverterOptionalString.computeSize(value.appVersion); + totalSize += FfiConverterOptionalString.computeSize(value.appId); + totalSize += FfiConverterOptionalString.computeSize(value.locale); + totalSize += FfiConverterOptionalString.computeSize(value.os); + totalSize += FfiConverterOptionalString.computeSize(value.osVersion); + totalSize += FfiConverterOptionalString.computeSize(value.formFactor); + totalSize += FfiConverterOptionalString.computeSize(value.country); + totalSize += FfiConverterOptionalMapStringString.computeSize(value.customTargettingAttributes); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof RemoteSettingsContext)) { + throw new UniFFITypeError(`Expected 'RemoteSettingsContext', found '${typeof value}'`); + } + try { + FfiConverterOptionalString.checkType(value.channel); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".channel"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.appVersion); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".appVersion"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.appId); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".appId"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.locale); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".locale"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.os); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".os"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.osVersion); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".osVersion"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.formFactor); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".formFactor"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.country); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".country"); + } + throw e; + } + try { + FfiConverterOptionalMapStringString.checkType(value.customTargettingAttributes); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".customTargettingAttributes"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeRemoteSettingsContext extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeRemoteSettingsContext.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeRemoteSettingsContext.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeRemoteSettingsContext.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeRemoteSettingsContext.computeSize(value) + } +} /** * Remote settings configuration - * + * * This is the version used in the new API, hence the `2` at the end. The plan is to move * consumers to the new API, remove the RemoteSettingsConfig struct, then remove the `2` from this * name. */ export class RemoteSettingsConfig2 { - constructor({ server = null, bucketName = null, appContext = null } = { server: undefined, bucketName: undefined, appContext: undefined }) { + constructor( + { + server= null, + bucketName= null, + appContext= null + } = { + server: undefined, + bucketName: undefined, + appContext: undefined + } + ) { try { FfiConverterOptionalTypeRemoteSettingsServer.checkType(server) } catch (e) { @@ -1295,7 +1281,7 @@ export class RemoteSettingsConfig2 { throw e; } try { - FfiConverterOptionalstring.checkType(bucketName) + FfiConverterOptionalString.checkType(bucketName) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("bucketName"); @@ -1312,26 +1298,23 @@ export class RemoteSettingsConfig2 { } /** * The Remote Settings server to use. Defaults to [RemoteSettingsServer::Prod], - * @type {?RemoteSettingsServer} */ this.server = server; /** * Bucket name to use, defaults to "main". Use "main-preview" for a preview bucket - * @type {?string} */ this.bucketName = bucketName; /** * App context to use for JEXL filtering (when the `jexl` feature is present). - * @type {?RemoteSettingsContext} */ this.appContext = appContext; } equals(other) { return ( - this.server == other.server && - this.bucketName == other.bucketName && - this.appContext == other.appContext + this.server == other.server + && this.bucketName == other.bucketName + && this.appContext == other.appContext ) } } @@ -1341,20 +1324,20 @@ export class FfiConverterTypeRemoteSettingsConfig2 extends FfiConverterArrayBuff static read(dataStream) { return new RemoteSettingsConfig2({ server: FfiConverterOptionalTypeRemoteSettingsServer.read(dataStream), - bucketName: FfiConverterOptionalstring.read(dataStream), + bucketName: FfiConverterOptionalString.read(dataStream), appContext: FfiConverterOptionalTypeRemoteSettingsContext.read(dataStream), }); } static write(dataStream, value) { FfiConverterOptionalTypeRemoteSettingsServer.write(dataStream, value.server); - FfiConverterOptionalstring.write(dataStream, value.bucketName); + FfiConverterOptionalString.write(dataStream, value.bucketName); FfiConverterOptionalTypeRemoteSettingsContext.write(dataStream, value.appContext); } static computeSize(value) { let totalSize = 0; totalSize += FfiConverterOptionalTypeRemoteSettingsServer.computeSize(value.server); - totalSize += FfiConverterOptionalstring.computeSize(value.bucketName); + totalSize += FfiConverterOptionalString.computeSize(value.bucketName); totalSize += FfiConverterOptionalTypeRemoteSettingsContext.computeSize(value.appContext); return totalSize } @@ -1373,7 +1356,7 @@ export class FfiConverterTypeRemoteSettingsConfig2 extends FfiConverterArrayBuff throw e; } try { - FfiConverterOptionalstring.checkType(value.bucketName); + FfiConverterOptionalString.checkType(value.bucketName); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".bucketName"); @@ -1390,289 +1373,108 @@ export class FfiConverterTypeRemoteSettingsConfig2 extends FfiConverterArrayBuff } } } - -/** - * Remote settings context object - * - * This is used to filter the records returned. We always fetch all `records` from the - * remote-settings storage. Some records could have a `filter_expression`. If this is passed in - * and the record has a `filter_expression`, then only returns where the expression is true will - * be returned. - * - * See https://remote-settings.readthedocs.io/en/latest/target-filters.html for details. - */ -export class RemoteSettingsContext { - constructor({ channel = null, appVersion = null, appId = null, locale = null, os = null, osVersion = null, formFactor = null, country = null, customTargettingAttributes = null } = { channel: undefined, appVersion: undefined, appId: undefined, locale: undefined, os: undefined, osVersion: undefined, formFactor: undefined, country: undefined, customTargettingAttributes: undefined }) { - try { - FfiConverterOptionalstring.checkType(channel) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("channel"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(appVersion) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("appVersion"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(appId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("appId"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(locale) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("locale"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(os) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("os"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(osVersion) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("osVersion"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(formFactor) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("formFactor"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(country) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("country"); - } - throw e; - } - try { - FfiConverterOptionalMapStringString.checkType(customTargettingAttributes) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("customTargettingAttributes"); - } - throw e; - } - /** - * The delivery channel of the application (e.g "nightly") - * @type {?string} - */ - this.channel = channel; - /** - * User visible version string (e.g. "1.0.3") - * @type {?string} - */ - this.appVersion = appVersion; - /** - * String containing the XUL application app_id - * @type {?string} - */ - this.appId = appId; - /** - * The locale of the application during initialization (e.g. "es-ES") - * @type {?string} - */ - this.locale = locale; - /** - * The name of the operating system (e.g. "Android", "iOS", "Darwin", "WINNT") - * @type {?string} - */ - this.os = os; - /** - * The user-visible version of the operating system (e.g. "1.2.3") - * @type {?string} - */ - this.osVersion = osVersion; - /** - * Form-factor of the device ("phone", "tablet", or "desktop") - * @type {?string} - */ - this.formFactor = formFactor; - /** - * Country of the user. - * - * This is usually populated in one of two ways: - * - The second component of the locale - * - By using a geolocation service, which determines country via the user's IP. - * Firefox apps usually have a module that integrates with these services, - * for example `Region` on Desktop and `RegionMiddleware` on Android. - * @type {?string} - */ - this.country = country; - /** - * Extra attributes to add to the env for JEXL filtering. - * - * Use this for prototyping / testing new features. In the long-term, new fields should be - * added to the official list and supported by both the Rust and Gecko clients. - * @type {?object} - */ - this.customTargettingAttributes = customTargettingAttributes; - } - - equals(other) { - return ( - this.channel == other.channel && - this.appVersion == other.appVersion && - this.appId == other.appId && - this.locale == other.locale && - this.os == other.os && - this.osVersion == other.osVersion && - this.formFactor == other.formFactor && - this.country == other.country && - this.customTargettingAttributes == other.customTargettingAttributes - ) - } -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteSettingsContext extends FfiConverterArrayBuffer { - static read(dataStream) { - return new RemoteSettingsContext({ - channel: FfiConverterOptionalstring.read(dataStream), - appVersion: FfiConverterOptionalstring.read(dataStream), - appId: FfiConverterOptionalstring.read(dataStream), - locale: FfiConverterOptionalstring.read(dataStream), - os: FfiConverterOptionalstring.read(dataStream), - osVersion: FfiConverterOptionalstring.read(dataStream), - formFactor: FfiConverterOptionalstring.read(dataStream), - country: FfiConverterOptionalstring.read(dataStream), - customTargettingAttributes: FfiConverterOptionalMapStringString.read(dataStream), - }); +export class FfiConverterBoolean extends FfiConverter { + static computeSize(_value) { + return 1; + } + static lift(value) { + return value == 1; + } + static lower(value) { + if (value) { + return 1; + } else { + return 0; + } } static write(dataStream, value) { - FfiConverterOptionalstring.write(dataStream, value.channel); - FfiConverterOptionalstring.write(dataStream, value.appVersion); - FfiConverterOptionalstring.write(dataStream, value.appId); - FfiConverterOptionalstring.write(dataStream, value.locale); - FfiConverterOptionalstring.write(dataStream, value.os); - FfiConverterOptionalstring.write(dataStream, value.osVersion); - FfiConverterOptionalstring.write(dataStream, value.formFactor); - FfiConverterOptionalstring.write(dataStream, value.country); - FfiConverterOptionalMapStringString.write(dataStream, value.customTargettingAttributes); + dataStream.writeUint8(this.lower(value)) + } + static read(dataStream) { + return this.lift(dataStream.readUint8()) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeAttachment extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeAttachment.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeAttachment.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeAttachment.write(dataStream, value) } static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterOptionalstring.computeSize(value.channel); - totalSize += FfiConverterOptionalstring.computeSize(value.appVersion); - totalSize += FfiConverterOptionalstring.computeSize(value.appId); - totalSize += FfiConverterOptionalstring.computeSize(value.locale); - totalSize += FfiConverterOptionalstring.computeSize(value.os); - totalSize += FfiConverterOptionalstring.computeSize(value.osVersion); - totalSize += FfiConverterOptionalstring.computeSize(value.formFactor); - totalSize += FfiConverterOptionalstring.computeSize(value.country); - totalSize += FfiConverterOptionalMapStringString.computeSize(value.customTargettingAttributes); - return totalSize + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeAttachment.computeSize(value) } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof RemoteSettingsContext)) { - throw new UniFFITypeError(`Expected 'RemoteSettingsContext', found '${typeof value}'`); - } - try { - FfiConverterOptionalstring.checkType(value.channel); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".channel"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.appVersion); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".appVersion"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.appId); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".appId"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.locale); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".locale"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.os); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".os"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.osVersion); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".osVersion"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.formFactor); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".formFactor"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.country); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".country"); - } - throw e; - } - try { - FfiConverterOptionalMapStringString.checkType(value.customTargettingAttributes); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".customTargettingAttributes"); - } - throw e; - } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRsJsonObject extends FfiConverter { + static lift(buf) { + return FfiConverterString.lift(buf); + } + + static lower(buf) { + return FfiConverterString.lower(buf); + } + + static write(dataStream, value) { + FfiConverterString.write(dataStream, value); + } + + static read(buf) { + return FfiConverterString.read(buf); + } + + static computeSize(value) { + return FfiConverterString.computeSize(value); } } +// TODO: We should also allow JS to customize the type eventually. /** * A parsed Remote Settings record. Records can contain arbitrary fields, so clients * are required to further extract expected values from the [fields] member. */ export class RemoteSettingsRecord { - constructor({ id, lastModified, deleted, attachment, fields } = { id: undefined, lastModified: undefined, deleted: undefined, attachment: undefined, fields: undefined }) { + constructor( + { + id, + lastModified, + deleted, + attachment, + fields + } = { + id: undefined, + lastModified: undefined, + deleted: undefined, + attachment: undefined, + fields: undefined + } + ) { try { FfiConverterString.checkType(id) } catch (e) { @@ -1682,7 +1484,7 @@ export class RemoteSettingsRecord { throw e; } try { - FfiConverterU64.checkType(lastModified) + FfiConverterUInt64.checkType(lastModified) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("lastModified"); @@ -1690,7 +1492,7 @@ export class RemoteSettingsRecord { throw e; } try { - FfiConverterBool.checkType(deleted) + FfiConverterBoolean.checkType(deleted) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("deleted"); @@ -1714,35 +1516,34 @@ export class RemoteSettingsRecord { throw e; } /** - * @type {string} + * id */ this.id = id; /** - * @type {number} + * lastModified */ this.lastModified = lastModified; /** * Tombstone flag (see https://remote-settings.readthedocs.io/en/latest/client-specifications.html#local-state) - * @type {Boolean} */ this.deleted = deleted; /** - * @type {?Attachment} + * attachment */ this.attachment = attachment; /** - * @type {RsJsonObject} + * fields */ this.fields = fields; } equals(other) { return ( - this.id == other.id && - this.lastModified == other.lastModified && - this.deleted == other.deleted && - this.attachment == other.attachment && - this.fields == other.fields + this.id == other.id + && this.lastModified == other.lastModified + && this.deleted == other.deleted + && this.attachment == other.attachment + && this.fields == other.fields ) } } @@ -1752,16 +1553,16 @@ export class FfiConverterTypeRemoteSettingsRecord extends FfiConverterArrayBuffe static read(dataStream) { return new RemoteSettingsRecord({ id: FfiConverterString.read(dataStream), - lastModified: FfiConverterU64.read(dataStream), - deleted: FfiConverterBool.read(dataStream), + lastModified: FfiConverterUInt64.read(dataStream), + deleted: FfiConverterBoolean.read(dataStream), attachment: FfiConverterOptionalTypeAttachment.read(dataStream), fields: FfiConverterTypeRsJsonObject.read(dataStream), }); } static write(dataStream, value) { FfiConverterString.write(dataStream, value.id); - FfiConverterU64.write(dataStream, value.lastModified); - FfiConverterBool.write(dataStream, value.deleted); + FfiConverterUInt64.write(dataStream, value.lastModified); + FfiConverterBoolean.write(dataStream, value.deleted); FfiConverterOptionalTypeAttachment.write(dataStream, value.attachment); FfiConverterTypeRsJsonObject.write(dataStream, value.fields); } @@ -1769,8 +1570,8 @@ export class FfiConverterTypeRemoteSettingsRecord extends FfiConverterArrayBuffe static computeSize(value) { let totalSize = 0; totalSize += FfiConverterString.computeSize(value.id); - totalSize += FfiConverterU64.computeSize(value.lastModified); - totalSize += FfiConverterBool.computeSize(value.deleted); + totalSize += FfiConverterUInt64.computeSize(value.lastModified); + totalSize += FfiConverterBoolean.computeSize(value.deleted); totalSize += FfiConverterOptionalTypeAttachment.computeSize(value.attachment); totalSize += FfiConverterTypeRsJsonObject.computeSize(value.fields); return totalSize @@ -1790,7 +1591,7 @@ export class FfiConverterTypeRemoteSettingsRecord extends FfiConverterArrayBuffe throw e; } try { - FfiConverterU64.checkType(value.lastModified); + FfiConverterUInt64.checkType(value.lastModified); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".lastModified"); @@ -1798,7 +1599,7 @@ export class FfiConverterTypeRemoteSettingsRecord extends FfiConverterArrayBuffe throw e; } try { - FfiConverterBool.checkType(value.deleted); + FfiConverterBoolean.checkType(value.deleted); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".deleted"); @@ -1823,13 +1624,63 @@ export class FfiConverterTypeRemoteSettingsRecord extends FfiConverterArrayBuffe } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeRemoteSettingsRecord extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeRemoteSettingsRecord.read(dataStream)); + } + return arr; + } + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeRemoteSettingsRecord.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeRemoteSettingsRecord.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeRemoteSettingsRecord.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} /** * Data structure representing the top-level response from the Remote Settings. * [last_modified] will be extracted from the etag header of the response. */ export class RemoteSettingsResponse { - constructor({ records, lastModified } = { records: undefined, lastModified: undefined }) { + constructor( + { + records, + lastModified + } = { + records: undefined, + lastModified: undefined + } + ) { try { FfiConverterSequenceTypeRemoteSettingsRecord.checkType(records) } catch (e) { @@ -1839,7 +1690,7 @@ export class RemoteSettingsResponse { throw e; } try { - FfiConverterU64.checkType(lastModified) + FfiConverterUInt64.checkType(lastModified) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("lastModified"); @@ -1847,19 +1698,19 @@ export class RemoteSettingsResponse { throw e; } /** - * @type {Array.} + * records */ this.records = records; /** - * @type {number} + * lastModified */ this.lastModified = lastModified; } equals(other) { return ( - this.records == other.records && - this.lastModified == other.lastModified + this.records == other.records + && this.lastModified == other.lastModified ) } } @@ -1869,18 +1720,18 @@ export class FfiConverterTypeRemoteSettingsResponse extends FfiConverterArrayBuf static read(dataStream) { return new RemoteSettingsResponse({ records: FfiConverterSequenceTypeRemoteSettingsRecord.read(dataStream), - lastModified: FfiConverterU64.read(dataStream), + lastModified: FfiConverterUInt64.read(dataStream), }); } static write(dataStream, value) { FfiConverterSequenceTypeRemoteSettingsRecord.write(dataStream, value.records); - FfiConverterU64.write(dataStream, value.lastModified); + FfiConverterUInt64.write(dataStream, value.lastModified); } static computeSize(value) { let totalSize = 0; totalSize += FfiConverterSequenceTypeRemoteSettingsRecord.computeSize(value.records); - totalSize += FfiConverterU64.computeSize(value.lastModified); + totalSize += FfiConverterUInt64.computeSize(value.lastModified); return totalSize } @@ -1898,7 +1749,7 @@ export class FfiConverterTypeRemoteSettingsResponse extends FfiConverterArrayBuf throw e; } try { - FfiConverterU64.checkType(value.lastModified); + FfiConverterUInt64.checkType(value.lastModified); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".lastModified"); @@ -1908,9 +1759,6 @@ export class FfiConverterTypeRemoteSettingsResponse extends FfiConverterArrayBuf } } - - - /** * Public error class, this is what we return to consumers */ @@ -1981,7 +1829,7 @@ export class FfiConverterTypeRemoteSettingsError extends FfiConverterArrayBuffer ); case 2: return new Backoff( - FfiConverterU64.read(dataStream) + FfiConverterUInt64.read(dataStream) ); case 3: return new Other( @@ -1999,7 +1847,7 @@ export class FfiConverterTypeRemoteSettingsError extends FfiConverterArrayBuffer return totalSize; } if (value instanceof Backoff) { - totalSize += FfiConverterU64.computeSize(value.seconds); + totalSize += FfiConverterUInt64.computeSize(value.seconds); return totalSize; } if (value instanceof Other) { @@ -2016,7 +1864,7 @@ export class FfiConverterTypeRemoteSettingsError extends FfiConverterArrayBuffer } if (value instanceof Backoff) { dataStream.writeInt32(2); - FfiConverterU64.write(dataStream, value.seconds); + FfiConverterUInt64.write(dataStream, value.seconds); return; } if (value instanceof Other) { @@ -2029,270 +1877,147 @@ export class FfiConverterTypeRemoteSettingsError extends FfiConverterArrayBuffer static errorClass = RemoteSettingsError; } +/** + * RemoteSettings + */ +export class RemoteSettings { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + remoteSettingsConfig) { + + FfiConverterTypeRemoteSettingsConfig.checkType(remoteSettingsConfig); + const result = UniFFIScaffolding.callSync( + 18, // uniffi_remote_settings_fn_constructor_remotesettings_new + FfiConverterTypeRemoteSettingsConfig.lower(remoteSettingsConfig), + ) + return handleRustResult( + result, + FfiConverterTypeRemoteSettings.lift.bind(FfiConverterTypeRemoteSettings), + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + /** + * Download an attachment with the provided id to the provided path. + */ + async downloadAttachmentToPath( + attachmentId, + path) { + + FfiConverterString.checkType(attachmentId); + FfiConverterString.checkType(path); + const result = await UniFFIScaffolding.callAsyncWrapper( + 19, // uniffi_remote_settings_fn_method_remotesettings_download_attachment_to_path + FfiConverterTypeRemoteSettings.lower(this), + FfiConverterString.lower(attachmentId), + FfiConverterString.lower(path), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + + /** + * Fetch all records for the configuration this client was initialized with. + */ + async getRecords() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 20, // uniffi_remote_settings_fn_method_remotesettings_get_records + FfiConverterTypeRemoteSettings.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeRemoteSettingsResponse.lift.bind(FfiConverterTypeRemoteSettingsResponse), + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + + /** + * Fetch all records added to the server since the provided timestamp, + * using the configuration this client was initialized with. + */ + async getRecordsSince( + timestamp) { + + FfiConverterUInt64.checkType(timestamp); + const result = await UniFFIScaffolding.callAsyncWrapper( + 21, // uniffi_remote_settings_fn_method_remotesettings_get_records_since + FfiConverterTypeRemoteSettings.lower(this), + FfiConverterUInt64.lower(timestamp), + ) + return handleRustResult( + result, + FfiConverterTypeRemoteSettingsResponse.lift.bind(FfiConverterTypeRemoteSettingsResponse), + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } -/** - * The Remote Settings server that the client should use. - */ -export class RemoteSettingsServer {} -/** - * Prod - */ -RemoteSettingsServer.Prod = class extends RemoteSettingsServer{ - constructor( - ) { - super(); - } -} -/** - * Stage - */ -RemoteSettingsServer.Stage = class extends RemoteSettingsServer{ - constructor( - ) { - super(); - } -} -/** - * Dev - */ -RemoteSettingsServer.Dev = class extends RemoteSettingsServer{ - constructor( - ) { - super(); - } -} -/** - * Custom - */ -RemoteSettingsServer.Custom = class extends RemoteSettingsServer{ - constructor( - url - ) { - super(); - this.url = url; - } } // Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteSettingsServer extends FfiConverterArrayBuffer { - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return new RemoteSettingsServer.Prod( - ); - case 2: - return new RemoteSettingsServer.Stage( - ); - case 3: - return new RemoteSettingsServer.Dev( - ); - case 4: - return new RemoteSettingsServer.Custom( - FfiConverterString.read(dataStream) - ); - default: - throw new UniFFITypeError("Unknown RemoteSettingsServer variant"); +export class FfiConverterTypeRemoteSettings extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new RemoteSettings(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'RemoteSettings' instance"); } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(3)); } static write(dataStream, value) { - if (value instanceof RemoteSettingsServer.Prod) { - dataStream.writeInt32(1); - return; - } - if (value instanceof RemoteSettingsServer.Stage) { - dataStream.writeInt32(2); - return; - } - if (value instanceof RemoteSettingsServer.Dev) { - dataStream.writeInt32(3); - return; - } - if (value instanceof RemoteSettingsServer.Custom) { - dataStream.writeInt32(4); - FfiConverterString.write(dataStream, value.url); - return; - } - throw new UniFFITypeError("Unknown RemoteSettingsServer variant"); + dataStream.writePointer(3, this.lower(value)); } static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof RemoteSettingsServer.Prod) { - return totalSize; - } - if (value instanceof RemoteSettingsServer.Stage) { - return totalSize; - } - if (value instanceof RemoteSettingsServer.Dev) { - return totalSize; - } - if (value instanceof RemoteSettingsServer.Custom) { - totalSize += FfiConverterString.computeSize(value.url); - return totalSize; - } - throw new UniFFITypeError("Unknown RemoteSettingsServer variant"); - } - - static checkType(value) { - if (value === undefined || value === null || !(value instanceof RemoteSettingsServer)) { - throw new UniFFITypeError(`${value} is not a subclass instance of RemoteSettingsServer`); - } + return 8; } } - - // Export the FFIConverter object to make external types work. -export class FfiConverterOptionalstring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterString.checkType(value) - } - } - +export class FfiConverterBytes extends FfiConverterArrayBuffer { static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } + return dataStream.readBytes() } static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterString.write(dataStream, value) + dataStream.writeBytes(value) } static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterString.computeSize(value) + // The size of the length + 1 byte / item + return 4 + value.length } -} -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeAttachment extends FfiConverterArrayBuffer { static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeAttachment.checkType(value) + if (!value instanceof Uint8Array) { + throw new UniFFITypeError(`${value} is not an Uint8Array`); } } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeAttachment.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeAttachment.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeAttachment.computeSize(value) - } } - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeRemoteSettingsContext extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeRemoteSettingsContext.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeRemoteSettingsContext.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeRemoteSettingsContext.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeRemoteSettingsContext.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeRemoteSettingsServer extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeRemoteSettingsServer.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeRemoteSettingsServer.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeRemoteSettingsServer.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeRemoteSettingsServer.computeSize(value) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterOptionalSequenceTypeRemoteSettingsRecord extends FfiConverterArrayBuffer { static checkType(value) { @@ -2329,44 +2054,60 @@ export class FfiConverterOptionalSequenceTypeRemoteSettingsRecord extends FfiCon return 1 + FfiConverterSequenceTypeRemoteSettingsRecord.computeSize(value) } } - // Export the FFIConverter object to make external types work. -export class FfiConverterOptionalMapStringString extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterMapStringString.checkType(value) - } - } - +export class FfiConverterMapStringTypeRemoteSettingsRecord extends FfiConverterArrayBuffer { static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterMapStringString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); + const len = dataStream.readInt32(); + const map = new Map(); + for (let i = 0; i < len; i++) { + const key = FfiConverterString.read(dataStream); + const value = FfiConverterTypeRemoteSettingsRecord.read(dataStream); + map.set(key, value); + } + + return map; + } + + static write(dataStream, map) { + dataStream.writeInt32(map.size); + for (const [key, value] of map) { + FfiConverterString.write(dataStream, key); + FfiConverterTypeRemoteSettingsRecord.write(dataStream, value); } } - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; + static computeSize(map) { + // The size of the length + let size = 4; + for (const [key, value] of map) { + size += FfiConverterString.computeSize(key); + size += FfiConverterTypeRemoteSettingsRecord.computeSize(value); } - dataStream.writeUint8(1); - FfiConverterMapStringString.write(dataStream, value) + return size; } - static computeSize(value) { - if (value === null || value === undefined) { - return 1; + static checkType(map) { + for (const [key, value] of map) { + try { + FfiConverterString.checkType(key); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("(key)"); + } + throw e; + } + + try { + FfiConverterTypeRemoteSettingsRecord.checkType(value); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${key}]`); + } + throw e; + } } - return 1 + FfiConverterMapStringString.computeSize(value) } } - // Export the FFIConverter object to make external types work. export class FfiConverterOptionalMapStringTypeRemoteSettingsRecord extends FfiConverterArrayBuffer { static checkType(value) { @@ -2403,9 +2144,188 @@ export class FfiConverterOptionalMapStringTypeRemoteSettingsRecord extends FfiCo return 1 + FfiConverterMapStringTypeRemoteSettingsRecord.computeSize(value) } } +/** + * Client for a single Remote Settings collection + * + * Use [RemoteSettingsService::make_client] to create these. + */ +export class RemoteSettingsClient { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + /** + * Collection this client is for + */ + async collectionName() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 22, // uniffi_remote_settings_fn_method_remotesettingsclient_collection_name + FfiConverterTypeRemoteSettingsClient.lower(this), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, + ) + } + + /** + * Get attachment data for a remote settings record + * + * Attachments are large binary blobs used for data that doesn't fit in a normal record. They + * are handled differently than other record data: + * + * - Attachments are not downloaded in [RemoteSettingsService::sync] + * - This method will make network requests if the attachment is not cached + * - This method will throw if there is a network or other error when fetching the + * attachment data. + */ + async getAttachment( + record) { + + FfiConverterTypeRemoteSettingsRecord.checkType(record); + const result = await UniFFIScaffolding.callAsyncWrapper( + 23, // uniffi_remote_settings_fn_method_remotesettingsclient_get_attachment + FfiConverterTypeRemoteSettingsClient.lower(this), + FfiConverterTypeRemoteSettingsRecord.lower(record), + ) + return handleRustResult( + result, + FfiConverterBytes.lift.bind(FfiConverterBytes), + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + + /** + * Get the current set of records. + * + * This method normally fetches records from the last sync. This means that it returns fast + * and does not make any network requests. + * + * If records have not yet been synced it will return None. Use `sync_if_empty = true` to + * change this behavior and perform a network request in this case. That this is probably a + * bad idea if you want to fetch the setting in application startup or when building the UI. + * + * None will also be returned on disk IO errors or other unexpected errors. The reason for + * this is that there is not much an application can do in this situation other than fall back + * to the same default handling as if records have not been synced. + * + * Application-services schedules regular dumps of the server data for specific collections. + * For these collections, `get_records` will never return None. If you would like to add your + * collection to this list, please reach out to the DISCO team. + */ + async getRecords( + syncIfEmpty = false) { + + FfiConverterBoolean.checkType(syncIfEmpty); + const result = await UniFFIScaffolding.callAsyncWrapper( + 24, // uniffi_remote_settings_fn_method_remotesettingsclient_get_records + FfiConverterTypeRemoteSettingsClient.lower(this), + FfiConverterBoolean.lower(syncIfEmpty), + ) + return handleRustResult( + result, + FfiConverterOptionalSequenceTypeRemoteSettingsRecord.lift.bind(FfiConverterOptionalSequenceTypeRemoteSettingsRecord), + null, + ) + } + + /** + * Get the current set of records as a map of record_id -> record. + * + * See [Self::get_records] for an explanation of when this makes network requests, error + * handling, and how the `sync_if_empty` param works. + */ + async getRecordsMap( + syncIfEmpty = false) { + + FfiConverterBoolean.checkType(syncIfEmpty); + const result = await UniFFIScaffolding.callAsyncWrapper( + 25, // uniffi_remote_settings_fn_method_remotesettingsclient_get_records_map + FfiConverterTypeRemoteSettingsClient.lower(this), + FfiConverterBoolean.lower(syncIfEmpty), + ) + return handleRustResult( + result, + FfiConverterOptionalMapStringTypeRemoteSettingsRecord.lift.bind(FfiConverterOptionalMapStringTypeRemoteSettingsRecord), + null, + ) + } + + /** + * Shutdown the client, releasing the SQLite connection used to cache records. + */ + async shutdown() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 26, // uniffi_remote_settings_fn_method_remotesettingsclient_shutdown + FfiConverterTypeRemoteSettingsClient.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + + /** + * sync + */ + async sync() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 27, // uniffi_remote_settings_fn_method_remotesettingsclient_sync + FfiConverterTypeRemoteSettingsClient.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + +} // Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { +export class FfiConverterTypeRemoteSettingsClient extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new RemoteSettingsClient(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'RemoteSettingsClient' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(4)); + } + + static write(dataStream, value) { + dataStream.writePointer(4, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceString extends FfiConverterArrayBuffer { static read(dataStream) { const len = dataStream.readInt32(); const arr = []; @@ -2447,185 +2367,160 @@ export class FfiConverterSequencestring extends FfiConverterArrayBuffer { }) } } +/** + * Application-level Remote Settings manager. + * + * This handles application-level operations, like syncing all the collections, and acts as a + * factory for creating clients. + */ +export class RemoteSettingsService { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + storageDir, + config) { + + FfiConverterString.checkType(storageDir); + FfiConverterTypeRemoteSettingsConfig2.checkType(config); + const result = UniFFIScaffolding.callSync( + 28, // uniffi_remote_settings_fn_constructor_remotesettingsservice_new + FfiConverterString.lower(storageDir), + FfiConverterTypeRemoteSettingsConfig2.lower(config), + ) + return handleRustResult( + result, + FfiConverterTypeRemoteSettingsService.lift.bind(FfiConverterTypeRemoteSettingsService), + null, + ) + } + + /** + * Create a new Remote Settings client + * + * This method performs no IO or network requests and is safe to run in a main thread that can't be blocked. + */ + async makeClient( + collectionName) { + + FfiConverterString.checkType(collectionName); + const result = await UniFFIScaffolding.callAsyncWrapper( + 29, // uniffi_remote_settings_fn_method_remotesettingsservice_make_client + FfiConverterTypeRemoteSettingsService.lower(this), + FfiConverterString.lower(collectionName), + ) + return handleRustResult( + result, + FfiConverterTypeRemoteSettingsClient.lift.bind(FfiConverterTypeRemoteSettingsClient), + null, + ) + } + + /** + * Sync collections for all active clients + */ + async sync() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 30, // uniffi_remote_settings_fn_method_remotesettingsservice_sync + FfiConverterTypeRemoteSettingsService.lower(this), + ) + return handleRustResult( + result, + FfiConverterSequenceString.lift.bind(FfiConverterSequenceString), + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + + /** + * Update the remote settings config + * + * This will cause all current and future clients to use new config and will delete any stored + * records causing the clients to return new results from the new config. + * + * Only intended for QA/debugging. Swapping the remote settings server in the middle of + * execution can cause weird effects. + */ + async updateConfig( + config) { + + FfiConverterTypeRemoteSettingsConfig2.checkType(config); + const result = await UniFFIScaffolding.callAsyncWrapper( + 31, // uniffi_remote_settings_fn_method_remotesettingsservice_update_config + FfiConverterTypeRemoteSettingsService.lower(this), + FfiConverterTypeRemoteSettingsConfig2.lower(config), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeRemoteSettingsError.lift.bind(FfiConverterTypeRemoteSettingsError), + ) + } + +} // Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeRemoteSettingsRecord extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeRemoteSettingsRecord.read(dataStream)); +export class FfiConverterTypeRemoteSettingsService extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new RemoteSettingsService(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'RemoteSettingsService' instance"); } - return arr; + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(5)); } static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeRemoteSettingsRecord.write(dataStream, innerValue); - }) + dataStream.writePointer(5, this.lower(value)); } static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeRemoteSettingsRecord.computeSize(innerValue); - } - return size; + return 8; } - +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeRemoteSettingsRecord.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterMapStringString extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const map = new Map(); - for (let i = 0; i < len; i++) { - const key = FfiConverterString.read(dataStream); - const value = FfiConverterString.read(dataStream); - map.set(key, value); - } - - return map; - } - - static write(dataStream, map) { - dataStream.writeInt32(map.size); - for (const [key, value] of map) { - FfiConverterString.write(dataStream, key); - FfiConverterString.write(dataStream, value); + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); } } - - static computeSize(map) { - // The size of the length - let size = 4; - for (const [key, value] of map) { - size += FfiConverterString.computeSize(key); - size += FfiConverterString.computeSize(value); - } - return size; + static computeSize(_value) { + return 1; } - - static checkType(map) { - for (const [key, value] of map) { - try { - FfiConverterString.checkType(key); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("(key)"); - } - throw e; - } - - try { - FfiConverterString.checkType(value); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${key}]`); - } - throw e; - } - } + static lift(value) { + return value; } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterMapStringTypeRemoteSettingsRecord extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const map = new Map(); - for (let i = 0; i < len; i++) { - const key = FfiConverterString.read(dataStream); - const value = FfiConverterTypeRemoteSettingsRecord.read(dataStream); - map.set(key, value); - } - - return map; + static lower(value) { + return value; } - - static write(dataStream, map) { - dataStream.writeInt32(map.size); - for (const [key, value] of map) { - FfiConverterString.write(dataStream, key); - FfiConverterTypeRemoteSettingsRecord.write(dataStream, value); - } - } - - static computeSize(map) { - // The size of the length - let size = 4; - for (const [key, value] of map) { - size += FfiConverterString.computeSize(key); - size += FfiConverterTypeRemoteSettingsRecord.computeSize(value); - } - return size; - } - - static checkType(map) { - for (const [key, value] of map) { - try { - FfiConverterString.checkType(key); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("(key)"); - } - throw e; - } - - try { - FfiConverterTypeRemoteSettingsRecord.checkType(value); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${key}]`); - } - throw e; - } - } - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRsJsonObject extends FfiConverter { - static lift(buf) { - return FfiConverterString.lift(buf); - } - - static lower(buf) { - return FfiConverterString.lower(buf); - } - static write(dataStream, value) { - FfiConverterString.write(dataStream, value); - } - - static read(buf) { - return FfiConverterString.read(buf); + dataStream.writeUint8(value) } - - static computeSize(value) { - return FfiConverterString.computeSize(value); + static read(dataStream) { + return dataStream.readUint8() } } -// TODO: We should also allow JS to customize the type eventually. - - - - diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSearch.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSearch.sys.mjs index 1463434f89d8..46dcf37813dc 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSearch.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSearch.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,25 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a SearchEngineSelector pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerSearchEngineSelector() { - const pointerId = 5; // search:SearchEngineSelector + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a SearchEngineSelector pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerSearchEngineSelector(value) { - const pointerId = 5; // search:SearchEngineSelector + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -288,57 +283,6 @@ const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint32(value) - } - static read(dataStream) { - return dataStream.readUint32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -368,221 +312,376 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - -/** - * SearchEngineSelector parses the JSON configuration for - * search engines and returns the applicable engines depending - * on their region + locale. - */ -export class SearchEngineSelector { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {SearchEngineSelector} - */ - static init() { - const liftResult = (result) => FfiConverterTypeSearchEngineSelector.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 36, // search:uniffi_search_fn_constructor_searchengineselector_new - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Clears the search configuration from memory if it is known that it is - * not required for a time, e.g. if the configuration will only be re-filtered - * after an app/environment update. - */ - clearSearchConfig() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 31, // search:uniffi_search_fn_method_searchengineselector_clear_search_config - FfiConverterTypeSearchEngineSelector.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Filters the search configuration with the user's given environment, - * and returns the set of engines and parameters that should be presented - * to the user. - * @returns {RefinedSearchConfig} - */ - filterEngineConfiguration(userEnvironment) { - const liftResult = (result) => FfiConverterTypeRefinedSearchConfig.lift(result); - const liftError = (data) => FfiConverterTypeSearchApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSearchUserEnvironment.checkType(userEnvironment) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("userEnvironment"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 32, // search:uniffi_search_fn_method_searchengineselector_filter_engine_configuration - FfiConverterTypeSearchEngineSelector.lower(this), - FfiConverterTypeSearchUserEnvironment.lower(userEnvironment), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * setConfigOverrides - */ - setConfigOverrides(overrides) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSearchApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(overrides) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("overrides"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 33, // search:uniffi_search_fn_method_searchengineselector_set_config_overrides - FfiConverterTypeSearchEngineSelector.lower(this), - FfiConverterString.lower(overrides), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Sets the search configuration from the given string. If the configuration - * string is unchanged since the last update, the cached configuration is - * reused to avoid unnecessary reprocessing. This helps optimize performance, - * particularly during test runs where the same configuration may be used - * repeatedly. - */ - setSearchConfig(configuration) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSearchApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(configuration) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("configuration"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 34, // search:uniffi_search_fn_method_searchengineselector_set_search_config - FfiConverterTypeSearchEngineSelector.lower(this), - FfiConverterString.lower(configuration), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Sets the RemoteSettingsService to use. The selector will create the - * relevant remote settings client(s) from the service. - * - * # Params: - * - `service`: The remote settings service instance for the application. - * - `options`: The remote settings options to be passed to the client(s). - * - `apply_engine_overrides`: Whether or not to apply overrides from - * `search-config-v2-overrides` to the selected - * engines. Should be false unless the application - * supports the click URL feature. - */ - useRemoteSettingsServer(service,applyEngineOverrides) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeRemoteSettingsService.checkType(service) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("service"); - } - throw e; - } - try { - FfiConverterBool.checkType(applyEngineOverrides) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("applyEngineOverrides"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 35, // search:uniffi_search_fn_method_searchengineselector_use_remote_settings_server - FfiConverterTypeSearchEngineSelector.lower(this), - FfiConverterTypeRemoteSettingsService.lower(service), - FfiConverterBool.lower(applyEngineOverrides), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchEngineSelector extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new SearchEngineSelector(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'SearchEngineSelector' instance"); +export class FfiConverterOptionalString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterString.checkType(value) } - return ptr; } static read(dataStream) { - return this.lift(dataStream.readPointerSearchEngineSelector()); + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } } static write(dataStream, value) { - dataStream.writePointerSearchEngineSelector(value[uniffiObjectPtr]); + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterString.write(dataStream, value) } static computeSize(value) { - return 8; + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterString.computeSize(value) } } +/** + * The list of possible submission methods for search engine urls. + */ +export const JsonEngineMethod = { + /** + * POST + */ + POST: 1, + /** + * GET + */ + GET: 2, +}; +Object.freeze(JsonEngineMethod); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeJSONEngineMethod extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return JsonEngineMethod.POST + case 2: + return JsonEngineMethod.GET + default: + throw new UniFFITypeError("Unknown JsonEngineMethod variant"); + } + } + + static write(dataStream, value) { + if (value === JsonEngineMethod.POST) { + dataStream.writeInt32(1); + return; + } + if (value === JsonEngineMethod.GET) { + dataStream.writeInt32(2); + return; + } + throw new UniFFITypeError("Unknown JsonEngineMethod variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 2) { + throw new UniFFITypeError(`${value} is not a valid value for JsonEngineMethod`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeJSONEngineMethod extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeJSONEngineMethod.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeJSONEngineMethod.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeJSONEngineMethod.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeJSONEngineMethod.computeSize(value) + } +} +/** + * Parameter definitions for search engine URLs. The name property is always + * specified, along with one of value, experiment_config or search_access_point. + */ +export class SearchUrlParam { + constructor( + { + name, + value, + enterpriseValue, + experimentConfig + } = { + name: undefined, + value: undefined, + enterpriseValue: undefined, + experimentConfig: undefined + } + ) { + try { + FfiConverterString.checkType(name) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("name"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("value"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(enterpriseValue) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("enterpriseValue"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(experimentConfig) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("experimentConfig"); + } + throw e; + } + /** + * The name of the parameter in the url. + */ + this.name = name; + /** + * The parameter value, this may be a static value, or additionally contain + * a parameter replacement, e.g. `{inputEncoding}`. For the partner code + * parameter, this field should be `{partnerCode}`. + */ + this.value = value; + /** + * Same as value but only used if Services.polices.isEnterprise is true. Overrides other parameters of the same name. + */ + this.enterpriseValue = enterpriseValue; + /** + * The value for the parameter will be derived from the equivalent experiment + * configuration value. + * Only desktop uses this currently. + */ + this.experimentConfig = experimentConfig; + } + + equals(other) { + return ( + this.name == other.name + && this.value == other.value + && this.enterpriseValue == other.enterpriseValue + && this.experimentConfig == other.experimentConfig + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSearchUrlParam extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SearchUrlParam({ + name: FfiConverterString.read(dataStream), + value: FfiConverterOptionalString.read(dataStream), + enterpriseValue: FfiConverterOptionalString.read(dataStream), + experimentConfig: FfiConverterOptionalString.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterString.write(dataStream, value.name); + FfiConverterOptionalString.write(dataStream, value.value); + FfiConverterOptionalString.write(dataStream, value.enterpriseValue); + FfiConverterOptionalString.write(dataStream, value.experimentConfig); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterString.computeSize(value.name); + totalSize += FfiConverterOptionalString.computeSize(value.value); + totalSize += FfiConverterOptionalString.computeSize(value.enterpriseValue); + totalSize += FfiConverterOptionalString.computeSize(value.experimentConfig); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SearchUrlParam)) { + throw new UniFFITypeError(`Expected 'SearchUrlParam', found '${typeof value}'`); + } + try { + FfiConverterString.checkType(value.name); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".name"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.value); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".value"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.enterpriseValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".enterpriseValue"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.experimentConfig); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".experimentConfig"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeSearchUrlParam extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeSearchUrlParam.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeSearchUrlParam.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeSearchUrlParam.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeSearchUrlParam.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalSequenceTypeSearchUrlParam extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterSequenceTypeSearchUrlParam.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterSequenceTypeSearchUrlParam.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterSequenceTypeSearchUrlParam.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterSequenceTypeSearchUrlParam.computeSize(value) + } +} /** * Defines an individual search engine URL. This is defined separately to * `types::SearchEngineUrl` as various fields may be optional in the supplied * configuration. */ export class JsonEngineUrl { - constructor({ base, method, params, searchTermParamName } = { base: undefined, method: undefined, params: undefined, searchTermParamName: undefined }) { + constructor( + { + base, + method, + params, + searchTermParamName + } = { + base: undefined, + method: undefined, + params: undefined, + searchTermParamName: undefined + } + ) { try { - FfiConverterOptionalstring.checkType(base) + FfiConverterOptionalString.checkType(base) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("base"); @@ -590,7 +689,7 @@ export class JsonEngineUrl { throw e; } try { - FfiConverterOptionalTypeJsonEngineMethod.checkType(method) + FfiConverterOptionalTypeJSONEngineMethod.checkType(method) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("method"); @@ -606,7 +705,7 @@ export class JsonEngineUrl { throw e; } try { - FfiConverterOptionalstring.checkType(searchTermParamName) + FfiConverterOptionalString.checkType(searchTermParamName) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("searchTermParamName"); @@ -617,62 +716,58 @@ export class JsonEngineUrl { * The PrePath and FilePath of the URL. May include variables for engines * which have a variable FilePath, e.g. `{searchTerms}` for when a search * term is within the path of the url. - * @type {?string} */ this.base = base; /** * The HTTP method to use to send the request (`GET` or `POST`). * If the engine definition has not specified the method, it defaults to GET. - * @type {?JsonEngineMethod} */ this.method = method; /** * The parameters for this URL. - * @type {?Array.} */ this.params = params; /** * The name of the query parameter for the search term. Automatically * appended to the end of the query. This may be skipped if `{searchTerms}` * is included in the base. - * @type {?string} */ this.searchTermParamName = searchTermParamName; } equals(other) { return ( - this.base == other.base && - this.method == other.method && - this.params == other.params && - this.searchTermParamName == other.searchTermParamName + this.base == other.base + && this.method == other.method + && this.params == other.params + && this.searchTermParamName == other.searchTermParamName ) } } // Export the FFIConverter object to make external types work. -export class FfiConverterTypeJsonEngineUrl extends FfiConverterArrayBuffer { +export class FfiConverterTypeJSONEngineUrl extends FfiConverterArrayBuffer { static read(dataStream) { return new JsonEngineUrl({ - base: FfiConverterOptionalstring.read(dataStream), - method: FfiConverterOptionalTypeJsonEngineMethod.read(dataStream), + base: FfiConverterOptionalString.read(dataStream), + method: FfiConverterOptionalTypeJSONEngineMethod.read(dataStream), params: FfiConverterOptionalSequenceTypeSearchUrlParam.read(dataStream), - searchTermParamName: FfiConverterOptionalstring.read(dataStream), + searchTermParamName: FfiConverterOptionalString.read(dataStream), }); } static write(dataStream, value) { - FfiConverterOptionalstring.write(dataStream, value.base); - FfiConverterOptionalTypeJsonEngineMethod.write(dataStream, value.method); + FfiConverterOptionalString.write(dataStream, value.base); + FfiConverterOptionalTypeJSONEngineMethod.write(dataStream, value.method); FfiConverterOptionalSequenceTypeSearchUrlParam.write(dataStream, value.params); - FfiConverterOptionalstring.write(dataStream, value.searchTermParamName); + FfiConverterOptionalString.write(dataStream, value.searchTermParamName); } static computeSize(value) { let totalSize = 0; - totalSize += FfiConverterOptionalstring.computeSize(value.base); - totalSize += FfiConverterOptionalTypeJsonEngineMethod.computeSize(value.method); + totalSize += FfiConverterOptionalString.computeSize(value.base); + totalSize += FfiConverterOptionalTypeJSONEngineMethod.computeSize(value.method); totalSize += FfiConverterOptionalSequenceTypeSearchUrlParam.computeSize(value.params); - totalSize += FfiConverterOptionalstring.computeSize(value.searchTermParamName); + totalSize += FfiConverterOptionalString.computeSize(value.searchTermParamName); return totalSize } @@ -682,7 +777,7 @@ export class FfiConverterTypeJsonEngineUrl extends FfiConverterArrayBuffer { throw new UniFFITypeError(`Expected 'JsonEngineUrl', found '${typeof value}'`); } try { - FfiConverterOptionalstring.checkType(value.base); + FfiConverterOptionalString.checkType(value.base); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".base"); @@ -690,7 +785,7 @@ export class FfiConverterTypeJsonEngineUrl extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalTypeJsonEngineMethod.checkType(value.method); + FfiConverterOptionalTypeJSONEngineMethod.checkType(value.method); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".method"); @@ -706,7 +801,7 @@ export class FfiConverterTypeJsonEngineUrl extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalstring.checkType(value.searchTermParamName); + FfiConverterOptionalString.checkType(value.searchTermParamName); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".searchTermParamName"); @@ -715,14 +810,61 @@ export class FfiConverterTypeJsonEngineUrl extends FfiConverterArrayBuffer { } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeJSONEngineUrl extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeJSONEngineUrl.checkType(value) + } + } + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeJSONEngineUrl.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeJSONEngineUrl.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeJSONEngineUrl.computeSize(value) + } +} /** * Reflects `types::SearchEngineUrls`, but using `EngineUrl`. */ export class JsonEngineUrls { - constructor({ search, suggestions, trending, searchForm } = { search: undefined, suggestions: undefined, trending: undefined, searchForm: undefined }) { + constructor( + { + search, + suggestions, + trending, + searchForm + } = { + search: undefined, + suggestions: undefined, + trending: undefined, + searchForm: undefined + } + ) { try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(search) + FfiConverterOptionalTypeJSONEngineUrl.checkType(search) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("search"); @@ -730,7 +872,7 @@ export class JsonEngineUrls { throw e; } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(suggestions) + FfiConverterOptionalTypeJSONEngineUrl.checkType(suggestions) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("suggestions"); @@ -738,7 +880,7 @@ export class JsonEngineUrls { throw e; } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(trending) + FfiConverterOptionalTypeJSONEngineUrl.checkType(trending) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("trending"); @@ -746,7 +888,7 @@ export class JsonEngineUrls { throw e; } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(searchForm) + FfiConverterOptionalTypeJSONEngineUrl.checkType(searchForm) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("searchForm"); @@ -755,59 +897,55 @@ export class JsonEngineUrls { } /** * The URL to use for searches. - * @type {?JsonEngineUrl} */ this.search = search; /** * The URL to use for suggestions. - * @type {?JsonEngineUrl} */ this.suggestions = suggestions; /** * The URL to use for trending suggestions. - * @type {?JsonEngineUrl} */ this.trending = trending; /** * The URL of the search engine homepage. - * @type {?JsonEngineUrl} */ this.searchForm = searchForm; } equals(other) { return ( - this.search == other.search && - this.suggestions == other.suggestions && - this.trending == other.trending && - this.searchForm == other.searchForm + this.search == other.search + && this.suggestions == other.suggestions + && this.trending == other.trending + && this.searchForm == other.searchForm ) } } // Export the FFIConverter object to make external types work. -export class FfiConverterTypeJsonEngineUrls extends FfiConverterArrayBuffer { +export class FfiConverterTypeJSONEngineUrls extends FfiConverterArrayBuffer { static read(dataStream) { return new JsonEngineUrls({ - search: FfiConverterOptionalTypeJsonEngineUrl.read(dataStream), - suggestions: FfiConverterOptionalTypeJsonEngineUrl.read(dataStream), - trending: FfiConverterOptionalTypeJsonEngineUrl.read(dataStream), - searchForm: FfiConverterOptionalTypeJsonEngineUrl.read(dataStream), + search: FfiConverterOptionalTypeJSONEngineUrl.read(dataStream), + suggestions: FfiConverterOptionalTypeJSONEngineUrl.read(dataStream), + trending: FfiConverterOptionalTypeJSONEngineUrl.read(dataStream), + searchForm: FfiConverterOptionalTypeJSONEngineUrl.read(dataStream), }); } static write(dataStream, value) { - FfiConverterOptionalTypeJsonEngineUrl.write(dataStream, value.search); - FfiConverterOptionalTypeJsonEngineUrl.write(dataStream, value.suggestions); - FfiConverterOptionalTypeJsonEngineUrl.write(dataStream, value.trending); - FfiConverterOptionalTypeJsonEngineUrl.write(dataStream, value.searchForm); + FfiConverterOptionalTypeJSONEngineUrl.write(dataStream, value.search); + FfiConverterOptionalTypeJSONEngineUrl.write(dataStream, value.suggestions); + FfiConverterOptionalTypeJSONEngineUrl.write(dataStream, value.trending); + FfiConverterOptionalTypeJSONEngineUrl.write(dataStream, value.searchForm); } static computeSize(value) { let totalSize = 0; - totalSize += FfiConverterOptionalTypeJsonEngineUrl.computeSize(value.search); - totalSize += FfiConverterOptionalTypeJsonEngineUrl.computeSize(value.suggestions); - totalSize += FfiConverterOptionalTypeJsonEngineUrl.computeSize(value.trending); - totalSize += FfiConverterOptionalTypeJsonEngineUrl.computeSize(value.searchForm); + totalSize += FfiConverterOptionalTypeJSONEngineUrl.computeSize(value.search); + totalSize += FfiConverterOptionalTypeJSONEngineUrl.computeSize(value.suggestions); + totalSize += FfiConverterOptionalTypeJSONEngineUrl.computeSize(value.trending); + totalSize += FfiConverterOptionalTypeJSONEngineUrl.computeSize(value.searchForm); return totalSize } @@ -817,7 +955,7 @@ export class FfiConverterTypeJsonEngineUrls extends FfiConverterArrayBuffer { throw new UniFFITypeError(`Expected 'JsonEngineUrls', found '${typeof value}'`); } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(value.search); + FfiConverterOptionalTypeJSONEngineUrl.checkType(value.search); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".search"); @@ -825,7 +963,7 @@ export class FfiConverterTypeJsonEngineUrls extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(value.suggestions); + FfiConverterOptionalTypeJSONEngineUrl.checkType(value.suggestions); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".suggestions"); @@ -833,7 +971,7 @@ export class FfiConverterTypeJsonEngineUrls extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(value.trending); + FfiConverterOptionalTypeJSONEngineUrl.checkType(value.trending); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".trending"); @@ -841,7 +979,7 @@ export class FfiConverterTypeJsonEngineUrls extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalTypeJsonEngineUrl.checkType(value.searchForm); + FfiConverterOptionalTypeJSONEngineUrl.checkType(value.searchForm); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".searchForm"); @@ -850,465 +988,139 @@ export class FfiConverterTypeJsonEngineUrls extends FfiConverterArrayBuffer { } } } - -/** - * Details of the search engines to display to the user, generated as a result - * of processing the search configuration. - */ -export class RefinedSearchConfig { - constructor({ engines, appDefaultEngineId, appPrivateDefaultEngineId } = { engines: undefined, appDefaultEngineId: undefined, appPrivateDefaultEngineId: undefined }) { - try { - FfiConverterSequenceTypeSearchEngineDefinition.checkType(engines) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("engines"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(appDefaultEngineId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("appDefaultEngineId"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(appPrivateDefaultEngineId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("appPrivateDefaultEngineId"); - } - throw e; - } - /** - * A sorted list of engines. Clients may use the engine in the order that - * this list is specified, or they may implement their own order if they - * have other requirements. - * - * The application default engines should not be assumed from this order in - * case of future changes. - * - * The sort order is: - * - * * Application Default Engine - * * Application Default Engine for Private Mode (if specified & different) - * * Engines sorted by descending `SearchEngineDefinition.orderHint` - * * Any other engines in alphabetical order (locale based comparison) - * @type {Array.} - */ - this.engines = engines; - /** - * The identifier of the engine that should be used for the application - * default engine. If this is undefined, an error has occurred, and the - * application should either default to the first engine in the engines - * list or otherwise handle appropriately. - * @type {?string} - */ - this.appDefaultEngineId = appDefaultEngineId; - /** - * If specified, the identifier of the engine that should be used for the - * application default engine in private browsing mode. - * Only desktop uses this currently. - * @type {?string} - */ - this.appPrivateDefaultEngineId = appPrivateDefaultEngineId; - } - - equals(other) { - return ( - this.engines == other.engines && - this.appDefaultEngineId == other.appDefaultEngineId && - this.appPrivateDefaultEngineId == other.appPrivateDefaultEngineId - ) - } -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeRefinedSearchConfig extends FfiConverterArrayBuffer { +export class FfiConverterSequenceString extends FfiConverterArrayBuffer { static read(dataStream) { - return new RefinedSearchConfig({ - engines: FfiConverterSequenceTypeSearchEngineDefinition.read(dataStream), - appDefaultEngineId: FfiConverterOptionalstring.read(dataStream), - appPrivateDefaultEngineId: FfiConverterOptionalstring.read(dataStream), - }); + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterString.read(dataStream)); + } + return arr; } + static write(dataStream, value) { - FfiConverterSequenceTypeSearchEngineDefinition.write(dataStream, value.engines); - FfiConverterOptionalstring.write(dataStream, value.appDefaultEngineId); - FfiConverterOptionalstring.write(dataStream, value.appPrivateDefaultEngineId); + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterString.write(dataStream, innerValue); + }) } static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterSequenceTypeSearchEngineDefinition.computeSize(value.engines); - totalSize += FfiConverterOptionalstring.computeSize(value.appDefaultEngineId); - totalSize += FfiConverterOptionalstring.computeSize(value.appPrivateDefaultEngineId); - return totalSize + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterString.computeSize(innerValue); + } + return size; } static checkType(value) { - super.checkType(value); - if (!(value instanceof RefinedSearchConfig)) { - throw new UniFFITypeError(`Expected 'RefinedSearchConfig', found '${typeof value}'`); + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); } - try { - FfiConverterSequenceTypeSearchEngineDefinition.checkType(value.engines); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".engines"); + value.forEach((innerValue, idx) => { + try { + FfiConverterString.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.appDefaultEngineId); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".appDefaultEngineId"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.appPrivateDefaultEngineId); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".appPrivateDefaultEngineId"); - } - throw e; - } + }) } } /** - * A definition for an individual search engine to be presented to the user. + * The list of acceptable classifications for a search engine. */ -export class SearchEngineDefinition { - constructor({ aliases, charset, classification, identifier, name, optional, partnerCode, telemetrySuffix, urls, orderHint, clickUrl } = { aliases: undefined, charset: undefined, classification: undefined, identifier: undefined, name: undefined, optional: undefined, partnerCode: undefined, telemetrySuffix: undefined, urls: undefined, orderHint: undefined, clickUrl: undefined }) { - try { - FfiConverterSequencestring.checkType(aliases) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("aliases"); - } - throw e; - } - try { - FfiConverterString.checkType(charset) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("charset"); - } - throw e; - } - try { - FfiConverterTypeSearchEngineClassification.checkType(classification) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("classification"); - } - throw e; - } - try { - FfiConverterString.checkType(identifier) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("identifier"); - } - throw e; - } - try { - FfiConverterString.checkType(name) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("name"); - } - throw e; - } - try { - FfiConverterBool.checkType(optional) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("optional"); - } - throw e; - } - try { - FfiConverterString.checkType(partnerCode) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("partnerCode"); - } - throw e; - } - try { - FfiConverterString.checkType(telemetrySuffix) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("telemetrySuffix"); - } - throw e; - } - try { - FfiConverterTypeSearchEngineUrls.checkType(urls) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("urls"); - } - throw e; - } - try { - FfiConverterOptionalu32.checkType(orderHint) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("orderHint"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(clickUrl) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("clickUrl"); - } - throw e; - } - /** - * A list of aliases for this engine. - * @type {Array.} - */ - this.aliases = aliases; - /** - * The character set this engine uses for queries. - * @type {string} - */ - this.charset = charset; - /** - * The classification of search engine according to the main search types - * (e.g. general, shopping, travel, dictionary). Currently, only marking as - * a general search engine is supported. - * On Android, only general search engines may be selected as "default" - * search engines. - * @type {SearchEngineClassification} - */ - this.classification = classification; - /** - * The identifier of the search engine. This is used as an internal - * identifier, e.g. for saving the user's settings for the engine. It is - * also used to form the base telemetry id and may be extended by telemetrySuffix. - * @type {string} - */ - this.identifier = identifier; - /** - * The user visible name of the search engine. - * @type {string} - */ - this.name = name; - /** - * This search engine is presented as an option that the user may enable. - * The application should not include these in the default list of the - * user's engines. If not supported, it should filter them out. - * @type {Boolean} - */ - this.optional = optional; - /** - * The partner code for the engine. This will be inserted into parameters - * which include `{partnerCode}`. May be the empty string. - * @type {string} - */ - this.partnerCode = partnerCode; - /** - * Optional suffix that is appended to the search engine identifier - * following a dash, i.e. `-`. If it is an empty string - * no dash should be appended. - * @type {string} - */ - this.telemetrySuffix = telemetrySuffix; - /** - * The URLs associated with the search engine. - * @type {SearchEngineUrls} - */ - this.urls = urls; - /** - * A hint to the order that this engine should be in the engine list. This - * is derived from the `engineOrders` section of the search configuration. - * The higher the number, the nearer to the front it should be. - * If the number is not specified, other methods of sorting may be relied - * upon (e.g. alphabetical). - * @type {?number} - */ - this.orderHint = orderHint; - /** - * The url used for reporting clicks. - * @type {?string} - */ - this.clickUrl = clickUrl; - } - - equals(other) { - return ( - this.aliases == other.aliases && - this.charset == other.charset && - this.classification == other.classification && - this.identifier == other.identifier && - this.name == other.name && - this.optional == other.optional && - this.partnerCode == other.partnerCode && - this.telemetrySuffix == other.telemetrySuffix && - this.urls.equals(other.urls) && - this.orderHint == other.orderHint && - this.clickUrl == other.clickUrl - ) - } -} +export const SearchEngineClassification = { + /** + * GENERAL + */ + GENERAL: 1, + /** + * UNKNOWN + */ + UNKNOWN: 2, +}; +Object.freeze(SearchEngineClassification); // Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchEngineDefinition extends FfiConverterArrayBuffer { +export class FfiConverterTypeSearchEngineClassification extends FfiConverterArrayBuffer { static read(dataStream) { - return new SearchEngineDefinition({ - aliases: FfiConverterSequencestring.read(dataStream), - charset: FfiConverterString.read(dataStream), - classification: FfiConverterTypeSearchEngineClassification.read(dataStream), - identifier: FfiConverterString.read(dataStream), - name: FfiConverterString.read(dataStream), - optional: FfiConverterBool.read(dataStream), - partnerCode: FfiConverterString.read(dataStream), - telemetrySuffix: FfiConverterString.read(dataStream), - urls: FfiConverterTypeSearchEngineUrls.read(dataStream), - orderHint: FfiConverterOptionalu32.read(dataStream), - clickUrl: FfiConverterOptionalstring.read(dataStream), - }); + switch (dataStream.readInt32()) { + case 1: + return SearchEngineClassification.GENERAL + case 2: + return SearchEngineClassification.UNKNOWN + default: + throw new UniFFITypeError("Unknown SearchEngineClassification variant"); + } } + static write(dataStream, value) { - FfiConverterSequencestring.write(dataStream, value.aliases); - FfiConverterString.write(dataStream, value.charset); - FfiConverterTypeSearchEngineClassification.write(dataStream, value.classification); - FfiConverterString.write(dataStream, value.identifier); - FfiConverterString.write(dataStream, value.name); - FfiConverterBool.write(dataStream, value.optional); - FfiConverterString.write(dataStream, value.partnerCode); - FfiConverterString.write(dataStream, value.telemetrySuffix); - FfiConverterTypeSearchEngineUrls.write(dataStream, value.urls); - FfiConverterOptionalu32.write(dataStream, value.orderHint); - FfiConverterOptionalstring.write(dataStream, value.clickUrl); + if (value === SearchEngineClassification.GENERAL) { + dataStream.writeInt32(1); + return; + } + if (value === SearchEngineClassification.UNKNOWN) { + dataStream.writeInt32(2); + return; + } + throw new UniFFITypeError("Unknown SearchEngineClassification variant"); } static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterSequencestring.computeSize(value.aliases); - totalSize += FfiConverterString.computeSize(value.charset); - totalSize += FfiConverterTypeSearchEngineClassification.computeSize(value.classification); - totalSize += FfiConverterString.computeSize(value.identifier); - totalSize += FfiConverterString.computeSize(value.name); - totalSize += FfiConverterBool.computeSize(value.optional); - totalSize += FfiConverterString.computeSize(value.partnerCode); - totalSize += FfiConverterString.computeSize(value.telemetrySuffix); - totalSize += FfiConverterTypeSearchEngineUrls.computeSize(value.urls); - totalSize += FfiConverterOptionalu32.computeSize(value.orderHint); - totalSize += FfiConverterOptionalstring.computeSize(value.clickUrl); - return totalSize + return 4; } static checkType(value) { - super.checkType(value); - if (!(value instanceof SearchEngineDefinition)) { - throw new UniFFITypeError(`Expected 'SearchEngineDefinition', found '${typeof value}'`); - } - try { - FfiConverterSequencestring.checkType(value.aliases); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".aliases"); - } - throw e; - } - try { - FfiConverterString.checkType(value.charset); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".charset"); - } - throw e; - } - try { - FfiConverterTypeSearchEngineClassification.checkType(value.classification); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".classification"); - } - throw e; - } - try { - FfiConverterString.checkType(value.identifier); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".identifier"); - } - throw e; - } - try { - FfiConverterString.checkType(value.name); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".name"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.optional); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".optional"); - } - throw e; - } - try { - FfiConverterString.checkType(value.partnerCode); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".partnerCode"); - } - throw e; - } - try { - FfiConverterString.checkType(value.telemetrySuffix); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".telemetrySuffix"); - } - throw e; - } - try { - FfiConverterTypeSearchEngineUrls.checkType(value.urls); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".urls"); - } - throw e; - } - try { - FfiConverterOptionalu32.checkType(value.orderHint); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".orderHint"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.clickUrl); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".clickUrl"); - } - throw e; - } + if (!Number.isInteger(value) || value < 1 || value > 2) { + throw new UniFFITypeError(`${value} is not a valid value for SearchEngineClassification`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterBoolean extends FfiConverter { + static computeSize(_value) { + return 1; + } + static lift(value) { + return value == 1; + } + static lower(value) { + if (value) { + return 1; + } else { + return 0; + } + } + static write(dataStream, value) { + dataStream.writeUint8(this.lower(value)) + } + static read(dataStream) { + return this.lift(dataStream.readUint8()) } } - /** * Defines an individual search engine URL. */ export class SearchEngineUrl { - constructor({ base, method, params, searchTermParamName } = { base: undefined, method: undefined, params: undefined, searchTermParamName: undefined }) { + constructor( + { + base, + method, + params, + searchTermParamName + } = { + base: undefined, + method: undefined, + params: undefined, + searchTermParamName: undefined + } + ) { try { FfiConverterString.checkType(base) } catch (e) { @@ -1334,7 +1146,7 @@ export class SearchEngineUrl { throw e; } try { - FfiConverterOptionalstring.checkType(searchTermParamName) + FfiConverterOptionalString.checkType(searchTermParamName) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("searchTermParamName"); @@ -1345,35 +1157,31 @@ export class SearchEngineUrl { * The PrePath and FilePath of the URL. May include variables for engines * which have a variable FilePath, e.g. `{searchTerms}` for when a search * term is within the path of the url. - * @type {string} */ this.base = base; /** * The HTTP method to use to send the request (`GET` or `POST`). * If the engine definition has not specified the method, it defaults to GET. - * @type {string} */ this.method = method; /** * The parameters for this URL. - * @type {Array.} */ this.params = params; /** * The name of the query parameter for the search term. Automatically * appended to the end of the query. This may be skipped if `{searchTerms}` * is included in the base. - * @type {?string} */ this.searchTermParamName = searchTermParamName; } equals(other) { return ( - this.base == other.base && - this.method == other.method && - this.params == other.params && - this.searchTermParamName == other.searchTermParamName + this.base == other.base + && this.method == other.method + && this.params == other.params + && this.searchTermParamName == other.searchTermParamName ) } } @@ -1385,14 +1193,14 @@ export class FfiConverterTypeSearchEngineUrl extends FfiConverterArrayBuffer { base: FfiConverterString.read(dataStream), method: FfiConverterString.read(dataStream), params: FfiConverterSequenceTypeSearchUrlParam.read(dataStream), - searchTermParamName: FfiConverterOptionalstring.read(dataStream), + searchTermParamName: FfiConverterOptionalString.read(dataStream), }); } static write(dataStream, value) { FfiConverterString.write(dataStream, value.base); FfiConverterString.write(dataStream, value.method); FfiConverterSequenceTypeSearchUrlParam.write(dataStream, value.params); - FfiConverterOptionalstring.write(dataStream, value.searchTermParamName); + FfiConverterOptionalString.write(dataStream, value.searchTermParamName); } static computeSize(value) { @@ -1400,7 +1208,7 @@ export class FfiConverterTypeSearchEngineUrl extends FfiConverterArrayBuffer { totalSize += FfiConverterString.computeSize(value.base); totalSize += FfiConverterString.computeSize(value.method); totalSize += FfiConverterSequenceTypeSearchUrlParam.computeSize(value.params); - totalSize += FfiConverterOptionalstring.computeSize(value.searchTermParamName); + totalSize += FfiConverterOptionalString.computeSize(value.searchTermParamName); return totalSize } @@ -1434,7 +1242,7 @@ export class FfiConverterTypeSearchEngineUrl extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalstring.checkType(value.searchTermParamName); + FfiConverterOptionalString.checkType(value.searchTermParamName); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".searchTermParamName"); @@ -1443,12 +1251,59 @@ export class FfiConverterTypeSearchEngineUrl extends FfiConverterArrayBuffer { } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeSearchEngineUrl extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeSearchEngineUrl.checkType(value) + } + } + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeSearchEngineUrl.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeSearchEngineUrl.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeSearchEngineUrl.computeSize(value) + } +} /** * The URLs associated with the search engine. */ export class SearchEngineUrls { - constructor({ search, suggestions, trending, searchForm } = { search: undefined, suggestions: undefined, trending: undefined, searchForm: undefined }) { + constructor( + { + search, + suggestions, + trending, + searchForm + } = { + search: undefined, + suggestions: undefined, + trending: undefined, + searchForm: undefined + } + ) { try { FfiConverterTypeSearchEngineUrl.checkType(search) } catch (e) { @@ -1483,32 +1338,28 @@ export class SearchEngineUrls { } /** * The URL to use for searches. - * @type {SearchEngineUrl} */ this.search = search; /** * The URL to use for suggestions. - * @type {?SearchEngineUrl} */ this.suggestions = suggestions; /** * The URL to use for trending suggestions. - * @type {?SearchEngineUrl} */ this.trending = trending; /** * The URL of the search engine homepage. - * @type {?SearchEngineUrl} */ this.searchForm = searchForm; } equals(other) { return ( - this.search.equals(other.search) && - this.suggestions == other.suggestions && - this.trending == other.trending && - this.searchForm == other.searchForm + this.search.equals(other.search) + && this.suggestions == other.suggestions + && this.trending == other.trending + && this.searchForm == other.searchForm ) } } @@ -1578,13 +1429,132 @@ export class FfiConverterTypeSearchEngineUrls extends FfiConverterArrayBuffer { } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt32 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 4294967295) { + throw new UniFFITypeError(`${value} exceeds the U32 bounds`); + } + } + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint32(value) + } + static read(dataStream) { + return dataStream.readUint32() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalUInt32 extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterUInt32.checkType(value) + } + } + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterUInt32.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterUInt32.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterUInt32.computeSize(value) + } +} /** - * Parameter definitions for search engine URLs. The name property is always - * specified, along with one of value, experiment_config or search_access_point. + * A definition for an individual search engine to be presented to the user. */ -export class SearchUrlParam { - constructor({ name, value, enterpriseValue, experimentConfig } = { name: undefined, value: undefined, enterpriseValue: undefined, experimentConfig: undefined }) { +export class SearchEngineDefinition { + constructor( + { + aliases, + charset, + classification, + identifier, + name, + optional, + partnerCode, + telemetrySuffix, + urls, + orderHint, + clickUrl + } = { + aliases: undefined, + charset: undefined, + classification: undefined, + identifier: undefined, + name: undefined, + optional: undefined, + partnerCode: undefined, + telemetrySuffix: undefined, + urls: undefined, + orderHint: undefined, + clickUrl: undefined + } + ) { + try { + FfiConverterSequenceString.checkType(aliases) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("aliases"); + } + throw e; + } + try { + FfiConverterString.checkType(charset) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("charset"); + } + throw e; + } + try { + FfiConverterTypeSearchEngineClassification.checkType(classification) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("classification"); + } + throw e; + } + try { + FfiConverterString.checkType(identifier) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("identifier"); + } + throw e; + } try { FfiConverterString.checkType(name) } catch (e) { @@ -1594,95 +1564,214 @@ export class SearchUrlParam { throw e; } try { - FfiConverterOptionalstring.checkType(value) + FfiConverterBoolean.checkType(optional) } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); + e.addItemDescriptionPart("optional"); } throw e; } try { - FfiConverterOptionalstring.checkType(enterpriseValue) + FfiConverterString.checkType(partnerCode) } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("enterpriseValue"); + e.addItemDescriptionPart("partnerCode"); } throw e; } try { - FfiConverterOptionalstring.checkType(experimentConfig) + FfiConverterString.checkType(telemetrySuffix) } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("experimentConfig"); + e.addItemDescriptionPart("telemetrySuffix"); + } + throw e; + } + try { + FfiConverterTypeSearchEngineUrls.checkType(urls) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("urls"); + } + throw e; + } + try { + FfiConverterOptionalUInt32.checkType(orderHint) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("orderHint"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(clickUrl) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("clickUrl"); } throw e; } /** - * The name of the parameter in the url. - * @type {string} + * A list of aliases for this engine. + */ + this.aliases = aliases; + /** + * The character set this engine uses for queries. + */ + this.charset = charset; + /** + * The classification of search engine according to the main search types + * (e.g. general, shopping, travel, dictionary). Currently, only marking as + * a general search engine is supported. + * On Android, only general search engines may be selected as "default" + * search engines. + */ + this.classification = classification; + /** + * The identifier of the search engine. This is used as an internal + * identifier, e.g. for saving the user's settings for the engine. It is + * also used to form the base telemetry id and may be extended by telemetrySuffix. + */ + this.identifier = identifier; + /** + * The user visible name of the search engine. */ this.name = name; /** - * The parameter value, this may be a static value, or additionally contain - * a parameter replacement, e.g. `{inputEncoding}`. For the partner code - * parameter, this field should be `{partnerCode}`. - * @type {?string} + * This search engine is presented as an option that the user may enable. + * The application should not include these in the default list of the + * user's engines. If not supported, it should filter them out. */ - this.value = value; + this.optional = optional; /** - * Same as value but only used if Services.polices.isEnterprise is true. Overrides other parameters of the same name. - * @type {?string} + * The partner code for the engine. This will be inserted into parameters + * which include `{partnerCode}`. May be the empty string. */ - this.enterpriseValue = enterpriseValue; + this.partnerCode = partnerCode; /** - * The value for the parameter will be derived from the equivalent experiment - * configuration value. - * Only desktop uses this currently. - * @type {?string} + * Optional suffix that is appended to the search engine identifier + * following a dash, i.e. `-`. If it is an empty string + * no dash should be appended. */ - this.experimentConfig = experimentConfig; + this.telemetrySuffix = telemetrySuffix; + /** + * The URLs associated with the search engine. + */ + this.urls = urls; + /** + * A hint to the order that this engine should be in the engine list. This + * is derived from the `engineOrders` section of the search configuration. + * The higher the number, the nearer to the front it should be. + * If the number is not specified, other methods of sorting may be relied + * upon (e.g. alphabetical). + */ + this.orderHint = orderHint; + /** + * The url used for reporting clicks. + */ + this.clickUrl = clickUrl; } equals(other) { return ( - this.name == other.name && - this.value == other.value && - this.enterpriseValue == other.enterpriseValue && - this.experimentConfig == other.experimentConfig + this.aliases == other.aliases + && this.charset == other.charset + && this.classification == other.classification + && this.identifier == other.identifier + && this.name == other.name + && this.optional == other.optional + && this.partnerCode == other.partnerCode + && this.telemetrySuffix == other.telemetrySuffix + && this.urls.equals(other.urls) + && this.orderHint == other.orderHint + && this.clickUrl == other.clickUrl ) } } // Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchUrlParam extends FfiConverterArrayBuffer { +export class FfiConverterTypeSearchEngineDefinition extends FfiConverterArrayBuffer { static read(dataStream) { - return new SearchUrlParam({ + return new SearchEngineDefinition({ + aliases: FfiConverterSequenceString.read(dataStream), + charset: FfiConverterString.read(dataStream), + classification: FfiConverterTypeSearchEngineClassification.read(dataStream), + identifier: FfiConverterString.read(dataStream), name: FfiConverterString.read(dataStream), - value: FfiConverterOptionalstring.read(dataStream), - enterpriseValue: FfiConverterOptionalstring.read(dataStream), - experimentConfig: FfiConverterOptionalstring.read(dataStream), + optional: FfiConverterBoolean.read(dataStream), + partnerCode: FfiConverterString.read(dataStream), + telemetrySuffix: FfiConverterString.read(dataStream), + urls: FfiConverterTypeSearchEngineUrls.read(dataStream), + orderHint: FfiConverterOptionalUInt32.read(dataStream), + clickUrl: FfiConverterOptionalString.read(dataStream), }); } static write(dataStream, value) { + FfiConverterSequenceString.write(dataStream, value.aliases); + FfiConverterString.write(dataStream, value.charset); + FfiConverterTypeSearchEngineClassification.write(dataStream, value.classification); + FfiConverterString.write(dataStream, value.identifier); FfiConverterString.write(dataStream, value.name); - FfiConverterOptionalstring.write(dataStream, value.value); - FfiConverterOptionalstring.write(dataStream, value.enterpriseValue); - FfiConverterOptionalstring.write(dataStream, value.experimentConfig); + FfiConverterBoolean.write(dataStream, value.optional); + FfiConverterString.write(dataStream, value.partnerCode); + FfiConverterString.write(dataStream, value.telemetrySuffix); + FfiConverterTypeSearchEngineUrls.write(dataStream, value.urls); + FfiConverterOptionalUInt32.write(dataStream, value.orderHint); + FfiConverterOptionalString.write(dataStream, value.clickUrl); } static computeSize(value) { let totalSize = 0; + totalSize += FfiConverterSequenceString.computeSize(value.aliases); + totalSize += FfiConverterString.computeSize(value.charset); + totalSize += FfiConverterTypeSearchEngineClassification.computeSize(value.classification); + totalSize += FfiConverterString.computeSize(value.identifier); totalSize += FfiConverterString.computeSize(value.name); - totalSize += FfiConverterOptionalstring.computeSize(value.value); - totalSize += FfiConverterOptionalstring.computeSize(value.enterpriseValue); - totalSize += FfiConverterOptionalstring.computeSize(value.experimentConfig); + totalSize += FfiConverterBoolean.computeSize(value.optional); + totalSize += FfiConverterString.computeSize(value.partnerCode); + totalSize += FfiConverterString.computeSize(value.telemetrySuffix); + totalSize += FfiConverterTypeSearchEngineUrls.computeSize(value.urls); + totalSize += FfiConverterOptionalUInt32.computeSize(value.orderHint); + totalSize += FfiConverterOptionalString.computeSize(value.clickUrl); return totalSize } static checkType(value) { super.checkType(value); - if (!(value instanceof SearchUrlParam)) { - throw new UniFFITypeError(`Expected 'SearchUrlParam', found '${typeof value}'`); + if (!(value instanceof SearchEngineDefinition)) { + throw new UniFFITypeError(`Expected 'SearchEngineDefinition', found '${typeof value}'`); + } + try { + FfiConverterSequenceString.checkType(value.aliases); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".aliases"); + } + throw e; + } + try { + FfiConverterString.checkType(value.charset); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".charset"); + } + throw e; + } + try { + FfiConverterTypeSearchEngineClassification.checkType(value.classification); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".classification"); + } + throw e; + } + try { + FfiConverterString.checkType(value.identifier); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".identifier"); + } + throw e; } try { FfiConverterString.checkType(value.name); @@ -1693,37 +1782,491 @@ export class FfiConverterTypeSearchUrlParam extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterOptionalstring.checkType(value.value); + FfiConverterBoolean.checkType(value.optional); } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".value"); + e.addItemDescriptionPart(".optional"); } throw e; } try { - FfiConverterOptionalstring.checkType(value.enterpriseValue); + FfiConverterString.checkType(value.partnerCode); } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".enterpriseValue"); + e.addItemDescriptionPart(".partnerCode"); } throw e; } try { - FfiConverterOptionalstring.checkType(value.experimentConfig); + FfiConverterString.checkType(value.telemetrySuffix); } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".experimentConfig"); + e.addItemDescriptionPart(".telemetrySuffix"); + } + throw e; + } + try { + FfiConverterTypeSearchEngineUrls.checkType(value.urls); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".urls"); + } + throw e; + } + try { + FfiConverterOptionalUInt32.checkType(value.orderHint); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".orderHint"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.clickUrl); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".clickUrl"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeSearchEngineDefinition extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeSearchEngineDefinition.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeSearchEngineDefinition.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeSearchEngineDefinition.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeSearchEngineDefinition.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +/** + * Details of the search engines to display to the user, generated as a result + * of processing the search configuration. + */ +export class RefinedSearchConfig { + constructor( + { + engines, + appDefaultEngineId, + appPrivateDefaultEngineId + } = { + engines: undefined, + appDefaultEngineId: undefined, + appPrivateDefaultEngineId: undefined + } + ) { + try { + FfiConverterSequenceTypeSearchEngineDefinition.checkType(engines) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("engines"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(appDefaultEngineId) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("appDefaultEngineId"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(appPrivateDefaultEngineId) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("appPrivateDefaultEngineId"); + } + throw e; + } + /** + * A sorted list of engines. Clients may use the engine in the order that + * this list is specified, or they may implement their own order if they + * have other requirements. + * + * The application default engines should not be assumed from this order in + * case of future changes. + * + * The sort order is: + * + * * Application Default Engine + * * Application Default Engine for Private Mode (if specified & different) + * * Engines sorted by descending `SearchEngineDefinition.orderHint` + * * Any other engines in alphabetical order (locale based comparison) + */ + this.engines = engines; + /** + * The identifier of the engine that should be used for the application + * default engine. If this is undefined, an error has occurred, and the + * application should either default to the first engine in the engines + * list or otherwise handle appropriately. + */ + this.appDefaultEngineId = appDefaultEngineId; + /** + * If specified, the identifier of the engine that should be used for the + * application default engine in private browsing mode. + * Only desktop uses this currently. + */ + this.appPrivateDefaultEngineId = appPrivateDefaultEngineId; + } + + equals(other) { + return ( + this.engines == other.engines + && this.appDefaultEngineId == other.appDefaultEngineId + && this.appPrivateDefaultEngineId == other.appPrivateDefaultEngineId + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRefinedSearchConfig extends FfiConverterArrayBuffer { + static read(dataStream) { + return new RefinedSearchConfig({ + engines: FfiConverterSequenceTypeSearchEngineDefinition.read(dataStream), + appDefaultEngineId: FfiConverterOptionalString.read(dataStream), + appPrivateDefaultEngineId: FfiConverterOptionalString.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterSequenceTypeSearchEngineDefinition.write(dataStream, value.engines); + FfiConverterOptionalString.write(dataStream, value.appDefaultEngineId); + FfiConverterOptionalString.write(dataStream, value.appPrivateDefaultEngineId); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterSequenceTypeSearchEngineDefinition.computeSize(value.engines); + totalSize += FfiConverterOptionalString.computeSize(value.appDefaultEngineId); + totalSize += FfiConverterOptionalString.computeSize(value.appPrivateDefaultEngineId); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof RefinedSearchConfig)) { + throw new UniFFITypeError(`Expected 'RefinedSearchConfig', found '${typeof value}'`); + } + try { + FfiConverterSequenceTypeSearchEngineDefinition.checkType(value.engines); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".engines"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.appDefaultEngineId); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".appDefaultEngineId"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.appPrivateDefaultEngineId); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".appPrivateDefaultEngineId"); } throw e; } } } +/** + * The list of possible update channels for a user's build. + * Use `default` for a self-build or an unknown channel. + */ +export const SearchUpdateChannel = { + /** + * NIGHTLY + */ + NIGHTLY: 1, + /** + * AURORA + */ + AURORA: 2, + /** + * BETA + */ + BETA: 3, + /** + * RELEASE + */ + RELEASE: 4, + /** + * ESR + */ + ESR: 5, + /** + * DEFAULT + */ + DEFAULT: 6, +}; +Object.freeze(SearchUpdateChannel); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSearchUpdateChannel extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return SearchUpdateChannel.NIGHTLY + case 2: + return SearchUpdateChannel.AURORA + case 3: + return SearchUpdateChannel.BETA + case 4: + return SearchUpdateChannel.RELEASE + case 5: + return SearchUpdateChannel.ESR + case 6: + return SearchUpdateChannel.DEFAULT + default: + throw new UniFFITypeError("Unknown SearchUpdateChannel variant"); + } + } + + static write(dataStream, value) { + if (value === SearchUpdateChannel.NIGHTLY) { + dataStream.writeInt32(1); + return; + } + if (value === SearchUpdateChannel.AURORA) { + dataStream.writeInt32(2); + return; + } + if (value === SearchUpdateChannel.BETA) { + dataStream.writeInt32(3); + return; + } + if (value === SearchUpdateChannel.RELEASE) { + dataStream.writeInt32(4); + return; + } + if (value === SearchUpdateChannel.ESR) { + dataStream.writeInt32(5); + return; + } + if (value === SearchUpdateChannel.DEFAULT) { + dataStream.writeInt32(6); + return; + } + throw new UniFFITypeError("Unknown SearchUpdateChannel variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 6) { + throw new UniFFITypeError(`${value} is not a valid value for SearchUpdateChannel`); + } + } +} + +/** + * The list of possible application names that are currently supported. + */ +export const SearchApplicationName = { + /** + * FIREFOX_ANDROID + */ + FIREFOX_ANDROID: 1, + /** + * FIREFOX_IOS + */ + FIREFOX_IOS: 2, + /** + * FOCUS_ANDROID + */ + FOCUS_ANDROID: 3, + /** + * FOCUS_IOS + */ + FOCUS_IOS: 4, + /** + * FIREFOX + */ + FIREFOX: 5, +}; +Object.freeze(SearchApplicationName); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSearchApplicationName extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return SearchApplicationName.FIREFOX_ANDROID + case 2: + return SearchApplicationName.FIREFOX_IOS + case 3: + return SearchApplicationName.FOCUS_ANDROID + case 4: + return SearchApplicationName.FOCUS_IOS + case 5: + return SearchApplicationName.FIREFOX + default: + throw new UniFFITypeError("Unknown SearchApplicationName variant"); + } + } + + static write(dataStream, value) { + if (value === SearchApplicationName.FIREFOX_ANDROID) { + dataStream.writeInt32(1); + return; + } + if (value === SearchApplicationName.FIREFOX_IOS) { + dataStream.writeInt32(2); + return; + } + if (value === SearchApplicationName.FOCUS_ANDROID) { + dataStream.writeInt32(3); + return; + } + if (value === SearchApplicationName.FOCUS_IOS) { + dataStream.writeInt32(4); + return; + } + if (value === SearchApplicationName.FIREFOX) { + dataStream.writeInt32(5); + return; + } + throw new UniFFITypeError("Unknown SearchApplicationName variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 5) { + throw new UniFFITypeError(`${value} is not a valid value for SearchApplicationName`); + } + } +} + +/** + * SearchDeviceType + */ +export const SearchDeviceType = { + /** + * SMARTPHONE + */ + SMARTPHONE: 1, + /** + * TABLET + */ + TABLET: 2, + /** + * NONE + */ + NONE: 3, +}; +Object.freeze(SearchDeviceType); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSearchDeviceType extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return SearchDeviceType.SMARTPHONE + case 2: + return SearchDeviceType.TABLET + case 3: + return SearchDeviceType.NONE + default: + throw new UniFFITypeError("Unknown SearchDeviceType variant"); + } + } + + static write(dataStream, value) { + if (value === SearchDeviceType.SMARTPHONE) { + dataStream.writeInt32(1); + return; + } + if (value === SearchDeviceType.TABLET) { + dataStream.writeInt32(2); + return; + } + if (value === SearchDeviceType.NONE) { + dataStream.writeInt32(3); + return; + } + throw new UniFFITypeError("Unknown SearchDeviceType variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 3) { + throw new UniFFITypeError(`${value} is not a valid value for SearchDeviceType`); + } + } +} /** * The user's environment that is used for filtering the search configuration. */ export class SearchUserEnvironment { - constructor({ locale, region, updateChannel, distributionId, experiment, appName, version, deviceType } = { locale: undefined, region: undefined, updateChannel: undefined, distributionId: undefined, experiment: undefined, appName: undefined, version: undefined, deviceType: undefined }) { + constructor( + { + locale, + region, + updateChannel, + distributionId, + experiment, + appName, + version, + deviceType + } = { + locale: undefined, + region: undefined, + updateChannel: undefined, + distributionId: undefined, + experiment: undefined, + appName: undefined, + version: undefined, + deviceType: undefined + } + ) { try { FfiConverterString.checkType(locale) } catch (e) { @@ -1790,59 +2333,51 @@ export class SearchUserEnvironment { } /** * The current locale of the application that the user is using. - * @type {string} */ this.locale = locale; /** * The home region that the user is currently identified as being within. * On desktop & android there is a 14 day lag after detecting a region * change before the home region changes. TBD: iOS? - * @type {string} */ this.region = region; /** * The update channel of the user's build. - * @type {SearchUpdateChannel} */ this.updateChannel = updateChannel; /** * The distribution id for the user's build. - * @type {string} */ this.distributionId = distributionId; /** * The search related experiment id that the user is included within. On * desktop this is the `searchConfiguration.experiment` variable. - * @type {string} */ this.experiment = experiment; /** * The application name that the user is using. - * @type {SearchApplicationName} */ this.appName = appName; /** * The application version that the user is using. - * @type {string} */ this.version = version; /** * The device type that the user is using. - * @type {SearchDeviceType} */ this.deviceType = deviceType; } equals(other) { return ( - this.locale == other.locale && - this.region == other.region && - this.updateChannel == other.updateChannel && - this.distributionId == other.distributionId && - this.experiment == other.experiment && - this.appName == other.appName && - this.version == other.version && - this.deviceType == other.deviceType + this.locale == other.locale + && this.region == other.region + && this.updateChannel == other.updateChannel + && this.distributionId == other.distributionId + && this.experiment == other.experiment + && this.appName == other.appName + && this.version == other.version + && this.deviceType == other.deviceType ) } } @@ -1957,66 +2492,6 @@ export class FfiConverterTypeSearchUserEnvironment extends FfiConverterArrayBuff } } - -/** - * The list of possible submission methods for search engine urls. - */ -export const JsonEngineMethod = { - /** - * POST - */ - POST:2, - /** - * GET - */ - GET:1, -}; - -Object.freeze(JsonEngineMethod); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeJsonEngineMethod extends FfiConverterArrayBuffer { - static #validValues = Object.values(JsonEngineMethod); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return JsonEngineMethod.POST - case 2: - return JsonEngineMethod.GET - default: - throw new UniFFITypeError("Unknown JsonEngineMethod variant"); - } - } - - static write(dataStream, value) { - if (value === JsonEngineMethod.POST) { - dataStream.writeInt32(1); - return; - } - if (value === JsonEngineMethod.GET) { - dataStream.writeInt32(2); - return; - } - throw new UniFFITypeError("Unknown JsonEngineMethod variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for JsonEngineMethod`); - } - } -} - - - - - /** * SearchApiError */ @@ -2073,676 +2548,236 @@ export class FfiConverterTypeSearchApiError extends FfiConverterArrayBuffer { static errorClass = SearchApiError; } - - -/** - * The list of possible application names that are currently supported. - */ -export const SearchApplicationName = { - /** - * FIREFOX_ANDROID - */ - FIREFOX_ANDROID:1, - /** - * FIREFOX_IOS - */ - FIREFOX_IOS:2, - /** - * FOCUS_ANDROID - */ - FOCUS_ANDROID:3, - /** - * FOCUS_IOS - */ - FOCUS_IOS:4, - /** - * FIREFOX - */ - FIREFOX:5, -}; - -Object.freeze(SearchApplicationName); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchApplicationName extends FfiConverterArrayBuffer { - static #validValues = Object.values(SearchApplicationName); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return SearchApplicationName.FIREFOX_ANDROID - case 2: - return SearchApplicationName.FIREFOX_IOS - case 3: - return SearchApplicationName.FOCUS_ANDROID - case 4: - return SearchApplicationName.FOCUS_IOS - case 5: - return SearchApplicationName.FIREFOX - default: - throw new UniFFITypeError("Unknown SearchApplicationName variant"); - } - } - - static write(dataStream, value) { - if (value === SearchApplicationName.FIREFOX_ANDROID) { - dataStream.writeInt32(1); - return; - } - if (value === SearchApplicationName.FIREFOX_IOS) { - dataStream.writeInt32(2); - return; - } - if (value === SearchApplicationName.FOCUS_ANDROID) { - dataStream.writeInt32(3); - return; - } - if (value === SearchApplicationName.FOCUS_IOS) { - dataStream.writeInt32(4); - return; - } - if (value === SearchApplicationName.FIREFOX) { - dataStream.writeInt32(5); - return; - } - throw new UniFFITypeError("Unknown SearchApplicationName variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for SearchApplicationName`); - } - } -} - - - -/** - * SearchDeviceType - */ -export const SearchDeviceType = { - /** - * SMARTPHONE - */ - SMARTPHONE:1, - /** - * TABLET - */ - TABLET:2, - /** - * NONE - */ - NONE:3, -}; - -Object.freeze(SearchDeviceType); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchDeviceType extends FfiConverterArrayBuffer { - static #validValues = Object.values(SearchDeviceType); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return SearchDeviceType.SMARTPHONE - case 2: - return SearchDeviceType.TABLET - case 3: - return SearchDeviceType.NONE - default: - throw new UniFFITypeError("Unknown SearchDeviceType variant"); - } - } - - static write(dataStream, value) { - if (value === SearchDeviceType.SMARTPHONE) { - dataStream.writeInt32(1); - return; - } - if (value === SearchDeviceType.TABLET) { - dataStream.writeInt32(2); - return; - } - if (value === SearchDeviceType.NONE) { - dataStream.writeInt32(3); - return; - } - throw new UniFFITypeError("Unknown SearchDeviceType variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for SearchDeviceType`); - } - } -} - - - -/** - * The list of acceptable classifications for a search engine. - */ -export const SearchEngineClassification = { - /** - * GENERAL - */ - GENERAL:2, - /** - * UNKNOWN - */ - UNKNOWN:1, -}; - -Object.freeze(SearchEngineClassification); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchEngineClassification extends FfiConverterArrayBuffer { - static #validValues = Object.values(SearchEngineClassification); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return SearchEngineClassification.GENERAL - case 2: - return SearchEngineClassification.UNKNOWN - default: - throw new UniFFITypeError("Unknown SearchEngineClassification variant"); - } - } - - static write(dataStream, value) { - if (value === SearchEngineClassification.GENERAL) { - dataStream.writeInt32(1); - return; - } - if (value === SearchEngineClassification.UNKNOWN) { - dataStream.writeInt32(2); - return; - } - throw new UniFFITypeError("Unknown SearchEngineClassification variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for SearchEngineClassification`); - } - } -} - - - -/** - * The list of possible update channels for a user's build. - * Use `default` for a self-build or an unknown channel. - */ -export const SearchUpdateChannel = { - /** - * NIGHTLY - */ - NIGHTLY:1, - /** - * AURORA - */ - AURORA:2, - /** - * BETA - */ - BETA:3, - /** - * RELEASE - */ - RELEASE:4, - /** - * ESR - */ - ESR:5, - /** - * DEFAULT - */ - DEFAULT:6, -}; - -Object.freeze(SearchUpdateChannel); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSearchUpdateChannel extends FfiConverterArrayBuffer { - static #validValues = Object.values(SearchUpdateChannel); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return SearchUpdateChannel.NIGHTLY - case 2: - return SearchUpdateChannel.AURORA - case 3: - return SearchUpdateChannel.BETA - case 4: - return SearchUpdateChannel.RELEASE - case 5: - return SearchUpdateChannel.ESR - case 6: - return SearchUpdateChannel.DEFAULT - default: - throw new UniFFITypeError("Unknown SearchUpdateChannel variant"); - } - } - - static write(dataStream, value) { - if (value === SearchUpdateChannel.NIGHTLY) { - dataStream.writeInt32(1); - return; - } - if (value === SearchUpdateChannel.AURORA) { - dataStream.writeInt32(2); - return; - } - if (value === SearchUpdateChannel.BETA) { - dataStream.writeInt32(3); - return; - } - if (value === SearchUpdateChannel.RELEASE) { - dataStream.writeInt32(4); - return; - } - if (value === SearchUpdateChannel.ESR) { - dataStream.writeInt32(5); - return; - } - if (value === SearchUpdateChannel.DEFAULT) { - dataStream.writeInt32(6); - return; - } - throw new UniFFITypeError("Unknown SearchUpdateChannel variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for SearchUpdateChannel`); - } - } -} - - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalu32 extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterU32.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterU32.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterU32.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterU32.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalstring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterString.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterString.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterString.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeJsonEngineUrl extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeJsonEngineUrl.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeJsonEngineUrl.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeJsonEngineUrl.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeJsonEngineUrl.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeSearchEngineUrl extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeSearchEngineUrl.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeSearchEngineUrl.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeSearchEngineUrl.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeSearchEngineUrl.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeJsonEngineMethod extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeJsonEngineMethod.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeJsonEngineMethod.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeJsonEngineMethod.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeJsonEngineMethod.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalSequenceTypeSearchUrlParam extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterSequenceTypeSearchUrlParam.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterSequenceTypeSearchUrlParam.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterSequenceTypeSearchUrlParam.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterSequenceTypeSearchUrlParam.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterString.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterString.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterString.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterString.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeSearchEngineDefinition extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeSearchEngineDefinition.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeSearchEngineDefinition.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeSearchEngineDefinition.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeSearchEngineDefinition.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeSearchUrlParam extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeSearchUrlParam.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeSearchUrlParam.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeSearchUrlParam.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeSearchUrlParam.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - import { FfiConverterTypeRemoteSettingsService, - RemoteSettingsService, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs"; +} from "./RustRemoteSettings.sys.mjs"; // Export the FFIConverter object to make external types work. -export { FfiConverterTypeRemoteSettingsService, RemoteSettingsService }; +export { FfiConverterTypeRemoteSettingsService }; +/** + * SearchEngineSelector parses the JSON configuration for + * search engines and returns the applicable engines depending + * on their region + locale. + */ +export class SearchEngineSelector { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init() { + + const result = UniFFIScaffolding.callSync( + 32, // uniffi_search_fn_constructor_searchengineselector_new + ) + return handleRustResult( + result, + FfiConverterTypeSearchEngineSelector.lift.bind(FfiConverterTypeSearchEngineSelector), + null, + ) + } + /** + * Clears the search configuration from memory if it is known that it is + * not required for a time, e.g. if the configuration will only be re-filtered + * after an app/environment update. + */ + clearSearchConfig() { + + const result = UniFFIScaffolding.callSync( + 33, // uniffi_search_fn_method_searchengineselector_clear_search_config + FfiConverterTypeSearchEngineSelector.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + /** + * Filters the search configuration with the user's given environment, + * and returns the set of engines and parameters that should be presented + * to the user. + */ + filterEngineConfiguration( + userEnvironment) { + + FfiConverterTypeSearchUserEnvironment.checkType(userEnvironment); + const result = UniFFIScaffolding.callSync( + 34, // uniffi_search_fn_method_searchengineselector_filter_engine_configuration + FfiConverterTypeSearchEngineSelector.lower(this), + FfiConverterTypeSearchUserEnvironment.lower(userEnvironment), + ) + return handleRustResult( + result, + FfiConverterTypeRefinedSearchConfig.lift.bind(FfiConverterTypeRefinedSearchConfig), + FfiConverterTypeSearchApiError.lift.bind(FfiConverterTypeSearchApiError), + ) + } + + /** + * setConfigOverrides + */ + setConfigOverrides( + overrides) { + + FfiConverterString.checkType(overrides); + const result = UniFFIScaffolding.callSync( + 35, // uniffi_search_fn_method_searchengineselector_set_config_overrides + FfiConverterTypeSearchEngineSelector.lower(this), + FfiConverterString.lower(overrides), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSearchApiError.lift.bind(FfiConverterTypeSearchApiError), + ) + } + + /** + * Sets the search configuration from the given string. If the configuration + * string is unchanged since the last update, the cached configuration is + * reused to avoid unnecessary reprocessing. This helps optimize performance, + * particularly during test runs where the same configuration may be used + * repeatedly. + */ + setSearchConfig( + configuration) { + + FfiConverterString.checkType(configuration); + const result = UniFFIScaffolding.callSync( + 36, // uniffi_search_fn_method_searchengineselector_set_search_config + FfiConverterTypeSearchEngineSelector.lower(this), + FfiConverterString.lower(configuration), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSearchApiError.lift.bind(FfiConverterTypeSearchApiError), + ) + } + + /** + * Sets the RemoteSettingsService to use. The selector will create the + * relevant remote settings client(s) from the service. + * + * # Params: + * - `service`: The remote settings service instance for the application. + * - `options`: The remote settings options to be passed to the client(s). + * - `apply_engine_overrides`: Whether or not to apply overrides from + * `search-config-v2-overrides` to the selected + * engines. Should be false unless the application + * supports the click URL feature. + */ + async useRemoteSettingsServer( + service, + applyEngineOverrides) { + + FfiConverterTypeRemoteSettingsService.checkType(service); + FfiConverterBoolean.checkType(applyEngineOverrides); + const result = await UniFFIScaffolding.callAsyncWrapper( + 37, // uniffi_search_fn_method_searchengineselector_use_remote_settings_server + FfiConverterTypeSearchEngineSelector.lower(this), + FfiConverterTypeRemoteSettingsService.lower(service), + FfiConverterBoolean.lower(applyEngineOverrides), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSearchEngineSelector extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new SearchEngineSelector(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'SearchEngineSelector' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(6)); + } + + static write(dataStream, value) { + dataStream.writePointer(6, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); + } + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint64(value) + } + static read(dataStream) { + return dataStream.readUint64() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSuggest.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSuggest.sys.mjs index 0c839c519b1b..d288abf196b0 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSuggest.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSuggest.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,45 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a SuggestStore pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerSuggestStore() { - const pointerId = 6; // suggest:SuggestStore + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a SuggestStore pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerSuggestStore(value) { - const pointerId = 6; // suggest:SuggestStore + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - - - // Reads a SuggestStoreBuilder pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerSuggestStoreBuilder() { - const pointerId = 7; // suggest:SuggestStoreBuilder - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a SuggestStoreBuilder pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerSuggestStoreBuilder(value) { - const pointerId = 7; // suggest:SuggestStoreBuilder - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -307,65 +282,144 @@ class FfiConverterArrayBuffer extends FfiConverter { const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; +/** + * Determines whether a "raw" sponsored suggestion URL is equivalent to a + * "cooked" URL. The two URLs are equivalent if they are identical except for + * their replaced template parameters, which can be different. + */ +export function rawSuggestionUrlMatches( + rawUrl, + cookedUrl) { + +FfiConverterString.checkType(rawUrl); +FfiConverterString.checkType(cookedUrl); +const result = UniFFIScaffolding.callSync( + 38, // uniffi_suggest_fn_func_raw_suggestion_url_matches + FfiConverterString.lower(rawUrl), + FfiConverterString.lower(cookedUrl), +) +return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + null, +) +} + // Export the FFIConverter object to make external types work. -export class FfiConverterI32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -2147483648 || value > 2147483647) { - throw new UniFFITypeError(`${value} exceeds the I32 bounds`); - } - } +export class FfiConverterBoolean extends FfiConverter { static computeSize(_value) { - return 4; + return 1; } static lift(value) { - return value; + return value == 1; } static lower(value) { - return value; + if (value) { + return 1; + } else { + return 0; + } } static write(dataStream, value) { - dataStream.writeInt32(value) + dataStream.writeUint8(this.lower(value)) } static read(dataStream) { - return dataStream.readInt32() + return this.lift(dataStream.readUint8()) + } +} +/** + * Additional data about how an FTS match was made + */ +export class FtsMatchInfo { + constructor( + { + prefix, + stemming + } = { + prefix: undefined, + stemming: undefined + } + ) { + try { + FfiConverterBoolean.checkType(prefix) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("prefix"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(stemming) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("stemming"); + } + throw e; + } + /** + * Was this a prefix match (`water b` matched against `water bottle`) + */ + this.prefix = prefix; + /** + * Did the match require stemming? (`run shoes` matched against `running shoes`) + */ + this.stemming = stemming; + } + + equals(other) { + return ( + this.prefix == other.prefix + && this.stemming == other.stemming + ) } } // Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; +export class FfiConverterTypeFtsMatchInfo extends FfiConverterArrayBuffer { + static read(dataStream) { + return new FtsMatchInfo({ + prefix: FfiConverterBoolean.read(dataStream), + stemming: FfiConverterBoolean.read(dataStream), + }); } static write(dataStream, value) { - dataStream.writeUint64(value) + FfiConverterBoolean.write(dataStream, value.prefix); + FfiConverterBoolean.write(dataStream, value.stemming); } - static read(dataStream) { - return dataStream.readUint64() + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterBoolean.computeSize(value.prefix); + totalSize += FfiConverterBoolean.computeSize(value.stemming); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof FtsMatchInfo)) { + throw new UniFFITypeError(`Expected 'FtsMatchInfo', found '${typeof value}'`); + } + try { + FfiConverterBoolean.checkType(value.prefix); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".prefix"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(value.stemming); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".stemming"); + } + throw e; + } } } - // Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { +export class FfiConverterInt64 extends FfiConverter { static checkType(value) { super.checkType(value); if (!Number.isSafeInteger(value)) { @@ -388,49 +442,6 @@ export class FfiConverterI64 extends FfiConverter { return dataStream.readInt64() } } - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -460,943 +471,81 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - // Export the FFIConverter object to make external types work. -export class FfiConverterBytes extends FfiConverterArrayBuffer { - static read(dataStream) { - return dataStream.readBytes() - } - - static write(dataStream, value) { - dataStream.writeBytes(value) - } - - static computeSize(value) { - // The size of the length + 1 byte / item - return 4 + value.length - } - - static checkType(value) { - if (!value instanceof Uint8Array) { - throw new UniFFITypeError(`${value} is not an Uint8Array`); - } - } -} - -/** - * The store is the entry point to the Suggest component. It incrementally - * downloads suggestions from the Remote Settings service, stores them in a - * local database, and returns them in response to user queries. - * - * Your application should create a single store, and manage it as a singleton. - * The store is thread-safe, and supports concurrent queries and ingests. We - * expect that your application will call [`SuggestStore::query()`] to show - * suggestions as the user types into the address bar, and periodically call - * [`SuggestStore::ingest()`] in the background to update the database with - * new suggestions from Remote Settings. - * - * For responsiveness, we recommend always calling `query()` on a worker - * thread. When the user types new input into the address bar, call - * [`SuggestStore::interrupt()`] on the main thread to cancel the query - * for the old input, and unblock the worker thread for the new query. - * - * The store keeps track of the state needed to support incremental ingestion, - * but doesn't schedule the ingestion work itself, or decide how many - * suggestions to ingest at once. This is for two reasons: - * - * 1. The primitives for scheduling background work vary between platforms, and - * aren't available to the lower-level Rust layer. You might use an idle - * timer on Desktop, `WorkManager` on Android, or `BGTaskScheduler` on iOS. - * 2. Ingestion constraints can change, depending on the platform and the needs - * of your application. A mobile device on a metered connection might want - * to request a small subset of the Suggest data and download the rest - * later, while a desktop on a fast link might download the entire dataset - * on the first launch. - */ -export class SuggestStore { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * Creates a Suggest store. - * @returns {SuggestStore} - */ - static init(path,remoteSettingsService) { - const liftResult = (result) => FfiConverterTypeSuggestStore.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(path) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("path"); - } - throw e; - } - try { - FfiConverterTypeRemoteSettingsService.checkType(remoteSettingsService) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("remoteSettingsService"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 53, // suggest:uniffi_suggest_fn_constructor_suggeststore_new - FfiConverterString.lower(path), - FfiConverterTypeRemoteSettingsService.lower(remoteSettingsService), - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Return whether any suggestions have been dismissed. - * @returns {Boolean} - */ - anyDismissedSuggestions() { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 38, // suggest:uniffi_suggest_fn_method_suggeststore_any_dismissed_suggestions - FfiConverterTypeSuggestStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Removes all content from the database. - */ - clear() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 39, // suggest:uniffi_suggest_fn_method_suggeststore_clear - FfiConverterTypeSuggestStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Clear dismissed suggestions - */ - clearDismissedSuggestions() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 40, // suggest:uniffi_suggest_fn_method_suggeststore_clear_dismissed_suggestions - FfiConverterTypeSuggestStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Dismiss a suggestion by its dismissal key. - * - * Dismissed suggestions cannot be fetched again. - * - * Prefer [SuggestStore::dismiss_by_suggestion] if you have a - * `crate::Suggestion`. This method is intended for cases where a - * suggestion originates outside this component. - */ - dismissByKey(key) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(key) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("key"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 41, // suggest:uniffi_suggest_fn_method_suggeststore_dismiss_by_key - FfiConverterTypeSuggestStore.lower(this), - FfiConverterString.lower(key), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Dismiss a suggestion. - * - * Dismissed suggestions cannot be fetched again. - */ - dismissBySuggestion(suggestion) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSuggestion.checkType(suggestion) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("suggestion"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 42, // suggest:uniffi_suggest_fn_method_suggeststore_dismiss_by_suggestion - FfiConverterTypeSuggestStore.lower(this), - FfiConverterTypeSuggestion.lower(suggestion), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Deprecated, use [SuggestStore::dismiss_by_suggestion] or - * [SuggestStore::dismiss_by_key] instead. - * - * Dismiss a suggestion - * - * Dismissed suggestions will not be returned again - */ - dismissSuggestion(suggestionUrl) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(suggestionUrl) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("suggestionUrl"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 43, // suggest:uniffi_suggest_fn_method_suggeststore_dismiss_suggestion - FfiConverterTypeSuggestStore.lower(this), - FfiConverterString.lower(suggestionUrl), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Fetches geonames stored in the database. A geoname represents a - * geographic place. - * - * `query` is a string that will be matched directly against geoname names. - * It is not a query string in the usual Suggest sense. `match_name_prefix` - * determines whether prefix matching is performed on names excluding - * abbreviations and airport codes. When `true`, names that start with - * `query` will match. When false, names that equal `query` will match. - * - * `geoname_type` restricts returned geonames to a [`GeonameType`]. - * - * `filter` restricts returned geonames to certain cities or regions. - * Cities can be restricted to regions by including the regions in - * `filter`, and regions can be restricted to those containing certain - * cities by including the cities in `filter`. This is especially useful - * since city and region names are not unique. `filter` is disjunctive: If - * any item in `filter` matches a geoname, the geoname will be filtered in. - * - * The query can match a single geoname in more than one way. For example, - * it can match both a full name and an abbreviation. The returned vec of - * [`GeonameMatch`] values will include all matches for a geoname, one - * match per `match_type` per geoname. In other words, a matched geoname - * can map to more than one `GeonameMatch`. - * @returns {Array.} - */ - fetchGeonames(query,matchNamePrefix,geonameType,filter) { - const liftResult = (result) => FfiConverterSequenceTypeGeonameMatch.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(query) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("query"); - } - throw e; - } - try { - FfiConverterBool.checkType(matchNamePrefix) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("matchNamePrefix"); - } - throw e; - } - try { - FfiConverterOptionalTypeGeonameType.checkType(geonameType) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("geonameType"); - } - throw e; - } - try { - FfiConverterOptionalSequenceTypeGeoname.checkType(filter) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("filter"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 44, // suggest:uniffi_suggest_fn_method_suggeststore_fetch_geonames - FfiConverterTypeSuggestStore.lower(this), - FfiConverterString.lower(query), - FfiConverterBool.lower(matchNamePrefix), - FfiConverterOptionalTypeGeonameType.lower(geonameType), - FfiConverterOptionalSequenceTypeGeoname.lower(filter), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Returns global Suggest configuration data. - * @returns {SuggestGlobalConfig} - */ - fetchGlobalConfig() { - const liftResult = (result) => FfiConverterTypeSuggestGlobalConfig.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 45, // suggest:uniffi_suggest_fn_method_suggeststore_fetch_global_config - FfiConverterTypeSuggestStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Returns per-provider Suggest configuration data. - * @returns {?SuggestProviderConfig} - */ - fetchProviderConfig(provider) { - const liftResult = (result) => FfiConverterOptionalTypeSuggestProviderConfig.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSuggestionProvider.checkType(provider) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("provider"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 46, // suggest:uniffi_suggest_fn_method_suggeststore_fetch_provider_config - FfiConverterTypeSuggestStore.lower(this), - FfiConverterTypeSuggestionProvider.lower(provider), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Ingests new suggestions from Remote Settings. - * @returns {SuggestIngestionMetrics} - */ - ingest(constraints) { - const liftResult = (result) => FfiConverterTypeSuggestIngestionMetrics.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSuggestIngestionConstraints.checkType(constraints) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("constraints"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 47, // suggest:uniffi_suggest_fn_method_suggeststore_ingest - FfiConverterTypeSuggestStore.lower(this), - FfiConverterTypeSuggestIngestionConstraints.lower(constraints), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Interrupts any ongoing queries. - * - * This should be called when the user types new input into the address - * bar, to ensure that they see fresh suggestions as they type. This - * method does not interrupt any ongoing ingests. - */ - interrupt(kind = null) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterOptionalTypeInterruptKind.checkType(kind) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("kind"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 48, // suggest:uniffi_suggest_fn_method_suggeststore_interrupt - FfiConverterTypeSuggestStore.lower(this), - FfiConverterOptionalTypeInterruptKind.lower(kind), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Return whether a suggestion has been dismissed given its dismissal key. - * - * [SuggestStore::query] will never return dismissed suggestions, so - * normally you never need to know whether a suggestion has been dismissed. - * This method is intended for cases where a dismissal key originates - * outside this component. - * @returns {Boolean} - */ - isDismissedByKey(key) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(key) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("key"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 49, // suggest:uniffi_suggest_fn_method_suggeststore_is_dismissed_by_key - FfiConverterTypeSuggestStore.lower(this), - FfiConverterString.lower(key), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Return whether a suggestion has been dismissed. - * - * [SuggestStore::query] will never return dismissed suggestions, so - * normally you never need to know whether a `Suggestion` has been - * dismissed, but this method can be used to do so. - * @returns {Boolean} - */ - isDismissedBySuggestion(suggestion) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSuggestion.checkType(suggestion) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("suggestion"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 50, // suggest:uniffi_suggest_fn_method_suggeststore_is_dismissed_by_suggestion - FfiConverterTypeSuggestStore.lower(this), - FfiConverterTypeSuggestion.lower(suggestion), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Queries the database for suggestions. - * @returns {Array.} - */ - query(query) { - const liftResult = (result) => FfiConverterSequenceTypeSuggestion.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSuggestionQuery.checkType(query) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("query"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 51, // suggest:uniffi_suggest_fn_method_suggeststore_query - FfiConverterTypeSuggestStore.lower(this), - FfiConverterTypeSuggestionQuery.lower(query), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Queries the database for suggestions. - * @returns {QueryWithMetricsResult} - */ - queryWithMetrics(query) { - const liftResult = (result) => FfiConverterTypeQueryWithMetricsResult.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeSuggestionQuery.checkType(query) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("query"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 52, // suggest:uniffi_suggest_fn_method_suggeststore_query_with_metrics - FfiConverterTypeSuggestStore.lower(this), - FfiConverterTypeSuggestionQuery.lower(query), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestStore extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new SuggestStore(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'SuggestStore' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerSuggestStore()); - } - - static write(dataStream, value) { - dataStream.writePointerSuggestStore(value[uniffiObjectPtr]); - } - - static computeSize(value) { +export class FfiConverterFloat64 extends FfiConverter { + static computeSize(_value) { return 8; } -} - -/** - * Builder for [SuggestStore] - * - * Using a builder is preferred to calling the constructor directly since it's harder to confuse - * the data_path and cache_path strings. - */ -export class SuggestStoreBuilder { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {SuggestStoreBuilder} - */ - static init() { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 61, // suggest:uniffi_suggest_fn_constructor_suggeststorebuilder_new - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * build - * @returns {SuggestStore} - */ - build() { - const liftResult = (result) => FfiConverterTypeSuggestStore.lift(result); - const liftError = (data) => FfiConverterTypeSuggestApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callSync( - 54, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_build - FfiConverterTypeSuggestStoreBuilder.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Deprecated: this is no longer used by the suggest component. - * @returns {SuggestStoreBuilder} - */ - cachePath(path) { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(path) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("path"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 55, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_cache_path - FfiConverterTypeSuggestStoreBuilder.lower(this), - FfiConverterString.lower(path), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * dataPath - * @returns {SuggestStoreBuilder} - */ - dataPath(path) { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(path) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("path"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 56, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_data_path - FfiConverterTypeSuggestStoreBuilder.lower(this), - FfiConverterString.lower(path), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Add an sqlite3 extension to load - * - * library_name should be the name of the library without any extension, for example `libmozsqlite3`. - * entrypoint should be the entry point, for example `sqlite3_fts5_init`. If `null` (the default) - * entry point will be used (see https://sqlite.org/loadext.html for details). - * @returns {SuggestStoreBuilder} - */ - loadExtension(library,entryPoint) { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(library) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("library"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(entryPoint) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("entryPoint"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 57, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_load_extension - FfiConverterTypeSuggestStoreBuilder.lower(this), - FfiConverterString.lower(library), - FfiConverterOptionalstring.lower(entryPoint), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * remoteSettingsBucketName - * @returns {SuggestStoreBuilder} - */ - remoteSettingsBucketName(bucketName) { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(bucketName) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("bucketName"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 58, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_bucket_name - FfiConverterTypeSuggestStoreBuilder.lower(this), - FfiConverterString.lower(bucketName), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * remoteSettingsServer - * @returns {SuggestStoreBuilder} - */ - remoteSettingsServer(server) { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeRemoteSettingsServer.checkType(server) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("server"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 59, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_server - FfiConverterTypeSuggestStoreBuilder.lower(this), - FfiConverterTypeRemoteSettingsServer.lower(server), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * remoteSettingsService - * @returns {SuggestStoreBuilder} - */ - remoteSettingsService(rsService) { - const liftResult = (result) => FfiConverterTypeSuggestStoreBuilder.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeRemoteSettingsService.checkType(rsService) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("rsService"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 60, // suggest:uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_service - FfiConverterTypeSuggestStoreBuilder.lower(this), - FfiConverterTypeRemoteSettingsService.lower(rsService), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestStoreBuilder extends FfiConverter { static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new SuggestStoreBuilder(opts); + return value; } - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'SuggestStoreBuilder' instance"); - } - return ptr; + return value; } - - static read(dataStream) { - return this.lift(dataStream.readPointerSuggestStoreBuilder()); - } - static write(dataStream, value) { - dataStream.writePointerSuggestStoreBuilder(value[uniffiObjectPtr]); + dataStream.writeFloat64(value) } - - static computeSize(value) { - return 8; + static read(dataStream) { + return dataStream.readFloat64() } } - -/** - * Additional data about how an FTS match was made - */ -export class FtsMatchInfo { - constructor({ prefix, stemming } = { prefix: undefined, stemming: undefined }) { - try { - FfiConverterBool.checkType(prefix) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("prefix"); - } - throw e; - } - try { - FfiConverterBool.checkType(stemming) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("stemming"); - } - throw e; - } - /** - * Was this a prefix match (`water b` matched against `water bottle`) - * @type {Boolean} - */ - this.prefix = prefix; - /** - * Did the match require stemming? (`run shoes` matched against `running shoes`) - * @type {Boolean} - */ - this.stemming = stemming; - } - - equals(other) { - return ( - this.prefix == other.prefix && - this.stemming == other.stemming - ) - } -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeFtsMatchInfo extends FfiConverterArrayBuffer { - static read(dataStream) { - return new FtsMatchInfo({ - prefix: FfiConverterBool.read(dataStream), - stemming: FfiConverterBool.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterBool.write(dataStream, value.prefix); - FfiConverterBool.write(dataStream, value.stemming); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterBool.computeSize(value.prefix); - totalSize += FfiConverterBool.computeSize(value.stemming); - return totalSize - } - +export class FfiConverterUInt64 extends FfiConverter { static checkType(value) { super.checkType(value); - if (!(value instanceof FtsMatchInfo)) { - throw new UniFFITypeError(`Expected 'FtsMatchInfo', found '${typeof value}'`); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); } - try { - FfiConverterBool.checkType(value.prefix); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".prefix"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.stemming); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".stemming"); - } - throw e; + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); } } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint64(value) + } + static read(dataStream) { + return dataStream.readUint64() + } } - /** * A single geographic place. - * + * * This corresponds to a single row in the main "geoname" table described in * the GeoNames documentation [1]. We exclude fields we don't need. - * + * * [1]: https://download.geonames.org/export/dump/readme.txt */ export class Geoname { - constructor({ geonameId, name, latitude, longitude, countryCode, admin1Code, population } = { geonameId: undefined, name: undefined, latitude: undefined, longitude: undefined, countryCode: undefined, admin1Code: undefined, population: undefined }) { + constructor( + { + geonameId, + name, + latitude, + longitude, + countryCode, + admin1Code, + population + } = { + geonameId: undefined, + name: undefined, + latitude: undefined, + longitude: undefined, + countryCode: undefined, + admin1Code: undefined, + population: undefined + } + ) { try { - FfiConverterI64.checkType(geonameId) + FfiConverterInt64.checkType(geonameId) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("geonameId"); @@ -1412,7 +561,7 @@ export class Geoname { throw e; } try { - FfiConverterF64.checkType(latitude) + FfiConverterFloat64.checkType(latitude) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("latitude"); @@ -1420,7 +569,7 @@ export class Geoname { throw e; } try { - FfiConverterF64.checkType(longitude) + FfiConverterFloat64.checkType(longitude) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("longitude"); @@ -1444,7 +593,7 @@ export class Geoname { throw e; } try { - FfiConverterU64.checkType(population) + FfiConverterUInt64.checkType(population) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("population"); @@ -1453,7 +602,6 @@ export class Geoname { } /** * The `geonameid` straight from the geoname table. - * @type {number} */ this.geonameId = geonameId; /** @@ -1462,47 +610,41 @@ export class Geoname { * there is such a row, it doesn't always have `is_preferred_name` set, and * in fact fact there may be another row with a different name with * `is_preferred_name` set. - * @type {string} */ this.name = name; /** * Latitude in decimal degrees. - * @type {number} */ this.latitude = latitude; /** * Longitude in decimal degrees. - * @type {number} */ this.longitude = longitude; /** * ISO-3166 two-letter uppercase country code, e.g., "US". - * @type {string} */ this.countryCode = countryCode; /** * The top-level administrative region for the place within its country, * like a state or province. For the U.S., the two-letter uppercase state * abbreviation. - * @type {string} */ this.admin1Code = admin1Code; /** * Population size. - * @type {number} */ this.population = population; } equals(other) { return ( - this.geonameId == other.geonameId && - this.name == other.name && - this.latitude == other.latitude && - this.longitude == other.longitude && - this.countryCode == other.countryCode && - this.admin1Code == other.admin1Code && - this.population == other.population + this.geonameId == other.geonameId + && this.name == other.name + && this.latitude == other.latitude + && this.longitude == other.longitude + && this.countryCode == other.countryCode + && this.admin1Code == other.admin1Code + && this.population == other.population ) } } @@ -1511,34 +653,34 @@ export class Geoname { export class FfiConverterTypeGeoname extends FfiConverterArrayBuffer { static read(dataStream) { return new Geoname({ - geonameId: FfiConverterI64.read(dataStream), + geonameId: FfiConverterInt64.read(dataStream), name: FfiConverterString.read(dataStream), - latitude: FfiConverterF64.read(dataStream), - longitude: FfiConverterF64.read(dataStream), + latitude: FfiConverterFloat64.read(dataStream), + longitude: FfiConverterFloat64.read(dataStream), countryCode: FfiConverterString.read(dataStream), admin1Code: FfiConverterString.read(dataStream), - population: FfiConverterU64.read(dataStream), + population: FfiConverterUInt64.read(dataStream), }); } static write(dataStream, value) { - FfiConverterI64.write(dataStream, value.geonameId); + FfiConverterInt64.write(dataStream, value.geonameId); FfiConverterString.write(dataStream, value.name); - FfiConverterF64.write(dataStream, value.latitude); - FfiConverterF64.write(dataStream, value.longitude); + FfiConverterFloat64.write(dataStream, value.latitude); + FfiConverterFloat64.write(dataStream, value.longitude); FfiConverterString.write(dataStream, value.countryCode); FfiConverterString.write(dataStream, value.admin1Code); - FfiConverterU64.write(dataStream, value.population); + FfiConverterUInt64.write(dataStream, value.population); } static computeSize(value) { let totalSize = 0; - totalSize += FfiConverterI64.computeSize(value.geonameId); + totalSize += FfiConverterInt64.computeSize(value.geonameId); totalSize += FfiConverterString.computeSize(value.name); - totalSize += FfiConverterF64.computeSize(value.latitude); - totalSize += FfiConverterF64.computeSize(value.longitude); + totalSize += FfiConverterFloat64.computeSize(value.latitude); + totalSize += FfiConverterFloat64.computeSize(value.longitude); totalSize += FfiConverterString.computeSize(value.countryCode); totalSize += FfiConverterString.computeSize(value.admin1Code); - totalSize += FfiConverterU64.computeSize(value.population); + totalSize += FfiConverterUInt64.computeSize(value.population); return totalSize } @@ -1548,7 +690,7 @@ export class FfiConverterTypeGeoname extends FfiConverterArrayBuffer { throw new UniFFITypeError(`Expected 'Geoname', found '${typeof value}'`); } try { - FfiConverterI64.checkType(value.geonameId); + FfiConverterInt64.checkType(value.geonameId); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".geonameId"); @@ -1564,7 +706,7 @@ export class FfiConverterTypeGeoname extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterF64.checkType(value.latitude); + FfiConverterFloat64.checkType(value.latitude); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".latitude"); @@ -1572,7 +714,7 @@ export class FfiConverterTypeGeoname extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterF64.checkType(value.longitude); + FfiConverterFloat64.checkType(value.longitude); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".longitude"); @@ -1596,7 +738,7 @@ export class FfiConverterTypeGeoname extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterU64.checkType(value.population); + FfiConverterUInt64.checkType(value.population); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".population"); @@ -1606,828 +748,6 @@ export class FfiConverterTypeGeoname extends FfiConverterArrayBuffer { } } -/** - * A fetched geoname with info on how it was matched. - */ -export class GeonameMatch { - constructor({ geoname, matchType, prefix } = { geoname: undefined, matchType: undefined, prefix: undefined }) { - try { - FfiConverterTypeGeoname.checkType(geoname) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("geoname"); - } - throw e; - } - try { - FfiConverterTypeGeonameMatchType.checkType(matchType) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("matchType"); - } - throw e; - } - try { - FfiConverterBool.checkType(prefix) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("prefix"); - } - throw e; - } - /** - * The geoname that was matched. - * @type {Geoname} - */ - this.geoname = geoname; - /** - * The type of name that was matched. - * @type {GeonameMatchType} - */ - this.matchType = matchType; - /** - * Whether the name was matched by prefix. - * @type {Boolean} - */ - this.prefix = prefix; - } - - equals(other) { - return ( - this.geoname.equals(other.geoname) && - this.matchType == other.matchType && - this.prefix == other.prefix - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeGeonameMatch extends FfiConverterArrayBuffer { - static read(dataStream) { - return new GeonameMatch({ - geoname: FfiConverterTypeGeoname.read(dataStream), - matchType: FfiConverterTypeGeonameMatchType.read(dataStream), - prefix: FfiConverterBool.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterTypeGeoname.write(dataStream, value.geoname); - FfiConverterTypeGeonameMatchType.write(dataStream, value.matchType); - FfiConverterBool.write(dataStream, value.prefix); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterTypeGeoname.computeSize(value.geoname); - totalSize += FfiConverterTypeGeonameMatchType.computeSize(value.matchType); - totalSize += FfiConverterBool.computeSize(value.prefix); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof GeonameMatch)) { - throw new UniFFITypeError(`Expected 'GeonameMatch', found '${typeof value}'`); - } - try { - FfiConverterTypeGeoname.checkType(value.geoname); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".geoname"); - } - throw e; - } - try { - FfiConverterTypeGeonameMatchType.checkType(value.matchType); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".matchType"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.prefix); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".prefix"); - } - throw e; - } - } -} - -/** - * Single sample for a Glean labeled_timing_distribution - */ -export class LabeledTimingSample { - constructor({ label, value } = { label: undefined, value: undefined }) { - try { - FfiConverterString.checkType(label) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("label"); - } - throw e; - } - try { - FfiConverterU64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - /** - * @type {string} - */ - this.label = label; - /** - * Time in microseconds - * @type {number} - */ - this.value = value; - } - - equals(other) { - return ( - this.label == other.label && - this.value == other.value - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeLabeledTimingSample extends FfiConverterArrayBuffer { - static read(dataStream) { - return new LabeledTimingSample({ - label: FfiConverterString.read(dataStream), - value: FfiConverterU64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterString.write(dataStream, value.label); - FfiConverterU64.write(dataStream, value.value); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterString.computeSize(value.label); - totalSize += FfiConverterU64.computeSize(value.value); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof LabeledTimingSample)) { - throw new UniFFITypeError(`Expected 'LabeledTimingSample', found '${typeof value}'`); - } - try { - FfiConverterString.checkType(value.label); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".label"); - } - throw e; - } - try { - FfiConverterU64.checkType(value.value); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".value"); - } - throw e; - } - } -} - -/** - * QueryWithMetricsResult - */ -export class QueryWithMetricsResult { - constructor({ suggestions, queryTimes } = { suggestions: undefined, queryTimes: undefined }) { - try { - FfiConverterSequenceTypeSuggestion.checkType(suggestions) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("suggestions"); - } - throw e; - } - try { - FfiConverterSequenceTypeLabeledTimingSample.checkType(queryTimes) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("queryTimes"); - } - throw e; - } - /** - * @type {Array.} - */ - this.suggestions = suggestions; - /** - * Samples for the `suggest.query_time` metric - * @type {Array.} - */ - this.queryTimes = queryTimes; - } - - equals(other) { - return ( - this.suggestions == other.suggestions && - this.queryTimes == other.queryTimes - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeQueryWithMetricsResult extends FfiConverterArrayBuffer { - static read(dataStream) { - return new QueryWithMetricsResult({ - suggestions: FfiConverterSequenceTypeSuggestion.read(dataStream), - queryTimes: FfiConverterSequenceTypeLabeledTimingSample.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterSequenceTypeSuggestion.write(dataStream, value.suggestions); - FfiConverterSequenceTypeLabeledTimingSample.write(dataStream, value.queryTimes); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterSequenceTypeSuggestion.computeSize(value.suggestions); - totalSize += FfiConverterSequenceTypeLabeledTimingSample.computeSize(value.queryTimes); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof QueryWithMetricsResult)) { - throw new UniFFITypeError(`Expected 'QueryWithMetricsResult', found '${typeof value}'`); - } - try { - FfiConverterSequenceTypeSuggestion.checkType(value.suggestions); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".suggestions"); - } - throw e; - } - try { - FfiConverterSequenceTypeLabeledTimingSample.checkType(value.queryTimes); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".queryTimes"); - } - throw e; - } - } -} - -/** - * Global Suggest configuration data. - */ -export class SuggestGlobalConfig { - constructor({ showLessFrequentlyCap } = { showLessFrequentlyCap: undefined }) { - try { - FfiConverterI32.checkType(showLessFrequentlyCap) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("showLessFrequentlyCap"); - } - throw e; - } - /** - * @type {number} - */ - this.showLessFrequentlyCap = showLessFrequentlyCap; - } - - equals(other) { - return ( - this.showLessFrequentlyCap == other.showLessFrequentlyCap - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestGlobalConfig extends FfiConverterArrayBuffer { - static read(dataStream) { - return new SuggestGlobalConfig({ - showLessFrequentlyCap: FfiConverterI32.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterI32.write(dataStream, value.showLessFrequentlyCap); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterI32.computeSize(value.showLessFrequentlyCap); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof SuggestGlobalConfig)) { - throw new UniFFITypeError(`Expected 'SuggestGlobalConfig', found '${typeof value}'`); - } - try { - FfiConverterI32.checkType(value.showLessFrequentlyCap); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".showLessFrequentlyCap"); - } - throw e; - } - } -} - -/** - * Constraints limit which suggestions to ingest from Remote Settings. - */ -export class SuggestIngestionConstraints { - constructor({ providers = null, providerConstraints = null, emptyOnly = false } = { providers: undefined, providerConstraints: undefined, emptyOnly: undefined }) { - try { - FfiConverterOptionalSequenceTypeSuggestionProvider.checkType(providers) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("providers"); - } - throw e; - } - try { - FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(providerConstraints) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("providerConstraints"); - } - throw e; - } - try { - FfiConverterBool.checkType(emptyOnly) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("emptyOnly"); - } - throw e; - } - /** - * @type {?Array.} - */ - this.providers = providers; - /** - * @type {?SuggestionProviderConstraints} - */ - this.providerConstraints = providerConstraints; - /** - * Only run ingestion if the table `suggestions` is empty - * - * @type {Boolean} - */ - this.emptyOnly = emptyOnly; - } - - equals(other) { - return ( - this.providers == other.providers && - this.providerConstraints == other.providerConstraints && - this.emptyOnly == other.emptyOnly - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestIngestionConstraints extends FfiConverterArrayBuffer { - static read(dataStream) { - return new SuggestIngestionConstraints({ - providers: FfiConverterOptionalSequenceTypeSuggestionProvider.read(dataStream), - providerConstraints: FfiConverterOptionalTypeSuggestionProviderConstraints.read(dataStream), - emptyOnly: FfiConverterBool.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterOptionalSequenceTypeSuggestionProvider.write(dataStream, value.providers); - FfiConverterOptionalTypeSuggestionProviderConstraints.write(dataStream, value.providerConstraints); - FfiConverterBool.write(dataStream, value.emptyOnly); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterOptionalSequenceTypeSuggestionProvider.computeSize(value.providers); - totalSize += FfiConverterOptionalTypeSuggestionProviderConstraints.computeSize(value.providerConstraints); - totalSize += FfiConverterBool.computeSize(value.emptyOnly); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof SuggestIngestionConstraints)) { - throw new UniFFITypeError(`Expected 'SuggestIngestionConstraints', found '${typeof value}'`); - } - try { - FfiConverterOptionalSequenceTypeSuggestionProvider.checkType(value.providers); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".providers"); - } - throw e; - } - try { - FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(value.providerConstraints); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".providerConstraints"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.emptyOnly); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".emptyOnly"); - } - throw e; - } - } -} - -/** - * Ingestion metrics - * - * These are recorded during [crate::Store::ingest] and returned to the consumer to record. - */ -export class SuggestIngestionMetrics { - constructor({ ingestionTimes, downloadTimes } = { ingestionTimes: undefined, downloadTimes: undefined }) { - try { - FfiConverterSequenceTypeLabeledTimingSample.checkType(ingestionTimes) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ingestionTimes"); - } - throw e; - } - try { - FfiConverterSequenceTypeLabeledTimingSample.checkType(downloadTimes) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("downloadTimes"); - } - throw e; - } - /** - * Samples for the `suggest.ingestion_time` metric - * @type {Array.} - */ - this.ingestionTimes = ingestionTimes; - /** - * Samples for the `suggest.ingestion_download_time` metric - * @type {Array.} - */ - this.downloadTimes = downloadTimes; - } - - equals(other) { - return ( - this.ingestionTimes == other.ingestionTimes && - this.downloadTimes == other.downloadTimes - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestIngestionMetrics extends FfiConverterArrayBuffer { - static read(dataStream) { - return new SuggestIngestionMetrics({ - ingestionTimes: FfiConverterSequenceTypeLabeledTimingSample.read(dataStream), - downloadTimes: FfiConverterSequenceTypeLabeledTimingSample.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterSequenceTypeLabeledTimingSample.write(dataStream, value.ingestionTimes); - FfiConverterSequenceTypeLabeledTimingSample.write(dataStream, value.downloadTimes); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterSequenceTypeLabeledTimingSample.computeSize(value.ingestionTimes); - totalSize += FfiConverterSequenceTypeLabeledTimingSample.computeSize(value.downloadTimes); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof SuggestIngestionMetrics)) { - throw new UniFFITypeError(`Expected 'SuggestIngestionMetrics', found '${typeof value}'`); - } - try { - FfiConverterSequenceTypeLabeledTimingSample.checkType(value.ingestionTimes); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".ingestionTimes"); - } - throw e; - } - try { - FfiConverterSequenceTypeLabeledTimingSample.checkType(value.downloadTimes); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".downloadTimes"); - } - throw e; - } - } -} - -/** - * Some providers manage multiple suggestion subtypes. Queries, ingests, and - * other operations on those providers must be constrained to a desired subtype. - */ -export class SuggestionProviderConstraints { - constructor({ dynamicSuggestionTypes = null, ampAlternativeMatching = null } = { dynamicSuggestionTypes: undefined, ampAlternativeMatching: undefined }) { - try { - FfiConverterOptionalSequencestring.checkType(dynamicSuggestionTypes) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("dynamicSuggestionTypes"); - } - throw e; - } - try { - FfiConverterOptionalTypeAmpMatchingStrategy.checkType(ampAlternativeMatching) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ampAlternativeMatching"); - } - throw e; - } - /** - * Which dynamic suggestions should we fetch or ingest? Corresponds to the - * `suggestion_type` value in dynamic suggestions remote settings records. - * @type {?Array.} - */ - this.dynamicSuggestionTypes = dynamicSuggestionTypes; - /** - * Which strategy should we use for the AMP queries? - * Use None for the default strategy. - * @type {?AmpMatchingStrategy} - */ - this.ampAlternativeMatching = ampAlternativeMatching; - } - - equals(other) { - return ( - this.dynamicSuggestionTypes == other.dynamicSuggestionTypes && - this.ampAlternativeMatching == other.ampAlternativeMatching - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestionProviderConstraints extends FfiConverterArrayBuffer { - static read(dataStream) { - return new SuggestionProviderConstraints({ - dynamicSuggestionTypes: FfiConverterOptionalSequencestring.read(dataStream), - ampAlternativeMatching: FfiConverterOptionalTypeAmpMatchingStrategy.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterOptionalSequencestring.write(dataStream, value.dynamicSuggestionTypes); - FfiConverterOptionalTypeAmpMatchingStrategy.write(dataStream, value.ampAlternativeMatching); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterOptionalSequencestring.computeSize(value.dynamicSuggestionTypes); - totalSize += FfiConverterOptionalTypeAmpMatchingStrategy.computeSize(value.ampAlternativeMatching); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof SuggestionProviderConstraints)) { - throw new UniFFITypeError(`Expected 'SuggestionProviderConstraints', found '${typeof value}'`); - } - try { - FfiConverterOptionalSequencestring.checkType(value.dynamicSuggestionTypes); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".dynamicSuggestionTypes"); - } - throw e; - } - try { - FfiConverterOptionalTypeAmpMatchingStrategy.checkType(value.ampAlternativeMatching); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".ampAlternativeMatching"); - } - throw e; - } - } -} - -/** - * A query for suggestions to show in the address bar. - */ -export class SuggestionQuery { - constructor({ keyword, providers, providerConstraints = null, limit = null } = { keyword: undefined, providers: undefined, providerConstraints: undefined, limit: undefined }) { - try { - FfiConverterString.checkType(keyword) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("keyword"); - } - throw e; - } - try { - FfiConverterSequenceTypeSuggestionProvider.checkType(providers) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("providers"); - } - throw e; - } - try { - FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(providerConstraints) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("providerConstraints"); - } - throw e; - } - try { - FfiConverterOptionali32.checkType(limit) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("limit"); - } - throw e; - } - /** - * @type {string} - */ - this.keyword = keyword; - /** - * @type {Array.} - */ - this.providers = providers; - /** - * @type {?SuggestionProviderConstraints} - */ - this.providerConstraints = providerConstraints; - /** - * @type {?number} - */ - this.limit = limit; - } - - equals(other) { - return ( - this.keyword == other.keyword && - this.providers == other.providers && - this.providerConstraints == other.providerConstraints && - this.limit == other.limit - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestionQuery extends FfiConverterArrayBuffer { - static read(dataStream) { - return new SuggestionQuery({ - keyword: FfiConverterString.read(dataStream), - providers: FfiConverterSequenceTypeSuggestionProvider.read(dataStream), - providerConstraints: FfiConverterOptionalTypeSuggestionProviderConstraints.read(dataStream), - limit: FfiConverterOptionali32.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterString.write(dataStream, value.keyword); - FfiConverterSequenceTypeSuggestionProvider.write(dataStream, value.providers); - FfiConverterOptionalTypeSuggestionProviderConstraints.write(dataStream, value.providerConstraints); - FfiConverterOptionali32.write(dataStream, value.limit); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterString.computeSize(value.keyword); - totalSize += FfiConverterSequenceTypeSuggestionProvider.computeSize(value.providers); - totalSize += FfiConverterOptionalTypeSuggestionProviderConstraints.computeSize(value.providerConstraints); - totalSize += FfiConverterOptionali32.computeSize(value.limit); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof SuggestionQuery)) { - throw new UniFFITypeError(`Expected 'SuggestionQuery', found '${typeof value}'`); - } - try { - FfiConverterString.checkType(value.keyword); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".keyword"); - } - throw e; - } - try { - FfiConverterSequenceTypeSuggestionProvider.checkType(value.providers); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".providers"); - } - throw e; - } - try { - FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(value.providerConstraints); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".providerConstraints"); - } - throw e; - } - try { - FfiConverterOptionali32.checkType(value.limit); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".limit"); - } - throw e; - } - } -} - - -/** - * AmpMatchingStrategy - */ -export const AmpMatchingStrategy = { - /** - * Disable keywords added via keyword expansion. - * This eliminates keywords that for terms related to the "real" keywords, for example - * misspellings like "underarmor" instead of "under armor"'. - */ - NO_KEYWORD_EXPANSION:1, - /** - * Use FTS matching against the full keywords, joined together. - */ - FTS_AGAINST_FULL_KEYWORDS:2, - /** - * Use FTS matching against the title field - */ - FTS_AGAINST_TITLE:3, -}; - -Object.freeze(AmpMatchingStrategy); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeAmpMatchingStrategy extends FfiConverterArrayBuffer { - static #validValues = Object.values(AmpMatchingStrategy); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return AmpMatchingStrategy.NO_KEYWORD_EXPANSION - case 2: - return AmpMatchingStrategy.FTS_AGAINST_FULL_KEYWORDS - case 3: - return AmpMatchingStrategy.FTS_AGAINST_TITLE - default: - throw new UniFFITypeError("Unknown AmpMatchingStrategy variant"); - } - } - - static write(dataStream, value) { - if (value === AmpMatchingStrategy.NO_KEYWORD_EXPANSION) { - dataStream.writeInt32(1); - return; - } - if (value === AmpMatchingStrategy.FTS_AGAINST_FULL_KEYWORDS) { - dataStream.writeInt32(2); - return; - } - if (value === AmpMatchingStrategy.FTS_AGAINST_TITLE) { - dataStream.writeInt32(3); - return; - } - throw new UniFFITypeError("Unknown AmpMatchingStrategy variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for AmpMatchingStrategy`); - } - } -} - - - /** * GeonameMatchType */ @@ -2435,24 +755,21 @@ export const GeonameMatchType = { /** * For U.S. states, abbreviations are the usual two-letter codes ("CA"). */ - ABBREVIATION:0, + ABBREVIATION: 1, /** * AIRPORT_CODE */ - AIRPORT_CODE:1, + AIRPORT_CODE: 2, /** * This includes any names that aren't abbreviations or airport codes. */ - NAME:2, + NAME: 3, }; - Object.freeze(GeonameMatchType); + // Export the FFIConverter object to make external types work. export class FfiConverterTypeGeonameMatchType extends FfiConverterArrayBuffer { - static #validValues = Object.values(GeonameMatchType); - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { case 1: return GeonameMatchType.ABBREVIATION @@ -2486,56 +803,385 @@ export class FfiConverterTypeGeonameMatchType extends FfiConverterArrayBuffer { } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { + if (!Number.isInteger(value) || value < 1 || value > 3) { throw new UniFFITypeError(`${value} is not a valid value for GeonameMatchType`); } } } - - - /** - * The type of a geoname. + * A fetched geoname with info on how it was matched. */ -export const GeonameType = { - /** - * CITY - */ - CITY:0, - /** - * REGION - */ - REGION:1, -}; +export class GeonameMatch { + constructor( + { + geoname, + matchType, + prefix + } = { + geoname: undefined, + matchType: undefined, + prefix: undefined + } + ) { + try { + FfiConverterTypeGeoname.checkType(geoname) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("geoname"); + } + throw e; + } + try { + FfiConverterTypeGeonameMatchType.checkType(matchType) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("matchType"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(prefix) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("prefix"); + } + throw e; + } + /** + * The geoname that was matched. + */ + this.geoname = geoname; + /** + * The type of name that was matched. + */ + this.matchType = matchType; + /** + * Whether the name was matched by prefix. + */ + this.prefix = prefix; + } + + equals(other) { + return ( + this.geoname.equals(other.geoname) + && this.matchType == other.matchType + && this.prefix == other.prefix + ) + } +} -Object.freeze(GeonameType); // Export the FFIConverter object to make external types work. -export class FfiConverterTypeGeonameType extends FfiConverterArrayBuffer { - static #validValues = Object.values(GeonameType); +export class FfiConverterTypeGeonameMatch extends FfiConverterArrayBuffer { + static read(dataStream) { + return new GeonameMatch({ + geoname: FfiConverterTypeGeoname.read(dataStream), + matchType: FfiConverterTypeGeonameMatchType.read(dataStream), + prefix: FfiConverterBoolean.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterTypeGeoname.write(dataStream, value.geoname); + FfiConverterTypeGeonameMatchType.write(dataStream, value.matchType); + FfiConverterBoolean.write(dataStream, value.prefix); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterTypeGeoname.computeSize(value.geoname); + totalSize += FfiConverterTypeGeonameMatchType.computeSize(value.matchType); + totalSize += FfiConverterBoolean.computeSize(value.prefix); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof GeonameMatch)) { + throw new UniFFITypeError(`Expected 'GeonameMatch', found '${typeof value}'`); + } + try { + FfiConverterTypeGeoname.checkType(value.geoname); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".geoname"); + } + throw e; + } + try { + FfiConverterTypeGeonameMatchType.checkType(value.matchType); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".matchType"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(value.prefix); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".prefix"); + } + throw e; + } + } +} +/** + * Single sample for a Glean labeled_timing_distribution + */ +export class LabeledTimingSample { + constructor( + { + label, + value + } = { + label: undefined, + value: undefined + } + ) { + try { + FfiConverterString.checkType(label) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("label"); + } + throw e; + } + try { + FfiConverterUInt64.checkType(value) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("value"); + } + throw e; + } + /** + * label + */ + this.label = label; + /** + * Time in microseconds + */ + this.value = value; + } + + equals(other) { + return ( + this.label == other.label + && this.value == other.value + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeLabeledTimingSample extends FfiConverterArrayBuffer { + static read(dataStream) { + return new LabeledTimingSample({ + label: FfiConverterString.read(dataStream), + value: FfiConverterUInt64.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterString.write(dataStream, value.label); + FfiConverterUInt64.write(dataStream, value.value); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterString.computeSize(value.label); + totalSize += FfiConverterUInt64.computeSize(value.value); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof LabeledTimingSample)) { + throw new UniFFITypeError(`Expected 'LabeledTimingSample', found '${typeof value}'`); + } + try { + FfiConverterString.checkType(value.label); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".label"); + } + throw e; + } + try { + FfiConverterUInt64.checkType(value.value); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".value"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterBytes extends FfiConverterArrayBuffer { + static read(dataStream) { + return dataStream.readBytes() + } + + static write(dataStream, value) { + dataStream.writeBytes(value) + } + + static computeSize(value) { + // The size of the length + 1 byte / item + return 4 + value.length + } + + static checkType(value) { + if (!value instanceof Uint8Array) { + throw new UniFFITypeError(`${value} is not an Uint8Array`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalBytes extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterBytes.checkType(value) + } + } static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null case 1: - return GeonameType.CITY - case 2: - return GeonameType.REGION + return FfiConverterBytes.read(dataStream) default: - throw new UniFFITypeError("Unknown GeonameType variant"); + throw new UniFFIError(`Unexpected code: ${code}`); } } static write(dataStream, value) { - if (value === GeonameType.CITY) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterBytes.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterBytes.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterString.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterString.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterString.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeFtsMatchInfo extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeFtsMatchInfo.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeFtsMatchInfo.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeFtsMatchInfo.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeFtsMatchInfo.computeSize(value) + } +} + +/** + * Subject type for Yelp suggestion. + */ +export const YelpSubjectType = { + /** + * SERVICE + */ + SERVICE: 1, + /** + * BUSINESS + */ + BUSINESS: 2, +}; +Object.freeze(YelpSubjectType); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeYelpSubjectType extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return YelpSubjectType.SERVICE + case 2: + return YelpSubjectType.BUSINESS + default: + throw new UniFFITypeError("Unknown YelpSubjectType variant"); + } + } + + static write(dataStream, value) { + if (value === YelpSubjectType.SERVICE) { dataStream.writeInt32(1); return; } - if (value === GeonameType.REGION) { + if (value === YelpSubjectType.BUSINESS) { dataStream.writeInt32(2); return; } - throw new UniFFITypeError("Unknown GeonameType variant"); + throw new UniFFITypeError("Unknown YelpSubjectType variant"); } static computeSize(value) { @@ -2543,294 +1189,108 @@ export class FfiConverterTypeGeonameType extends FfiConverterArrayBuffer { } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for GeonameType`); + if (!Number.isInteger(value) || value < 1 || value > 2) { + throw new UniFFITypeError(`${value} is not a valid value for YelpSubjectType`); } } } - - - -/** - * What should be interrupted when [SuggestStore::interrupt] is called? - */ -export const InterruptKind = { - /** - * Interrupt read operations like [SuggestStore::query] - */ - READ:0, - /** - * Interrupt write operations. This mostly means [SuggestStore::ingest], but - * other operations may also be interrupted. - */ - WRITE:1, - /** - * Interrupt both read and write operations, - */ - READ_WRITE:2, -}; - -Object.freeze(InterruptKind); // Export the FFIConverter object to make external types work. -export class FfiConverterTypeInterruptKind extends FfiConverterArrayBuffer { - static #validValues = Object.values(InterruptKind); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return InterruptKind.READ - case 2: - return InterruptKind.WRITE - case 3: - return InterruptKind.READ_WRITE - default: - throw new UniFFITypeError("Unknown InterruptKind variant"); - } - } - - static write(dataStream, value) { - if (value === InterruptKind.READ) { - dataStream.writeInt32(1); - return; - } - if (value === InterruptKind.WRITE) { - dataStream.writeInt32(2); - return; - } - if (value === InterruptKind.READ_WRITE) { - dataStream.writeInt32(3); - return; - } - throw new UniFFITypeError("Unknown InterruptKind variant"); - } - - static computeSize(value) { - return 4; - } - +export class FfiConverterOptionalFloat64 extends FfiConverterArrayBuffer { static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for InterruptKind`); - } + if (value !== undefined && value !== null) { + FfiConverterFloat64.checkType(value) + } } -} - - - - -/** - * The error type for all Suggest component operations. These errors are - * exposed to your application, which should handle them as needed. - */ -export class SuggestApiError extends Error {} - - -/** - * Network - */ -export class Network extends SuggestApiError { - - constructor( - reason, - ...params - ) { - const message = `reason: ${ reason }`; - super(message, ...params); - this.reason = reason; - } - toString() { - return `Network: ${super.toString()}` - } -} - -/** - * The server requested a backoff after too many requests - */ -export class Backoff extends SuggestApiError { - - constructor( - seconds, - ...params - ) { - const message = `seconds: ${ seconds }`; - super(message, ...params); - this.seconds = seconds; - } - toString() { - return `Backoff: ${super.toString()}` - } -} - -/** - * An operation was interrupted by calling `SuggestStore.interrupt()` - */ -export class Interrupted extends SuggestApiError { - - constructor( - ...params - ) { - super(...params); - } - toString() { - return `Interrupted: ${super.toString()}` - } -} - -/** - * Other - */ -export class Other extends SuggestApiError { - - constructor( - reason, - ...params - ) { - const message = `reason: ${ reason }`; - super(message, ...params); - this.reason = reason; - } - toString() { - return `Other: ${super.toString()}` - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestApiError extends FfiConverterArrayBuffer { static read(dataStream) { - switch (dataStream.readInt32()) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null case 1: - return new Network( - FfiConverterString.read(dataStream) - ); - case 2: - return new Backoff( - FfiConverterU64.read(dataStream) - ); - case 3: - return new Interrupted( - ); - case 4: - return new Other( - FfiConverterString.read(dataStream) - ); + return FfiConverterFloat64.read(dataStream) default: - throw new UniFFITypeError("Unknown SuggestApiError variant"); - } - } - static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof Network) { - totalSize += FfiConverterString.computeSize(value.reason); - return totalSize; - } - if (value instanceof Backoff) { - totalSize += FfiConverterU64.computeSize(value.seconds); - return totalSize; - } - if (value instanceof Interrupted) { - return totalSize; - } - if (value instanceof Other) { - totalSize += FfiConverterString.computeSize(value.reason); - return totalSize; - } - throw new UniFFITypeError("Unknown SuggestApiError variant"); - } - static write(dataStream, value) { - if (value instanceof Network) { - dataStream.writeInt32(1); - FfiConverterString.write(dataStream, value.reason); - return; - } - if (value instanceof Backoff) { - dataStream.writeInt32(2); - FfiConverterU64.write(dataStream, value.seconds); - return; - } - if (value instanceof Interrupted) { - dataStream.writeInt32(3); - return; - } - if (value instanceof Other) { - dataStream.writeInt32(4); - FfiConverterString.write(dataStream, value.reason); - return; - } - throw new UniFFITypeError("Unknown SuggestApiError variant"); - } - - static errorClass = SuggestApiError; -} - - -/** - * Per-provider configuration data. - */ -export class SuggestProviderConfig {} -/** - * Weather - */ -SuggestProviderConfig.Weather = class extends SuggestProviderConfig{ - constructor( - score, - minKeywordLength - ) { - super(); - this.score = score; - this.minKeywordLength = minKeywordLength; - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSuggestProviderConfig extends FfiConverterArrayBuffer { - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return new SuggestProviderConfig.Weather( - FfiConverterF64.read(dataStream), - FfiConverterI32.read(dataStream) - ); - default: - throw new UniFFITypeError("Unknown SuggestProviderConfig variant"); + throw new UniFFIError(`Unexpected code: ${code}`); } } static write(dataStream, value) { - if (value instanceof SuggestProviderConfig.Weather) { - dataStream.writeInt32(1); - FfiConverterF64.write(dataStream, value.score); - FfiConverterI32.write(dataStream, value.minKeywordLength); + if (value === null || value === undefined) { + dataStream.writeUint8(0); return; } - throw new UniFFITypeError("Unknown SuggestProviderConfig variant"); + dataStream.writeUint8(1); + FfiConverterFloat64.write(dataStream, value) } static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof SuggestProviderConfig.Weather) { - totalSize += FfiConverterF64.computeSize(value.score); - totalSize += FfiConverterI32.computeSize(value.minKeywordLength); - return totalSize; + if (value === null || value === undefined) { + return 1; } - throw new UniFFITypeError("Unknown SuggestProviderConfig variant"); + return 1 + FfiConverterFloat64.computeSize(value) } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeJsonValue extends FfiConverter { + static lift(buf) { + return FfiConverterString.lift(buf); + } + + static lower(buf) { + return FfiConverterString.lower(buf); + } + + static write(dataStream, value) { + FfiConverterString.write(dataStream, value); + } + + static read(buf) { + return FfiConverterString.read(buf); + } + + static computeSize(value) { + return FfiConverterString.computeSize(value); + } +} +// TODO: We should also allow JS to customize the type eventually. +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeJsonValue extends FfiConverterArrayBuffer { static checkType(value) { - if (value === undefined || value === null || !(value instanceof SuggestProviderConfig)) { - throw new UniFFITypeError(`${value} is not a subclass instance of SuggestProviderConfig`); - } + if (value !== undefined && value !== null) { + FfiConverterTypeJsonValue.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeJsonValue.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeJsonValue.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeJsonValue.computeSize(value) } } - - /** * A suggestion from the database to show in the address bar. */ @@ -3048,38 +1508,37 @@ Suggestion.Dynamic = class extends Suggestion{ // Export the FFIConverter object to make external types work. export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { case 1: return new Suggestion.Amp( FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterOptionalbytes.read(dataStream), - FfiConverterOptionalstring.read(dataStream), + FfiConverterOptionalBytes.read(dataStream), + FfiConverterOptionalString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterI64.read(dataStream), + FfiConverterInt64.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterF64.read(dataStream), + FfiConverterFloat64.read(dataStream), FfiConverterOptionalTypeFtsMatchInfo.read(dataStream) ); case 2: return new Suggestion.Pocket( FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterF64.read(dataStream), - FfiConverterBool.read(dataStream) + FfiConverterFloat64.read(dataStream), + FfiConverterBoolean.read(dataStream) ); case 3: return new Suggestion.Wikipedia( FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterOptionalbytes.read(dataStream), - FfiConverterOptionalstring.read(dataStream), + FfiConverterOptionalBytes.read(dataStream), + FfiConverterOptionalString.read(dataStream), FfiConverterString.read(dataStream) ); case 4: @@ -3088,20 +1547,20 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterOptionalstring.read(dataStream), - FfiConverterI64.read(dataStream), + FfiConverterOptionalString.read(dataStream), + FfiConverterInt64.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterF64.read(dataStream) + FfiConverterFloat64.read(dataStream) ); case 5: return new Suggestion.Yelp( FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterOptionalbytes.read(dataStream), - FfiConverterOptionalstring.read(dataStream), - FfiConverterF64.read(dataStream), - FfiConverterBool.read(dataStream), - FfiConverterBool.read(dataStream), + FfiConverterOptionalBytes.read(dataStream), + FfiConverterOptionalString.read(dataStream), + FfiConverterFloat64.read(dataStream), + FfiConverterBoolean.read(dataStream), + FfiConverterBoolean.read(dataStream), FfiConverterTypeYelpSubjectType.read(dataStream), FfiConverterString.read(dataStream) ); @@ -3110,36 +1569,36 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterF64.read(dataStream) + FfiConverterFloat64.read(dataStream) ); case 7: return new Suggestion.Weather( - FfiConverterOptionalstring.read(dataStream), - FfiConverterOptionalstring.read(dataStream), - FfiConverterOptionalstring.read(dataStream), - FfiConverterOptionalf64.read(dataStream), - FfiConverterOptionalf64.read(dataStream), - FfiConverterF64.read(dataStream) + FfiConverterOptionalString.read(dataStream), + FfiConverterOptionalString.read(dataStream), + FfiConverterOptionalString.read(dataStream), + FfiConverterOptionalFloat64.read(dataStream), + FfiConverterOptionalFloat64.read(dataStream), + FfiConverterFloat64.read(dataStream) ); case 8: return new Suggestion.Fakespot( FfiConverterString.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterF64.read(dataStream), + FfiConverterFloat64.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterI64.read(dataStream), + FfiConverterInt64.read(dataStream), FfiConverterString.read(dataStream), - FfiConverterOptionalbytes.read(dataStream), - FfiConverterOptionalstring.read(dataStream), - FfiConverterF64.read(dataStream), + FfiConverterOptionalBytes.read(dataStream), + FfiConverterOptionalString.read(dataStream), + FfiConverterFloat64.read(dataStream), FfiConverterOptionalTypeFtsMatchInfo.read(dataStream) ); case 9: return new Suggestion.Dynamic( FfiConverterString.read(dataStream), FfiConverterOptionalTypeJsonValue.read(dataStream), - FfiConverterOptionalstring.read(dataStream), - FfiConverterF64.read(dataStream) + FfiConverterOptionalString.read(dataStream), + FfiConverterFloat64.read(dataStream) ); default: throw new UniFFITypeError("Unknown Suggestion variant"); @@ -3152,16 +1611,16 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { FfiConverterString.write(dataStream, value.title); FfiConverterString.write(dataStream, value.url); FfiConverterString.write(dataStream, value.rawUrl); - FfiConverterOptionalbytes.write(dataStream, value.icon); - FfiConverterOptionalstring.write(dataStream, value.iconMimetype); + FfiConverterOptionalBytes.write(dataStream, value.icon); + FfiConverterOptionalString.write(dataStream, value.iconMimetype); FfiConverterString.write(dataStream, value.fullKeyword); - FfiConverterI64.write(dataStream, value.blockId); + FfiConverterInt64.write(dataStream, value.blockId); FfiConverterString.write(dataStream, value.advertiser); FfiConverterString.write(dataStream, value.iabCategory); FfiConverterString.write(dataStream, value.impressionUrl); FfiConverterString.write(dataStream, value.clickUrl); FfiConverterString.write(dataStream, value.rawClickUrl); - FfiConverterF64.write(dataStream, value.score); + FfiConverterFloat64.write(dataStream, value.score); FfiConverterOptionalTypeFtsMatchInfo.write(dataStream, value.ftsMatchInfo); return; } @@ -3169,16 +1628,16 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { dataStream.writeInt32(2); FfiConverterString.write(dataStream, value.title); FfiConverterString.write(dataStream, value.url); - FfiConverterF64.write(dataStream, value.score); - FfiConverterBool.write(dataStream, value.isTopPick); + FfiConverterFloat64.write(dataStream, value.score); + FfiConverterBoolean.write(dataStream, value.isTopPick); return; } if (value instanceof Suggestion.Wikipedia) { dataStream.writeInt32(3); FfiConverterString.write(dataStream, value.title); FfiConverterString.write(dataStream, value.url); - FfiConverterOptionalbytes.write(dataStream, value.icon); - FfiConverterOptionalstring.write(dataStream, value.iconMimetype); + FfiConverterOptionalBytes.write(dataStream, value.icon); + FfiConverterOptionalString.write(dataStream, value.iconMimetype); FfiConverterString.write(dataStream, value.fullKeyword); return; } @@ -3188,21 +1647,21 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { FfiConverterString.write(dataStream, value.url); FfiConverterString.write(dataStream, value.iconUrl); FfiConverterString.write(dataStream, value.description); - FfiConverterOptionalstring.write(dataStream, value.rating); - FfiConverterI64.write(dataStream, value.numberOfRatings); + FfiConverterOptionalString.write(dataStream, value.rating); + FfiConverterInt64.write(dataStream, value.numberOfRatings); FfiConverterString.write(dataStream, value.guid); - FfiConverterF64.write(dataStream, value.score); + FfiConverterFloat64.write(dataStream, value.score); return; } if (value instanceof Suggestion.Yelp) { dataStream.writeInt32(5); FfiConverterString.write(dataStream, value.url); FfiConverterString.write(dataStream, value.title); - FfiConverterOptionalbytes.write(dataStream, value.icon); - FfiConverterOptionalstring.write(dataStream, value.iconMimetype); - FfiConverterF64.write(dataStream, value.score); - FfiConverterBool.write(dataStream, value.hasLocationSign); - FfiConverterBool.write(dataStream, value.subjectExactMatch); + FfiConverterOptionalBytes.write(dataStream, value.icon); + FfiConverterOptionalString.write(dataStream, value.iconMimetype); + FfiConverterFloat64.write(dataStream, value.score); + FfiConverterBoolean.write(dataStream, value.hasLocationSign); + FfiConverterBoolean.write(dataStream, value.subjectExactMatch); FfiConverterTypeYelpSubjectType.write(dataStream, value.subjectType); FfiConverterString.write(dataStream, value.locationParam); return; @@ -3212,30 +1671,30 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { FfiConverterString.write(dataStream, value.title); FfiConverterString.write(dataStream, value.url); FfiConverterString.write(dataStream, value.description); - FfiConverterF64.write(dataStream, value.score); + FfiConverterFloat64.write(dataStream, value.score); return; } if (value instanceof Suggestion.Weather) { dataStream.writeInt32(7); - FfiConverterOptionalstring.write(dataStream, value.city); - FfiConverterOptionalstring.write(dataStream, value.region); - FfiConverterOptionalstring.write(dataStream, value.country); - FfiConverterOptionalf64.write(dataStream, value.latitude); - FfiConverterOptionalf64.write(dataStream, value.longitude); - FfiConverterF64.write(dataStream, value.score); + FfiConverterOptionalString.write(dataStream, value.city); + FfiConverterOptionalString.write(dataStream, value.region); + FfiConverterOptionalString.write(dataStream, value.country); + FfiConverterOptionalFloat64.write(dataStream, value.latitude); + FfiConverterOptionalFloat64.write(dataStream, value.longitude); + FfiConverterFloat64.write(dataStream, value.score); return; } if (value instanceof Suggestion.Fakespot) { dataStream.writeInt32(8); FfiConverterString.write(dataStream, value.fakespotGrade); FfiConverterString.write(dataStream, value.productId); - FfiConverterF64.write(dataStream, value.rating); + FfiConverterFloat64.write(dataStream, value.rating); FfiConverterString.write(dataStream, value.title); - FfiConverterI64.write(dataStream, value.totalReviews); + FfiConverterInt64.write(dataStream, value.totalReviews); FfiConverterString.write(dataStream, value.url); - FfiConverterOptionalbytes.write(dataStream, value.icon); - FfiConverterOptionalstring.write(dataStream, value.iconMimetype); - FfiConverterF64.write(dataStream, value.score); + FfiConverterOptionalBytes.write(dataStream, value.icon); + FfiConverterOptionalString.write(dataStream, value.iconMimetype); + FfiConverterFloat64.write(dataStream, value.score); FfiConverterOptionalTypeFtsMatchInfo.write(dataStream, value.matchInfo); return; } @@ -3243,8 +1702,8 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { dataStream.writeInt32(9); FfiConverterString.write(dataStream, value.suggestionType); FfiConverterOptionalTypeJsonValue.write(dataStream, value.data); - FfiConverterOptionalstring.write(dataStream, value.dismissalKey); - FfiConverterF64.write(dataStream, value.score); + FfiConverterOptionalString.write(dataStream, value.dismissalKey); + FfiConverterFloat64.write(dataStream, value.score); return; } throw new UniFFITypeError("Unknown Suggestion variant"); @@ -3257,31 +1716,31 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { totalSize += FfiConverterString.computeSize(value.title); totalSize += FfiConverterString.computeSize(value.url); totalSize += FfiConverterString.computeSize(value.rawUrl); - totalSize += FfiConverterOptionalbytes.computeSize(value.icon); - totalSize += FfiConverterOptionalstring.computeSize(value.iconMimetype); + totalSize += FfiConverterOptionalBytes.computeSize(value.icon); + totalSize += FfiConverterOptionalString.computeSize(value.iconMimetype); totalSize += FfiConverterString.computeSize(value.fullKeyword); - totalSize += FfiConverterI64.computeSize(value.blockId); + totalSize += FfiConverterInt64.computeSize(value.blockId); totalSize += FfiConverterString.computeSize(value.advertiser); totalSize += FfiConverterString.computeSize(value.iabCategory); totalSize += FfiConverterString.computeSize(value.impressionUrl); totalSize += FfiConverterString.computeSize(value.clickUrl); totalSize += FfiConverterString.computeSize(value.rawClickUrl); - totalSize += FfiConverterF64.computeSize(value.score); + totalSize += FfiConverterFloat64.computeSize(value.score); totalSize += FfiConverterOptionalTypeFtsMatchInfo.computeSize(value.ftsMatchInfo); return totalSize; } if (value instanceof Suggestion.Pocket) { totalSize += FfiConverterString.computeSize(value.title); totalSize += FfiConverterString.computeSize(value.url); - totalSize += FfiConverterF64.computeSize(value.score); - totalSize += FfiConverterBool.computeSize(value.isTopPick); + totalSize += FfiConverterFloat64.computeSize(value.score); + totalSize += FfiConverterBoolean.computeSize(value.isTopPick); return totalSize; } if (value instanceof Suggestion.Wikipedia) { totalSize += FfiConverterString.computeSize(value.title); totalSize += FfiConverterString.computeSize(value.url); - totalSize += FfiConverterOptionalbytes.computeSize(value.icon); - totalSize += FfiConverterOptionalstring.computeSize(value.iconMimetype); + totalSize += FfiConverterOptionalBytes.computeSize(value.icon); + totalSize += FfiConverterOptionalString.computeSize(value.iconMimetype); totalSize += FfiConverterString.computeSize(value.fullKeyword); return totalSize; } @@ -3290,20 +1749,20 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { totalSize += FfiConverterString.computeSize(value.url); totalSize += FfiConverterString.computeSize(value.iconUrl); totalSize += FfiConverterString.computeSize(value.description); - totalSize += FfiConverterOptionalstring.computeSize(value.rating); - totalSize += FfiConverterI64.computeSize(value.numberOfRatings); + totalSize += FfiConverterOptionalString.computeSize(value.rating); + totalSize += FfiConverterInt64.computeSize(value.numberOfRatings); totalSize += FfiConverterString.computeSize(value.guid); - totalSize += FfiConverterF64.computeSize(value.score); + totalSize += FfiConverterFloat64.computeSize(value.score); return totalSize; } if (value instanceof Suggestion.Yelp) { totalSize += FfiConverterString.computeSize(value.url); totalSize += FfiConverterString.computeSize(value.title); - totalSize += FfiConverterOptionalbytes.computeSize(value.icon); - totalSize += FfiConverterOptionalstring.computeSize(value.iconMimetype); - totalSize += FfiConverterF64.computeSize(value.score); - totalSize += FfiConverterBool.computeSize(value.hasLocationSign); - totalSize += FfiConverterBool.computeSize(value.subjectExactMatch); + totalSize += FfiConverterOptionalBytes.computeSize(value.icon); + totalSize += FfiConverterOptionalString.computeSize(value.iconMimetype); + totalSize += FfiConverterFloat64.computeSize(value.score); + totalSize += FfiConverterBoolean.computeSize(value.hasLocationSign); + totalSize += FfiConverterBoolean.computeSize(value.subjectExactMatch); totalSize += FfiConverterTypeYelpSubjectType.computeSize(value.subjectType); totalSize += FfiConverterString.computeSize(value.locationParam); return totalSize; @@ -3312,49 +1771,314 @@ export class FfiConverterTypeSuggestion extends FfiConverterArrayBuffer { totalSize += FfiConverterString.computeSize(value.title); totalSize += FfiConverterString.computeSize(value.url); totalSize += FfiConverterString.computeSize(value.description); - totalSize += FfiConverterF64.computeSize(value.score); + totalSize += FfiConverterFloat64.computeSize(value.score); return totalSize; } if (value instanceof Suggestion.Weather) { - totalSize += FfiConverterOptionalstring.computeSize(value.city); - totalSize += FfiConverterOptionalstring.computeSize(value.region); - totalSize += FfiConverterOptionalstring.computeSize(value.country); - totalSize += FfiConverterOptionalf64.computeSize(value.latitude); - totalSize += FfiConverterOptionalf64.computeSize(value.longitude); - totalSize += FfiConverterF64.computeSize(value.score); + totalSize += FfiConverterOptionalString.computeSize(value.city); + totalSize += FfiConverterOptionalString.computeSize(value.region); + totalSize += FfiConverterOptionalString.computeSize(value.country); + totalSize += FfiConverterOptionalFloat64.computeSize(value.latitude); + totalSize += FfiConverterOptionalFloat64.computeSize(value.longitude); + totalSize += FfiConverterFloat64.computeSize(value.score); return totalSize; } if (value instanceof Suggestion.Fakespot) { totalSize += FfiConverterString.computeSize(value.fakespotGrade); totalSize += FfiConverterString.computeSize(value.productId); - totalSize += FfiConverterF64.computeSize(value.rating); + totalSize += FfiConverterFloat64.computeSize(value.rating); totalSize += FfiConverterString.computeSize(value.title); - totalSize += FfiConverterI64.computeSize(value.totalReviews); + totalSize += FfiConverterInt64.computeSize(value.totalReviews); totalSize += FfiConverterString.computeSize(value.url); - totalSize += FfiConverterOptionalbytes.computeSize(value.icon); - totalSize += FfiConverterOptionalstring.computeSize(value.iconMimetype); - totalSize += FfiConverterF64.computeSize(value.score); + totalSize += FfiConverterOptionalBytes.computeSize(value.icon); + totalSize += FfiConverterOptionalString.computeSize(value.iconMimetype); + totalSize += FfiConverterFloat64.computeSize(value.score); totalSize += FfiConverterOptionalTypeFtsMatchInfo.computeSize(value.matchInfo); return totalSize; } if (value instanceof Suggestion.Dynamic) { totalSize += FfiConverterString.computeSize(value.suggestionType); totalSize += FfiConverterOptionalTypeJsonValue.computeSize(value.data); - totalSize += FfiConverterOptionalstring.computeSize(value.dismissalKey); - totalSize += FfiConverterF64.computeSize(value.score); + totalSize += FfiConverterOptionalString.computeSize(value.dismissalKey); + totalSize += FfiConverterFloat64.computeSize(value.score); return totalSize; } throw new UniFFITypeError("Unknown Suggestion variant"); } static checkType(value) { - if (value === undefined || value === null || !(value instanceof Suggestion)) { + if (!(value instanceof Suggestion)) { throw new UniFFITypeError(`${value} is not a subclass instance of Suggestion`); } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeSuggestion extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeSuggestion.read(dataStream)); + } + return arr; + } + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeSuggestion.write(dataStream, innerValue); + }) + } + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeSuggestion.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeSuggestion.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeLabeledTimingSample extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeLabeledTimingSample.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeLabeledTimingSample.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeLabeledTimingSample.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeLabeledTimingSample.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +/** + * QueryWithMetricsResult + */ +export class QueryWithMetricsResult { + constructor( + { + suggestions, + queryTimes + } = { + suggestions: undefined, + queryTimes: undefined + } + ) { + try { + FfiConverterSequenceTypeSuggestion.checkType(suggestions) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("suggestions"); + } + throw e; + } + try { + FfiConverterSequenceTypeLabeledTimingSample.checkType(queryTimes) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("queryTimes"); + } + throw e; + } + /** + * suggestions + */ + this.suggestions = suggestions; + /** + * Samples for the `suggest.query_time` metric + */ + this.queryTimes = queryTimes; + } + + equals(other) { + return ( + this.suggestions == other.suggestions + && this.queryTimes == other.queryTimes + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeQueryWithMetricsResult extends FfiConverterArrayBuffer { + static read(dataStream) { + return new QueryWithMetricsResult({ + suggestions: FfiConverterSequenceTypeSuggestion.read(dataStream), + queryTimes: FfiConverterSequenceTypeLabeledTimingSample.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterSequenceTypeSuggestion.write(dataStream, value.suggestions); + FfiConverterSequenceTypeLabeledTimingSample.write(dataStream, value.queryTimes); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterSequenceTypeSuggestion.computeSize(value.suggestions); + totalSize += FfiConverterSequenceTypeLabeledTimingSample.computeSize(value.queryTimes); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof QueryWithMetricsResult)) { + throw new UniFFITypeError(`Expected 'QueryWithMetricsResult', found '${typeof value}'`); + } + try { + FfiConverterSequenceTypeSuggestion.checkType(value.suggestions); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".suggestions"); + } + throw e; + } + try { + FfiConverterSequenceTypeLabeledTimingSample.checkType(value.queryTimes); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".queryTimes"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterInt32 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < -2147483648 || value > 2147483647) { + throw new UniFFITypeError(`${value} exceeds the I32 bounds`); + } + } + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt32(value) + } + static read(dataStream) { + return dataStream.readInt32() + } +} +/** + * Global Suggest configuration data. + */ +export class SuggestGlobalConfig { + constructor( + { + showLessFrequentlyCap + } = { + showLessFrequentlyCap: undefined + } + ) { + try { + FfiConverterInt32.checkType(showLessFrequentlyCap) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("showLessFrequentlyCap"); + } + throw e; + } + /** + * showLessFrequentlyCap + */ + this.showLessFrequentlyCap = showLessFrequentlyCap; + } + + equals(other) { + return ( + this.showLessFrequentlyCap == other.showLessFrequentlyCap + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestGlobalConfig extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SuggestGlobalConfig({ + showLessFrequentlyCap: FfiConverterInt32.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterInt32.write(dataStream, value.showLessFrequentlyCap); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterInt32.computeSize(value.showLessFrequentlyCap); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SuggestGlobalConfig)) { + throw new UniFFITypeError(`Expected 'SuggestGlobalConfig', found '${typeof value}'`); + } + try { + FfiConverterInt32.checkType(value.showLessFrequentlyCap); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".showLessFrequentlyCap"); + } + throw e; + } + } +} /** * A provider is a source of search suggestions. @@ -3363,48 +2087,45 @@ export const SuggestionProvider = { /** * AMP */ - AMP:1, + AMP: 1, /** * WIKIPEDIA */ - WIKIPEDIA:2, + WIKIPEDIA: 2, /** * AMO */ - AMO:3, + AMO: 3, /** * POCKET */ - POCKET:4, + POCKET: 4, /** * YELP */ - YELP:5, + YELP: 5, /** * MDN */ - MDN:6, + MDN: 6, /** * WEATHER */ - WEATHER:7, + WEATHER: 7, /** * FAKESPOT */ - FAKESPOT:8, + FAKESPOT: 8, /** * DYNAMIC */ - DYNAMIC:9, + DYNAMIC: 9, }; - Object.freeze(SuggestionProvider); + // Export the FFIConverter object to make external types work. export class FfiConverterTypeSuggestionProvider extends FfiConverterArrayBuffer { - static #validValues = Object.values(SuggestionProvider); - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { case 1: return SuggestionProvider.AMP @@ -3474,809 +2195,11 @@ export class FfiConverterTypeSuggestionProvider extends FfiConverterArrayBuffer } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { + if (!Number.isInteger(value) || value < 1 || value > 9) { throw new UniFFITypeError(`${value} is not a valid value for SuggestionProvider`); } } } - - - -/** - * Subject type for Yelp suggestion. - */ -export const YelpSubjectType = { - /** - * SERVICE - */ - SERVICE:0, - /** - * BUSINESS - */ - BUSINESS:1, -}; - -Object.freeze(YelpSubjectType); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeYelpSubjectType extends FfiConverterArrayBuffer { - static #validValues = Object.values(YelpSubjectType); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return YelpSubjectType.SERVICE - case 2: - return YelpSubjectType.BUSINESS - default: - throw new UniFFITypeError("Unknown YelpSubjectType variant"); - } - } - - static write(dataStream, value) { - if (value === YelpSubjectType.SERVICE) { - dataStream.writeInt32(1); - return; - } - if (value === YelpSubjectType.BUSINESS) { - dataStream.writeInt32(2); - return; - } - throw new UniFFITypeError("Unknown YelpSubjectType variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for YelpSubjectType`); - } - } -} - - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionali32 extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterI32.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterI32.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterI32.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterI32.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalf64 extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterF64.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterF64.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterF64.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterF64.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalstring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterString.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterString.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterString.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalbytes extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterBytes.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterBytes.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterBytes.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterBytes.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeFtsMatchInfo extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeFtsMatchInfo.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeFtsMatchInfo.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeFtsMatchInfo.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeFtsMatchInfo.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeSuggestionProviderConstraints extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeSuggestionProviderConstraints.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeSuggestionProviderConstraints.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeSuggestionProviderConstraints.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeSuggestionProviderConstraints.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeAmpMatchingStrategy extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeAmpMatchingStrategy.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeAmpMatchingStrategy.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeAmpMatchingStrategy.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeAmpMatchingStrategy.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeGeonameType extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeGeonameType.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeGeonameType.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeGeonameType.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeGeonameType.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeInterruptKind extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeInterruptKind.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeInterruptKind.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeInterruptKind.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeInterruptKind.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeSuggestProviderConfig extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeSuggestProviderConfig.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeSuggestProviderConfig.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeSuggestProviderConfig.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeSuggestProviderConfig.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalSequencestring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterSequencestring.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterSequencestring.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterSequencestring.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterSequencestring.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalSequenceTypeGeoname extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterSequenceTypeGeoname.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterSequenceTypeGeoname.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterSequenceTypeGeoname.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterSequenceTypeGeoname.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalSequenceTypeSuggestionProvider extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterSequenceTypeSuggestionProvider.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterSequenceTypeSuggestionProvider.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterSequenceTypeSuggestionProvider.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterSequenceTypeSuggestionProvider.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeJsonValue extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeJsonValue.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeJsonValue.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeJsonValue.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeJsonValue.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterString.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterString.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterString.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterString.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeGeoname extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeGeoname.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeGeoname.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeGeoname.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeGeoname.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeGeonameMatch extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeGeonameMatch.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeGeonameMatch.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeGeonameMatch.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeGeonameMatch.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeLabeledTimingSample extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeLabeledTimingSample.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeLabeledTimingSample.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeLabeledTimingSample.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeLabeledTimingSample.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeSuggestion extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeSuggestion.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeSuggestion.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeSuggestion.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeSuggestion.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterSequenceTypeSuggestionProvider extends FfiConverterArrayBuffer { static read(dataStream) { @@ -4320,79 +2243,1941 @@ export class FfiConverterSequenceTypeSuggestionProvider extends FfiConverterArra }) } } - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeJsonValue extends FfiConverter { - static lift(buf) { - return FfiConverterString.lift(buf); +export class FfiConverterOptionalSequenceTypeSuggestionProvider extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterSequenceTypeSuggestionProvider.checkType(value) + } } - - static lower(buf) { - return FfiConverterString.lower(buf); + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterSequenceTypeSuggestionProvider.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } } - + static write(dataStream, value) { - FfiConverterString.write(dataStream, value); - } - - static read(buf) { - return FfiConverterString.read(buf); + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterSequenceTypeSuggestionProvider.write(dataStream, value) } - + static computeSize(value) { - return FfiConverterString.computeSize(value); + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterSequenceTypeSuggestionProvider.computeSize(value) } } -// TODO: We should also allow JS to customize the type eventually. +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceString extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterString.read(dataStream)); + } + return arr; + } -import { - FfiConverterTypeRemoteSettingsService, - RemoteSettingsService, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs"; + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterString.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterString.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterString.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalSequenceString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterSequenceString.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterSequenceString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterSequenceString.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterSequenceString.computeSize(value) + } +} + +/** + * AmpMatchingStrategy + */ +export const AmpMatchingStrategy = { + /** + * Disable keywords added via keyword expansion. + * This eliminates keywords that for terms related to the "real" keywords, for example + * misspellings like "underarmor" instead of "under armor"'. + */ + NO_KEYWORD_EXPANSION: 1, + /** + * Use FTS matching against the full keywords, joined together. + */ + FTS_AGAINST_FULL_KEYWORDS: 2, + /** + * Use FTS matching against the title field + */ + FTS_AGAINST_TITLE: 3, +}; +Object.freeze(AmpMatchingStrategy); // Export the FFIConverter object to make external types work. -export { FfiConverterTypeRemoteSettingsService, RemoteSettingsService };import { - FfiConverterTypeRemoteSettingsServer, - RemoteSettingsServer, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustRemoteSettings.sys.mjs"; +export class FfiConverterTypeAmpMatchingStrategy extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return AmpMatchingStrategy.NO_KEYWORD_EXPANSION + case 2: + return AmpMatchingStrategy.FTS_AGAINST_FULL_KEYWORDS + case 3: + return AmpMatchingStrategy.FTS_AGAINST_TITLE + default: + throw new UniFFITypeError("Unknown AmpMatchingStrategy variant"); + } + } + + static write(dataStream, value) { + if (value === AmpMatchingStrategy.NO_KEYWORD_EXPANSION) { + dataStream.writeInt32(1); + return; + } + if (value === AmpMatchingStrategy.FTS_AGAINST_FULL_KEYWORDS) { + dataStream.writeInt32(2); + return; + } + if (value === AmpMatchingStrategy.FTS_AGAINST_TITLE) { + dataStream.writeInt32(3); + return; + } + throw new UniFFITypeError("Unknown AmpMatchingStrategy variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 3) { + throw new UniFFITypeError(`${value} is not a valid value for AmpMatchingStrategy`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeAmpMatchingStrategy extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeAmpMatchingStrategy.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeAmpMatchingStrategy.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeAmpMatchingStrategy.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeAmpMatchingStrategy.computeSize(value) + } +} +/** + * Some providers manage multiple suggestion subtypes. Queries, ingests, and + * other operations on those providers must be constrained to a desired subtype. + */ +export class SuggestionProviderConstraints { + constructor( + { + dynamicSuggestionTypes= null, + ampAlternativeMatching= null + } = { + dynamicSuggestionTypes: undefined, + ampAlternativeMatching: undefined + } + ) { + try { + FfiConverterOptionalSequenceString.checkType(dynamicSuggestionTypes) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("dynamicSuggestionTypes"); + } + throw e; + } + try { + FfiConverterOptionalTypeAmpMatchingStrategy.checkType(ampAlternativeMatching) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("ampAlternativeMatching"); + } + throw e; + } + /** + * Which dynamic suggestions should we fetch or ingest? Corresponds to the + * `suggestion_type` value in dynamic suggestions remote settings records. + */ + this.dynamicSuggestionTypes = dynamicSuggestionTypes; + /** + * Which strategy should we use for the AMP queries? + * Use None for the default strategy. + */ + this.ampAlternativeMatching = ampAlternativeMatching; + } + + equals(other) { + return ( + this.dynamicSuggestionTypes == other.dynamicSuggestionTypes + && this.ampAlternativeMatching == other.ampAlternativeMatching + ) + } +} // Export the FFIConverter object to make external types work. -export { FfiConverterTypeRemoteSettingsServer, RemoteSettingsServer }; +export class FfiConverterTypeSuggestionProviderConstraints extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SuggestionProviderConstraints({ + dynamicSuggestionTypes: FfiConverterOptionalSequenceString.read(dataStream), + ampAlternativeMatching: FfiConverterOptionalTypeAmpMatchingStrategy.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterOptionalSequenceString.write(dataStream, value.dynamicSuggestionTypes); + FfiConverterOptionalTypeAmpMatchingStrategy.write(dataStream, value.ampAlternativeMatching); + } + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterOptionalSequenceString.computeSize(value.dynamicSuggestionTypes); + totalSize += FfiConverterOptionalTypeAmpMatchingStrategy.computeSize(value.ampAlternativeMatching); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SuggestionProviderConstraints)) { + throw new UniFFITypeError(`Expected 'SuggestionProviderConstraints', found '${typeof value}'`); + } + try { + FfiConverterOptionalSequenceString.checkType(value.dynamicSuggestionTypes); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".dynamicSuggestionTypes"); + } + throw e; + } + try { + FfiConverterOptionalTypeAmpMatchingStrategy.checkType(value.ampAlternativeMatching); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".ampAlternativeMatching"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeSuggestionProviderConstraints extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeSuggestionProviderConstraints.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeSuggestionProviderConstraints.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeSuggestionProviderConstraints.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeSuggestionProviderConstraints.computeSize(value) + } +} +/** + * Constraints limit which suggestions to ingest from Remote Settings. + */ +export class SuggestIngestionConstraints { + constructor( + { + providers= null, + providerConstraints= null, + emptyOnly= false + } = { + providers: undefined, + providerConstraints: undefined, + emptyOnly: undefined + } + ) { + try { + FfiConverterOptionalSequenceTypeSuggestionProvider.checkType(providers) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("providers"); + } + throw e; + } + try { + FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(providerConstraints) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("providerConstraints"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(emptyOnly) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("emptyOnly"); + } + throw e; + } + /** + * providers + */ + this.providers = providers; + /** + * providerConstraints + */ + this.providerConstraints = providerConstraints; + /** + * Only run ingestion if the table `suggestions` is empty + * + */ + this.emptyOnly = emptyOnly; + } + + equals(other) { + return ( + this.providers == other.providers + && this.providerConstraints == other.providerConstraints + && this.emptyOnly == other.emptyOnly + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestIngestionConstraints extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SuggestIngestionConstraints({ + providers: FfiConverterOptionalSequenceTypeSuggestionProvider.read(dataStream), + providerConstraints: FfiConverterOptionalTypeSuggestionProviderConstraints.read(dataStream), + emptyOnly: FfiConverterBoolean.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterOptionalSequenceTypeSuggestionProvider.write(dataStream, value.providers); + FfiConverterOptionalTypeSuggestionProviderConstraints.write(dataStream, value.providerConstraints); + FfiConverterBoolean.write(dataStream, value.emptyOnly); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterOptionalSequenceTypeSuggestionProvider.computeSize(value.providers); + totalSize += FfiConverterOptionalTypeSuggestionProviderConstraints.computeSize(value.providerConstraints); + totalSize += FfiConverterBoolean.computeSize(value.emptyOnly); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SuggestIngestionConstraints)) { + throw new UniFFITypeError(`Expected 'SuggestIngestionConstraints', found '${typeof value}'`); + } + try { + FfiConverterOptionalSequenceTypeSuggestionProvider.checkType(value.providers); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".providers"); + } + throw e; + } + try { + FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(value.providerConstraints); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".providerConstraints"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(value.emptyOnly); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".emptyOnly"); + } + throw e; + } + } +} +/** + * Ingestion metrics + * + * These are recorded during [crate::Store::ingest] and returned to the consumer to record. + */ +export class SuggestIngestionMetrics { + constructor( + { + ingestionTimes, + downloadTimes + } = { + ingestionTimes: undefined, + downloadTimes: undefined + } + ) { + try { + FfiConverterSequenceTypeLabeledTimingSample.checkType(ingestionTimes) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("ingestionTimes"); + } + throw e; + } + try { + FfiConverterSequenceTypeLabeledTimingSample.checkType(downloadTimes) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("downloadTimes"); + } + throw e; + } + /** + * Samples for the `suggest.ingestion_time` metric + */ + this.ingestionTimes = ingestionTimes; + /** + * Samples for the `suggest.ingestion_download_time` metric + */ + this.downloadTimes = downloadTimes; + } + + equals(other) { + return ( + this.ingestionTimes == other.ingestionTimes + && this.downloadTimes == other.downloadTimes + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestIngestionMetrics extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SuggestIngestionMetrics({ + ingestionTimes: FfiConverterSequenceTypeLabeledTimingSample.read(dataStream), + downloadTimes: FfiConverterSequenceTypeLabeledTimingSample.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterSequenceTypeLabeledTimingSample.write(dataStream, value.ingestionTimes); + FfiConverterSequenceTypeLabeledTimingSample.write(dataStream, value.downloadTimes); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterSequenceTypeLabeledTimingSample.computeSize(value.ingestionTimes); + totalSize += FfiConverterSequenceTypeLabeledTimingSample.computeSize(value.downloadTimes); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SuggestIngestionMetrics)) { + throw new UniFFITypeError(`Expected 'SuggestIngestionMetrics', found '${typeof value}'`); + } + try { + FfiConverterSequenceTypeLabeledTimingSample.checkType(value.ingestionTimes); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".ingestionTimes"); + } + throw e; + } + try { + FfiConverterSequenceTypeLabeledTimingSample.checkType(value.downloadTimes); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".downloadTimes"); + } + throw e; + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalInt32 extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterInt32.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterInt32.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterInt32.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterInt32.computeSize(value) + } +} +/** + * A query for suggestions to show in the address bar. + */ +export class SuggestionQuery { + constructor( + { + keyword, + providers, + providerConstraints= null, + limit= null + } = { + keyword: undefined, + providers: undefined, + providerConstraints: undefined, + limit: undefined + } + ) { + try { + FfiConverterString.checkType(keyword) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("keyword"); + } + throw e; + } + try { + FfiConverterSequenceTypeSuggestionProvider.checkType(providers) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("providers"); + } + throw e; + } + try { + FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(providerConstraints) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("providerConstraints"); + } + throw e; + } + try { + FfiConverterOptionalInt32.checkType(limit) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("limit"); + } + throw e; + } + /** + * keyword + */ + this.keyword = keyword; + /** + * providers + */ + this.providers = providers; + /** + * providerConstraints + */ + this.providerConstraints = providerConstraints; + /** + * limit + */ + this.limit = limit; + } + + equals(other) { + return ( + this.keyword == other.keyword + && this.providers == other.providers + && this.providerConstraints == other.providerConstraints + && this.limit == other.limit + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestionQuery extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SuggestionQuery({ + keyword: FfiConverterString.read(dataStream), + providers: FfiConverterSequenceTypeSuggestionProvider.read(dataStream), + providerConstraints: FfiConverterOptionalTypeSuggestionProviderConstraints.read(dataStream), + limit: FfiConverterOptionalInt32.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterString.write(dataStream, value.keyword); + FfiConverterSequenceTypeSuggestionProvider.write(dataStream, value.providers); + FfiConverterOptionalTypeSuggestionProviderConstraints.write(dataStream, value.providerConstraints); + FfiConverterOptionalInt32.write(dataStream, value.limit); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterString.computeSize(value.keyword); + totalSize += FfiConverterSequenceTypeSuggestionProvider.computeSize(value.providers); + totalSize += FfiConverterOptionalTypeSuggestionProviderConstraints.computeSize(value.providerConstraints); + totalSize += FfiConverterOptionalInt32.computeSize(value.limit); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SuggestionQuery)) { + throw new UniFFITypeError(`Expected 'SuggestionQuery', found '${typeof value}'`); + } + try { + FfiConverterString.checkType(value.keyword); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".keyword"); + } + throw e; + } + try { + FfiConverterSequenceTypeSuggestionProvider.checkType(value.providers); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".providers"); + } + throw e; + } + try { + FfiConverterOptionalTypeSuggestionProviderConstraints.checkType(value.providerConstraints); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".providerConstraints"); + } + throw e; + } + try { + FfiConverterOptionalInt32.checkType(value.limit); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".limit"); + } + throw e; + } + } +} + +/** + * The type of a geoname. + */ +export const GeonameType = { + /** + * CITY + */ + CITY: 1, + /** + * REGION + */ + REGION: 2, +}; +Object.freeze(GeonameType); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeGeonameType extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return GeonameType.CITY + case 2: + return GeonameType.REGION + default: + throw new UniFFITypeError("Unknown GeonameType variant"); + } + } + + static write(dataStream, value) { + if (value === GeonameType.CITY) { + dataStream.writeInt32(1); + return; + } + if (value === GeonameType.REGION) { + dataStream.writeInt32(2); + return; + } + throw new UniFFITypeError("Unknown GeonameType variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 2) { + throw new UniFFITypeError(`${value} is not a valid value for GeonameType`); + } + } +} + +/** + * What should be interrupted when [SuggestStore::interrupt] is called? + */ +export const InterruptKind = { + /** + * Interrupt read operations like [SuggestStore::query] + */ + READ: 1, + /** + * Interrupt write operations. This mostly means [SuggestStore::ingest], but + * other operations may also be interrupted. + */ + WRITE: 2, + /** + * Interrupt both read and write operations, + */ + READ_WRITE: 3, +}; +Object.freeze(InterruptKind); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeInterruptKind extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return InterruptKind.READ + case 2: + return InterruptKind.WRITE + case 3: + return InterruptKind.READ_WRITE + default: + throw new UniFFITypeError("Unknown InterruptKind variant"); + } + } + + static write(dataStream, value) { + if (value === InterruptKind.READ) { + dataStream.writeInt32(1); + return; + } + if (value === InterruptKind.WRITE) { + dataStream.writeInt32(2); + return; + } + if (value === InterruptKind.READ_WRITE) { + dataStream.writeInt32(3); + return; + } + throw new UniFFITypeError("Unknown InterruptKind variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 3) { + throw new UniFFITypeError(`${value} is not a valid value for InterruptKind`); + } + } +} + +/** + * The error type for all Suggest component operations. These errors are + * exposed to your application, which should handle them as needed. + */ +export class SuggestApiError extends Error {} /** - * Determines whether a "raw" sponsored suggestion URL is equivalent to a - * "cooked" URL. The two URLs are equivalent if they are identical except for - * their replaced template parameters, which can be different. - * @returns {Boolean} + * Network */ -export function rawSuggestionUrlMatches(rawUrl,cookedUrl) { +export class Network extends SuggestApiError { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(rawUrl) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("rawUrl"); - } - throw e; - } - try { - FfiConverterString.checkType(cookedUrl) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("cookedUrl"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 37, // suggest:uniffi_suggest_fn_func_raw_suggestion_url_matches - FfiConverterString.lower(rawUrl), - FfiConverterString.lower(cookedUrl), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); + constructor( + reason, + ...params + ) { + const message = `reason: ${ reason }`; + super(message, ...params); + this.reason = reason; + } + toString() { + return `Network: ${super.toString()}` + } +} + +/** + * The server requested a backoff after too many requests + */ +export class Backoff extends SuggestApiError { + + constructor( + seconds, + ...params + ) { + const message = `seconds: ${ seconds }`; + super(message, ...params); + this.seconds = seconds; + } + toString() { + return `Backoff: ${super.toString()}` + } +} + +/** + * An operation was interrupted by calling `SuggestStore.interrupt()` + */ +export class Interrupted extends SuggestApiError { + + constructor( + ...params + ) { + super(...params); + } + toString() { + return `Interrupted: ${super.toString()}` + } +} + +/** + * Other + */ +export class Other extends SuggestApiError { + + constructor( + reason, + ...params + ) { + const message = `reason: ${ reason }`; + super(message, ...params); + this.reason = reason; + } + toString() { + return `Other: ${super.toString()}` + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestApiError extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new Network( + FfiConverterString.read(dataStream) + ); + case 2: + return new Backoff( + FfiConverterUInt64.read(dataStream) + ); + case 3: + return new Interrupted( + ); + case 4: + return new Other( + FfiConverterString.read(dataStream) + ); + default: + throw new UniFFITypeError("Unknown SuggestApiError variant"); + } + } + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof Network) { + totalSize += FfiConverterString.computeSize(value.reason); + return totalSize; + } + if (value instanceof Backoff) { + totalSize += FfiConverterUInt64.computeSize(value.seconds); + return totalSize; + } + if (value instanceof Interrupted) { + return totalSize; + } + if (value instanceof Other) { + totalSize += FfiConverterString.computeSize(value.reason); + return totalSize; + } + throw new UniFFITypeError("Unknown SuggestApiError variant"); + } + static write(dataStream, value) { + if (value instanceof Network) { + dataStream.writeInt32(1); + FfiConverterString.write(dataStream, value.reason); + return; + } + if (value instanceof Backoff) { + dataStream.writeInt32(2); + FfiConverterUInt64.write(dataStream, value.seconds); + return; + } + if (value instanceof Interrupted) { + dataStream.writeInt32(3); + return; + } + if (value instanceof Other) { + dataStream.writeInt32(4); + FfiConverterString.write(dataStream, value.reason); + return; + } + throw new UniFFITypeError("Unknown SuggestApiError variant"); + } + + static errorClass = SuggestApiError; +} + +/** + * Per-provider configuration data. + */ +export class SuggestProviderConfig {} +/** + * Weather + */ +SuggestProviderConfig.Weather = class extends SuggestProviderConfig{ + constructor( + score, + minKeywordLength + ) { + super(); + this.score = score; + this.minKeywordLength = minKeywordLength; + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestProviderConfig extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new SuggestProviderConfig.Weather( + FfiConverterFloat64.read(dataStream), + FfiConverterInt32.read(dataStream) + ); + default: + throw new UniFFITypeError("Unknown SuggestProviderConfig variant"); + } + } + + static write(dataStream, value) { + if (value instanceof SuggestProviderConfig.Weather) { + dataStream.writeInt32(1); + FfiConverterFloat64.write(dataStream, value.score); + FfiConverterInt32.write(dataStream, value.minKeywordLength); + return; + } + throw new UniFFITypeError("Unknown SuggestProviderConfig variant"); + } + + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof SuggestProviderConfig.Weather) { + totalSize += FfiConverterFloat64.computeSize(value.score); + totalSize += FfiConverterInt32.computeSize(value.minKeywordLength); + return totalSize; + } + throw new UniFFITypeError("Unknown SuggestProviderConfig variant"); + } + + static checkType(value) { + if (!(value instanceof SuggestProviderConfig)) { + throw new UniFFITypeError(`${value} is not a subclass instance of SuggestProviderConfig`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeGeonameType extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeGeonameType.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeGeonameType.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeGeonameType.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeGeonameType.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeGeoname extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeGeoname.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeGeoname.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeGeoname.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeGeoname.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalSequenceTypeGeoname extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterSequenceTypeGeoname.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterSequenceTypeGeoname.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterSequenceTypeGeoname.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterSequenceTypeGeoname.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeGeonameMatch extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeGeonameMatch.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeGeonameMatch.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeGeonameMatch.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeGeonameMatch.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeSuggestProviderConfig extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeSuggestProviderConfig.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeSuggestProviderConfig.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeSuggestProviderConfig.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeSuggestProviderConfig.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeInterruptKind extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeInterruptKind.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeInterruptKind.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeInterruptKind.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeInterruptKind.computeSize(value) + } +} +/** + * The store is the entry point to the Suggest component. It incrementally + * downloads suggestions from the Remote Settings service, stores them in a + * local database, and returns them in response to user queries. + * + * Your application should create a single store, and manage it as a singleton. + * The store is thread-safe, and supports concurrent queries and ingests. We + * expect that your application will call [`SuggestStore::query()`] to show + * suggestions as the user types into the address bar, and periodically call + * [`SuggestStore::ingest()`] in the background to update the database with + * new suggestions from Remote Settings. + * + * For responsiveness, we recommend always calling `query()` on a worker + * thread. When the user types new input into the address bar, call + * [`SuggestStore::interrupt()`] on the main thread to cancel the query + * for the old input, and unblock the worker thread for the new query. + * + * The store keeps track of the state needed to support incremental ingestion, + * but doesn't schedule the ingestion work itself, or decide how many + * suggestions to ingest at once. This is for two reasons: + * + * 1. The primitives for scheduling background work vary between platforms, and + * aren't available to the lower-level Rust layer. You might use an idle + * timer on Desktop, `WorkManager` on Android, or `BGTaskScheduler` on iOS. + * 2. Ingestion constraints can change, depending on the platform and the needs + * of your application. A mobile device on a metered connection might want + * to request a small subset of the Suggest data and download the rest + * later, while a desktop on a fast link might download the entire dataset + * on the first launch. + */ +export class SuggestStore { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + path, + remoteSettingsService) { + + FfiConverterString.checkType(path); + FfiConverterTypeRemoteSettingsService.checkType(remoteSettingsService); + const result = UniFFIScaffolding.callSync( + 39, // uniffi_suggest_fn_constructor_suggeststore_new + FfiConverterString.lower(path), + FfiConverterTypeRemoteSettingsService.lower(remoteSettingsService), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStore.lift.bind(FfiConverterTypeSuggestStore), + null, + ) + } + + /** + * Return whether any suggestions have been dismissed. + */ + async anyDismissedSuggestions() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 40, // uniffi_suggest_fn_method_suggeststore_any_dismissed_suggestions + FfiConverterTypeSuggestStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Removes all content from the database. + */ + async clear() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 41, // uniffi_suggest_fn_method_suggeststore_clear + FfiConverterTypeSuggestStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Clear dismissed suggestions + */ + async clearDismissedSuggestions() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 42, // uniffi_suggest_fn_method_suggeststore_clear_dismissed_suggestions + FfiConverterTypeSuggestStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Dismiss a suggestion by its dismissal key. + * + * Dismissed suggestions cannot be fetched again. + * + * Prefer [SuggestStore::dismiss_by_suggestion] if you have a + * `crate::Suggestion`. This method is intended for cases where a + * suggestion originates outside this component. + */ + async dismissByKey( + key) { + + FfiConverterString.checkType(key); + const result = await UniFFIScaffolding.callAsyncWrapper( + 43, // uniffi_suggest_fn_method_suggeststore_dismiss_by_key + FfiConverterTypeSuggestStore.lower(this), + FfiConverterString.lower(key), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Dismiss a suggestion. + * + * Dismissed suggestions cannot be fetched again. + */ + async dismissBySuggestion( + suggestion) { + + FfiConverterTypeSuggestion.checkType(suggestion); + const result = await UniFFIScaffolding.callAsyncWrapper( + 44, // uniffi_suggest_fn_method_suggeststore_dismiss_by_suggestion + FfiConverterTypeSuggestStore.lower(this), + FfiConverterTypeSuggestion.lower(suggestion), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Deprecated, use [SuggestStore::dismiss_by_suggestion] or + * [SuggestStore::dismiss_by_key] instead. + * + * Dismiss a suggestion + * + * Dismissed suggestions will not be returned again + */ + async dismissSuggestion( + suggestionUrl) { + + FfiConverterString.checkType(suggestionUrl); + const result = await UniFFIScaffolding.callAsyncWrapper( + 45, // uniffi_suggest_fn_method_suggeststore_dismiss_suggestion + FfiConverterTypeSuggestStore.lower(this), + FfiConverterString.lower(suggestionUrl), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Fetches geonames stored in the database. A geoname represents a + * geographic place. + * + * `query` is a string that will be matched directly against geoname names. + * It is not a query string in the usual Suggest sense. `match_name_prefix` + * determines whether prefix matching is performed on names excluding + * abbreviations and airport codes. When `true`, names that start with + * `query` will match. When false, names that equal `query` will match. + * + * `geoname_type` restricts returned geonames to a [`GeonameType`]. + * + * `filter` restricts returned geonames to certain cities or regions. + * Cities can be restricted to regions by including the regions in + * `filter`, and regions can be restricted to those containing certain + * cities by including the cities in `filter`. This is especially useful + * since city and region names are not unique. `filter` is disjunctive: If + * any item in `filter` matches a geoname, the geoname will be filtered in. + * + * The query can match a single geoname in more than one way. For example, + * it can match both a full name and an abbreviation. The returned vec of + * [`GeonameMatch`] values will include all matches for a geoname, one + * match per `match_type` per geoname. In other words, a matched geoname + * can map to more than one `GeonameMatch`. + */ + async fetchGeonames( + query, + matchNamePrefix, + geonameType, + filter) { + + FfiConverterString.checkType(query); + FfiConverterBoolean.checkType(matchNamePrefix); + FfiConverterOptionalTypeGeonameType.checkType(geonameType); + FfiConverterOptionalSequenceTypeGeoname.checkType(filter); + const result = await UniFFIScaffolding.callAsyncWrapper( + 46, // uniffi_suggest_fn_method_suggeststore_fetch_geonames + FfiConverterTypeSuggestStore.lower(this), + FfiConverterString.lower(query), + FfiConverterBoolean.lower(matchNamePrefix), + FfiConverterOptionalTypeGeonameType.lower(geonameType), + FfiConverterOptionalSequenceTypeGeoname.lower(filter), + ) + return handleRustResult( + result, + FfiConverterSequenceTypeGeonameMatch.lift.bind(FfiConverterSequenceTypeGeonameMatch), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Returns global Suggest configuration data. + */ + async fetchGlobalConfig() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 47, // uniffi_suggest_fn_method_suggeststore_fetch_global_config + FfiConverterTypeSuggestStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestGlobalConfig.lift.bind(FfiConverterTypeSuggestGlobalConfig), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Returns per-provider Suggest configuration data. + */ + async fetchProviderConfig( + provider) { + + FfiConverterTypeSuggestionProvider.checkType(provider); + const result = await UniFFIScaffolding.callAsyncWrapper( + 48, // uniffi_suggest_fn_method_suggeststore_fetch_provider_config + FfiConverterTypeSuggestStore.lower(this), + FfiConverterTypeSuggestionProvider.lower(provider), + ) + return handleRustResult( + result, + FfiConverterOptionalTypeSuggestProviderConfig.lift.bind(FfiConverterOptionalTypeSuggestProviderConfig), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Ingests new suggestions from Remote Settings. + */ + async ingest( + constraints) { + + FfiConverterTypeSuggestIngestionConstraints.checkType(constraints); + const result = await UniFFIScaffolding.callAsyncWrapper( + 49, // uniffi_suggest_fn_method_suggeststore_ingest + FfiConverterTypeSuggestStore.lower(this), + FfiConverterTypeSuggestIngestionConstraints.lower(constraints), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestIngestionMetrics.lift.bind(FfiConverterTypeSuggestIngestionMetrics), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Interrupts any ongoing queries. + * + * This should be called when the user types new input into the address + * bar, to ensure that they see fresh suggestions as they type. This + * method does not interrupt any ongoing ingests. + */ + interrupt( + kind = null) { + + FfiConverterOptionalTypeInterruptKind.checkType(kind); + const result = UniFFIScaffolding.callSync( + 50, // uniffi_suggest_fn_method_suggeststore_interrupt + FfiConverterTypeSuggestStore.lower(this), + FfiConverterOptionalTypeInterruptKind.lower(kind), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + + /** + * Return whether a suggestion has been dismissed given its dismissal key. + * + * [SuggestStore::query] will never return dismissed suggestions, so + * normally you never need to know whether a suggestion has been dismissed. + * This method is intended for cases where a dismissal key originates + * outside this component. + */ + async isDismissedByKey( + key) { + + FfiConverterString.checkType(key); + const result = await UniFFIScaffolding.callAsyncWrapper( + 51, // uniffi_suggest_fn_method_suggeststore_is_dismissed_by_key + FfiConverterTypeSuggestStore.lower(this), + FfiConverterString.lower(key), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Return whether a suggestion has been dismissed. + * + * [SuggestStore::query] will never return dismissed suggestions, so + * normally you never need to know whether a `Suggestion` has been + * dismissed, but this method can be used to do so. + */ + async isDismissedBySuggestion( + suggestion) { + + FfiConverterTypeSuggestion.checkType(suggestion); + const result = await UniFFIScaffolding.callAsyncWrapper( + 52, // uniffi_suggest_fn_method_suggeststore_is_dismissed_by_suggestion + FfiConverterTypeSuggestStore.lower(this), + FfiConverterTypeSuggestion.lower(suggestion), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Queries the database for suggestions. + */ + async query( + query) { + + FfiConverterTypeSuggestionQuery.checkType(query); + const result = await UniFFIScaffolding.callAsyncWrapper( + 53, // uniffi_suggest_fn_method_suggeststore_query + FfiConverterTypeSuggestStore.lower(this), + FfiConverterTypeSuggestionQuery.lower(query), + ) + return handleRustResult( + result, + FfiConverterSequenceTypeSuggestion.lift.bind(FfiConverterSequenceTypeSuggestion), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Queries the database for suggestions. + */ + async queryWithMetrics( + query) { + + FfiConverterTypeSuggestionQuery.checkType(query); + const result = await UniFFIScaffolding.callAsyncWrapper( + 54, // uniffi_suggest_fn_method_suggeststore_query_with_metrics + FfiConverterTypeSuggestStore.lower(this), + FfiConverterTypeSuggestionQuery.lower(query), + ) + return handleRustResult( + result, + FfiConverterTypeQueryWithMetricsResult.lift.bind(FfiConverterTypeQueryWithMetricsResult), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestStore extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new SuggestStore(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'SuggestStore' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(7)); + } + + static write(dataStream, value) { + dataStream.writePointer(7, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +import { + FfiConverterTypeRemoteSettingsServer, +} from "./RustRemoteSettings.sys.mjs"; + +// Export the FFIConverter object to make external types work. +export { FfiConverterTypeRemoteSettingsServer }; +import { + FfiConverterTypeRemoteSettingsService, +} from "./RustRemoteSettings.sys.mjs"; + +// Export the FFIConverter object to make external types work. +export { FfiConverterTypeRemoteSettingsService }; +/** + * Builder for [SuggestStore] + * + * Using a builder is preferred to calling the constructor directly since it's harder to confuse + * the data_path and cache_path strings. + */ +export class SuggestStoreBuilder { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init() { + + const result = UniFFIScaffolding.callSync( + 55, // uniffi_suggest_fn_constructor_suggeststorebuilder_new + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + + /** + * build + */ + build() { + + const result = UniFFIScaffolding.callSync( + 56, // uniffi_suggest_fn_method_suggeststorebuilder_build + FfiConverterTypeSuggestStoreBuilder.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStore.lift.bind(FfiConverterTypeSuggestStore), + FfiConverterTypeSuggestApiError.lift.bind(FfiConverterTypeSuggestApiError), + ) + } + + /** + * Deprecated: this is no longer used by the suggest component. + */ + async cachePath( + path) { + + FfiConverterString.checkType(path); + const result = await UniFFIScaffolding.callAsyncWrapper( + 57, // uniffi_suggest_fn_method_suggeststorebuilder_cache_path + FfiConverterTypeSuggestStoreBuilder.lower(this), + FfiConverterString.lower(path), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + + /** + * dataPath + */ + dataPath( + path) { + + FfiConverterString.checkType(path); + const result = UniFFIScaffolding.callSync( + 58, // uniffi_suggest_fn_method_suggeststorebuilder_data_path + FfiConverterTypeSuggestStoreBuilder.lower(this), + FfiConverterString.lower(path), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + + /** + * Add an sqlite3 extension to load + * + * library_name should be the name of the library without any extension, for example `libmozsqlite3`. + * entrypoint should be the entry point, for example `sqlite3_fts5_init`. If `null` (the default) + * entry point will be used (see https://sqlite.org/loadext.html for details). + */ + loadExtension( + library, + entryPoint) { + + FfiConverterString.checkType(library); + FfiConverterOptionalString.checkType(entryPoint); + const result = UniFFIScaffolding.callSync( + 59, // uniffi_suggest_fn_method_suggeststorebuilder_load_extension + FfiConverterTypeSuggestStoreBuilder.lower(this), + FfiConverterString.lower(library), + FfiConverterOptionalString.lower(entryPoint), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + + /** + * remoteSettingsBucketName + */ + remoteSettingsBucketName( + bucketName) { + + FfiConverterString.checkType(bucketName); + const result = UniFFIScaffolding.callSync( + 60, // uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_bucket_name + FfiConverterTypeSuggestStoreBuilder.lower(this), + FfiConverterString.lower(bucketName), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + + /** + * remoteSettingsServer + */ + remoteSettingsServer( + server) { + + FfiConverterTypeRemoteSettingsServer.checkType(server); + const result = UniFFIScaffolding.callSync( + 61, // uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_server + FfiConverterTypeSuggestStoreBuilder.lower(this), + FfiConverterTypeRemoteSettingsServer.lower(server), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + + /** + * remoteSettingsService + */ + remoteSettingsService( + rsService) { + + FfiConverterTypeRemoteSettingsService.checkType(rsService); + const result = UniFFIScaffolding.callSync( + 62, // uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_service + FfiConverterTypeSuggestStoreBuilder.lower(this), + FfiConverterTypeRemoteSettingsService.lower(rsService), + ) + return handleRustResult( + result, + FfiConverterTypeSuggestStoreBuilder.lift.bind(FfiConverterTypeSuggestStoreBuilder), + null, + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSuggestStoreBuilder extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new SuggestStoreBuilder(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'SuggestStoreBuilder' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(8)); + } + + static write(dataStream, value) { + dataStream.writePointer(8, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSync15.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSync15.sys.mjs index 3d874766a665..10bb10aab3bd 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSync15.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSync15.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -170,6 +168,23 @@ class ArrayBufferDataStream { this.writeUint8(elt); }) } + + // Reads a pointer from the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + readPointer(pointerId) { + const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); + this.pos += 8; + return res; + } + + // Writes a pointer into the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + writePointer(pointerId, value) { + UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); + this.pos += 8; + } } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -268,40 +283,10 @@ const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - /** * Enumeration for the different types of device. - * + * * Firefox Accounts separates devices into broad categories for display purposes, * such as distinguishing a desktop PC from a mobile phone. Upon signin, the * application should inspect the device it is running on and select an appropriate @@ -311,36 +296,33 @@ export const DeviceType = { /** * DESKTOP */ - DESKTOP:0, + DESKTOP: 1, /** * MOBILE */ - MOBILE:1, + MOBILE: 2, /** * TABLET */ - TABLET:2, + TABLET: 3, /** * VR */ - VR:3, + VR: 4, /** * TV */ - TV:4, + TV: 5, /** * UNKNOWN */ - UNKNOWN:5, + UNKNOWN: 6, }; - Object.freeze(DeviceType); + // Export the FFIConverter object to make external types work. export class FfiConverterTypeDeviceType extends FfiConverterArrayBuffer { - static #validValues = Object.values(DeviceType); - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { case 1: return DeviceType.DESKTOP @@ -392,14 +374,35 @@ export class FfiConverterTypeDeviceType extends FfiConverterArrayBuffer { } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { + if (!Number.isInteger(value) || value < 1 || value > 6) { throw new UniFFITypeError(`${value} is not a valid value for DeviceType`); } } } - - - - - +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustTabs.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustTabs.sys.mjs index d3650a6e7801..1b9792d07b08 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustTabs.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustTabs.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,65 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a RemoteCommandStore pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerRemoteCommandStore() { - const pointerId = 8; // tabs:RemoteCommandStore + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a RemoteCommandStore pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerRemoteCommandStore(value) { - const pointerId = 8; // tabs:RemoteCommandStore + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - - - // Reads a TabsBridgedEngine pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerTabsBridgedEngine() { - const pointerId = 9; // tabs:TabsBridgedEngine - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a TabsBridgedEngine pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerTabsBridgedEngine(value) { - const pointerId = 9; // tabs:TabsBridgedEngine - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a TabsStore pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerTabsStore() { - const pointerId = 10; // tabs:TabsStore - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a TabsStore pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerTabsStore(value) { - const pointerId = 10; // tabs:TabsStore - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -328,54 +283,6 @@ const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; -// Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt64(value) - } - static read(dataStream) { - return dataStream.readInt64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -405,789 +312,367 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - -/** - * RemoteCommandStore - */ -export class RemoteCommandStore { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * Add a new command, after which it will be pending. Returns false if the command is already active. - * @returns {Boolean} - */ - addRemoteCommand(deviceId,command) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(deviceId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("deviceId"); - } - throw e; - } - try { - FfiConverterTypeRemoteCommand.checkType(command) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("command"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 62, // tabs:uniffi_tabs_fn_method_remotecommandstore_add_remote_command - FfiConverterTypeRemoteCommandStore.lower(this), - FfiConverterString.lower(deviceId), - FfiConverterTypeRemoteCommand.lower(command), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Add a new command with an explicit timestamp. Primarily used by tests. - * @returns {Boolean} - */ - addRemoteCommandAt(deviceId,command,when) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(deviceId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("deviceId"); - } - throw e; - } - try { - FfiConverterTypeRemoteCommand.checkType(command) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("command"); - } - throw e; - } - try { - FfiConverterTypeTimestamp.checkType(when) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("when"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 63, // tabs:uniffi_tabs_fn_method_remotecommandstore_add_remote_command_at - FfiConverterTypeRemoteCommandStore.lower(this), - FfiConverterString.lower(deviceId), - FfiConverterTypeRemoteCommand.lower(command), - FfiConverterTypeTimestamp.lower(when), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Return all unsent commands. This is for the code sending the commands, result is sorted by time_requested. - * @returns {Array.} - */ - getUnsentCommands() { - const liftResult = (result) => FfiConverterSequenceTypePendingCommand.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 64, // tabs:uniffi_tabs_fn_method_remotecommandstore_get_unsent_commands - FfiConverterTypeRemoteCommandStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Removes the remote command. Typically used to implement "undo" but may also be used by the queue - * processor when it gives up trying to send a command. - * @returns {Boolean} - */ - removeRemoteCommand(deviceId,command) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(deviceId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("deviceId"); - } - throw e; - } - try { - FfiConverterTypeRemoteCommand.checkType(command) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("command"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 65, // tabs:uniffi_tabs_fn_method_remotecommandstore_remove_remote_command - FfiConverterTypeRemoteCommandStore.lower(this), - FfiConverterString.lower(deviceId), - FfiConverterTypeRemoteCommand.lower(command), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Flag a command as sent. - * @returns {Boolean} - */ - setPendingCommandSent(command) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterTypePendingCommand.checkType(command) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("command"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 66, // tabs:uniffi_tabs_fn_method_remotecommandstore_set_pending_command_sent - FfiConverterTypeRemoteCommandStore.lower(this), - FfiConverterTypePendingCommand.lower(command), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} +import { + FfiConverterTypeDeviceType, +} from "./RustSync15.sys.mjs"; // Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteCommandStore extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new RemoteCommandStore(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'RemoteCommandStore' instance"); +export { FfiConverterTypeDeviceType }; +// Export the FFIConverter object to make external types work. +export class FfiConverterInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); } - return ptr; } - + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt64(value) + } static read(dataStream) { - return this.lift(dataStream.readPointerRemoteCommandStore()); + return dataStream.readInt64() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceString extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterString.read(dataStream)); + } + return arr; } static write(dataStream, value) { - dataStream.writePointerRemoteCommandStore(value[uniffiObjectPtr]); + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterString.write(dataStream, innerValue); + }) } static computeSize(value) { - return 8; + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterString.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterString.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) } } - -/** - * Note the canonical docs for this are in https://searchfox.org/mozilla-central/source/services/interfaces/mozIBridgedSyncEngine.idl - * It's only actually used in desktop, but it's fine to expose this everywhere. - * NOTE: all timestamps here are milliseconds. - */ -export class TabsBridgedEngine { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * apply - * @returns {Array.} - */ - apply() { - const liftResult = (result) => FfiConverterSequencestring.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 67, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_apply - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * ensureCurrentSyncId - * @returns {string} - */ - ensureCurrentSyncId(newSyncId) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(newSyncId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("newSyncId"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 68, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_ensure_current_sync_id - FfiConverterTypeTabsBridgedEngine.lower(this), - FfiConverterString.lower(newSyncId), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * lastSync - * @returns {number} - */ - lastSync() { - const liftResult = (result) => FfiConverterI64.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 69, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_last_sync - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * prepareForSync - */ - prepareForSync(clientData) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(clientData) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("clientData"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 70, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_prepare_for_sync - FfiConverterTypeTabsBridgedEngine.lower(this), - FfiConverterString.lower(clientData), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * reset - */ - reset() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 71, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_reset - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * resetSyncId - * @returns {string} - */ - resetSyncId() { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 72, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_reset_sync_id - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * setLastSync - */ - setLastSync(lastSync) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterI64.checkType(lastSync) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("lastSync"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 73, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_set_last_sync - FfiConverterTypeTabsBridgedEngine.lower(this), - FfiConverterI64.lower(lastSync), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * setUploaded - */ - setUploaded(newTimestamp,uploadedIds) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterI64.checkType(newTimestamp) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("newTimestamp"); - } - throw e; - } - try { - FfiConverterSequenceTypeTabsGuid.checkType(uploadedIds) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("uploadedIds"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 74, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_set_uploaded - FfiConverterTypeTabsBridgedEngine.lower(this), - FfiConverterI64.lower(newTimestamp), - FfiConverterSequenceTypeTabsGuid.lower(uploadedIds), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * storeIncoming - */ - storeIncoming(incomingEnvelopesAsJson) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - try { - FfiConverterSequencestring.checkType(incomingEnvelopesAsJson) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("incomingEnvelopesAsJson"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 75, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_store_incoming - FfiConverterTypeTabsBridgedEngine.lower(this), - FfiConverterSequencestring.lower(incomingEnvelopesAsJson), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * syncFinished - */ - syncFinished() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 76, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_sync_finished - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * syncId - * @returns {?string} - */ - syncId() { - const liftResult = (result) => FfiConverterOptionalstring.lift(result); - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 77, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_sync_id - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * syncStarted - */ - syncStarted() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 78, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_sync_started - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * wipe - */ - wipe() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTabsApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 79, // tabs:uniffi_tabs_fn_method_tabsbridgedengine_wipe - FfiConverterTypeTabsBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeTabsBridgedEngine extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new TabsBridgedEngine(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'TabsBridgedEngine' instance"); +export class FfiConverterOptionalString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterString.checkType(value) } - return ptr; } static read(dataStream) { - return this.lift(dataStream.readPointerTabsBridgedEngine()); + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } } static write(dataStream, value) { - dataStream.writePointerTabsBridgedEngine(value[uniffiObjectPtr]); + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterString.write(dataStream, value) } static computeSize(value) { - return 8; + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterString.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterBoolean extends FfiConverter { + static computeSize(_value) { + return 1; + } + static lift(value) { + return value == 1; + } + static lower(value) { + if (value) { + return 1; + } else { + return 0; + } + } + static write(dataStream, value) { + dataStream.writeUint8(this.lower(value)) + } + static read(dataStream) { + return this.lift(dataStream.readUint8()) } } - /** - * TabsStore + * RemoteTabRecord */ -export class TabsStore { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") +export class RemoteTabRecord { + constructor( + { + title, + urlHistory, + icon, + lastUsed, + inactive= false + } = { + title: undefined, + urlHistory: undefined, + icon: undefined, + lastUsed: undefined, + inactive: undefined } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {TabsStore} - */ - static init(path) { - const liftResult = (result) => FfiConverterTypeTabsStore.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(path) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("path"); - } - throw e; + ) { + try { + FfiConverterString.checkType(title) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("title"); } - return UniFFIScaffolding.callAsyncWrapper( - 86, // tabs:uniffi_tabs_fn_constructor_tabsstore_new - FfiConverterString.lower(path), - ) + throw e; } try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * bridgedEngine - * @returns {TabsBridgedEngine} - */ - bridgedEngine() { - const liftResult = (result) => FfiConverterTypeTabsBridgedEngine.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 80, // tabs:uniffi_tabs_fn_method_tabsstore_bridged_engine - FfiConverterTypeTabsStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * closeConnection - */ - closeConnection() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 81, // tabs:uniffi_tabs_fn_method_tabsstore_close_connection - FfiConverterTypeTabsStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getAll - * @returns {Array.} - */ - getAll() { - const liftResult = (result) => FfiConverterSequenceTypeClientRemoteTabs.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 82, // tabs:uniffi_tabs_fn_method_tabsstore_get_all - FfiConverterTypeTabsStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * newRemoteCommandStore - * @returns {RemoteCommandStore} - */ - newRemoteCommandStore() { - const liftResult = (result) => FfiConverterTypeRemoteCommandStore.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 83, // tabs:uniffi_tabs_fn_method_tabsstore_new_remote_command_store - FfiConverterTypeTabsStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * registerWithSyncManager - */ - registerWithSyncManager() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 84, // tabs:uniffi_tabs_fn_method_tabsstore_register_with_sync_manager - FfiConverterTypeTabsStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * setLocalTabs - */ - setLocalTabs(remoteTabs) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterSequenceTypeRemoteTabRecord.checkType(remoteTabs) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("remoteTabs"); - } - throw e; + FfiConverterSequenceString.checkType(urlHistory) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("urlHistory"); } - return UniFFIScaffolding.callAsyncWrapper( - 85, // tabs:uniffi_tabs_fn_method_tabsstore_set_local_tabs - FfiConverterTypeTabsStore.lower(this), - FfiConverterSequenceTypeRemoteTabRecord.lower(remoteTabs), - ) + throw e; } try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) + FfiConverterOptionalString.checkType(icon) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("icon"); + } + throw e; } + try { + FfiConverterInt64.checkType(lastUsed) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("lastUsed"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(inactive) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("inactive"); + } + throw e; + } + /** + * title + */ + this.title = title; + /** + * urlHistory + */ + this.urlHistory = urlHistory; + /** + * icon + */ + this.icon = icon; + /** + * Number of ms since the unix epoch (as reported by the client's clock) + */ + this.lastUsed = lastUsed; + /** + * inactive + */ + this.inactive = inactive; } + equals(other) { + return ( + this.title == other.title + && this.urlHistory == other.urlHistory + && this.icon == other.icon + && this.lastUsed == other.lastUsed + && this.inactive == other.inactive + ) + } } // Export the FFIConverter object to make external types work. -export class FfiConverterTypeTabsStore extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new TabsStore(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'TabsStore' instance"); - } - return ptr; - } - +export class FfiConverterTypeRemoteTabRecord extends FfiConverterArrayBuffer { static read(dataStream) { - return this.lift(dataStream.readPointerTabsStore()); + return new RemoteTabRecord({ + title: FfiConverterString.read(dataStream), + urlHistory: FfiConverterSequenceString.read(dataStream), + icon: FfiConverterOptionalString.read(dataStream), + lastUsed: FfiConverterInt64.read(dataStream), + inactive: FfiConverterBoolean.read(dataStream), + }); } - static write(dataStream, value) { - dataStream.writePointerTabsStore(value[uniffiObjectPtr]); + FfiConverterString.write(dataStream, value.title); + FfiConverterSequenceString.write(dataStream, value.urlHistory); + FfiConverterOptionalString.write(dataStream, value.icon); + FfiConverterInt64.write(dataStream, value.lastUsed); + FfiConverterBoolean.write(dataStream, value.inactive); } static computeSize(value) { - return 8; + let totalSize = 0; + totalSize += FfiConverterString.computeSize(value.title); + totalSize += FfiConverterSequenceString.computeSize(value.urlHistory); + totalSize += FfiConverterOptionalString.computeSize(value.icon); + totalSize += FfiConverterInt64.computeSize(value.lastUsed); + totalSize += FfiConverterBoolean.computeSize(value.inactive); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof RemoteTabRecord)) { + throw new UniFFITypeError(`Expected 'RemoteTabRecord', found '${typeof value}'`); + } + try { + FfiConverterString.checkType(value.title); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".title"); + } + throw e; + } + try { + FfiConverterSequenceString.checkType(value.urlHistory); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".urlHistory"); + } + throw e; + } + try { + FfiConverterOptionalString.checkType(value.icon); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".icon"); + } + throw e; + } + try { + FfiConverterInt64.checkType(value.lastUsed); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".lastUsed"); + } + throw e; + } + try { + FfiConverterBoolean.checkType(value.inactive); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".inactive"); + } + throw e; + } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeRemoteTabRecord extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeRemoteTabRecord.read(dataStream)); + } + return arr; + } + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeRemoteTabRecord.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeRemoteTabRecord.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeRemoteTabRecord.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} /** * ClientRemoteTabs */ export class ClientRemoteTabs { - constructor({ clientId, clientName, deviceType, lastModified, remoteTabs } = { clientId: undefined, clientName: undefined, deviceType: undefined, lastModified: undefined, remoteTabs: undefined }) { + constructor( + { + clientId, + clientName, + deviceType, + lastModified, + remoteTabs + } = { + clientId: undefined, + clientName: undefined, + deviceType: undefined, + lastModified: undefined, + remoteTabs: undefined + } + ) { try { FfiConverterString.checkType(clientId) } catch (e) { @@ -1213,7 +698,7 @@ export class ClientRemoteTabs { throw e; } try { - FfiConverterI64.checkType(lastModified) + FfiConverterInt64.checkType(lastModified) } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("lastModified"); @@ -1229,35 +714,34 @@ export class ClientRemoteTabs { throw e; } /** - * @type {string} + * clientId */ this.clientId = clientId; /** - * @type {string} + * clientName */ this.clientName = clientName; /** - * @type {DeviceType} + * deviceType */ this.deviceType = deviceType; /** * Number of ms since the unix epoch (as reported by the server's clock) - * @type {number} */ this.lastModified = lastModified; /** - * @type {Array.} + * remoteTabs */ this.remoteTabs = remoteTabs; } equals(other) { return ( - this.clientId == other.clientId && - this.clientName == other.clientName && - this.deviceType == other.deviceType && - this.lastModified == other.lastModified && - this.remoteTabs == other.remoteTabs + this.clientId == other.clientId + && this.clientName == other.clientName + && this.deviceType == other.deviceType + && this.lastModified == other.lastModified + && this.remoteTabs == other.remoteTabs ) } } @@ -1269,7 +753,7 @@ export class FfiConverterTypeClientRemoteTabs extends FfiConverterArrayBuffer { clientId: FfiConverterString.read(dataStream), clientName: FfiConverterString.read(dataStream), deviceType: FfiConverterTypeDeviceType.read(dataStream), - lastModified: FfiConverterI64.read(dataStream), + lastModified: FfiConverterInt64.read(dataStream), remoteTabs: FfiConverterSequenceTypeRemoteTabRecord.read(dataStream), }); } @@ -1277,7 +761,7 @@ export class FfiConverterTypeClientRemoteTabs extends FfiConverterArrayBuffer { FfiConverterString.write(dataStream, value.clientId); FfiConverterString.write(dataStream, value.clientName); FfiConverterTypeDeviceType.write(dataStream, value.deviceType); - FfiConverterI64.write(dataStream, value.lastModified); + FfiConverterInt64.write(dataStream, value.lastModified); FfiConverterSequenceTypeRemoteTabRecord.write(dataStream, value.remoteTabs); } @@ -1286,7 +770,7 @@ export class FfiConverterTypeClientRemoteTabs extends FfiConverterArrayBuffer { totalSize += FfiConverterString.computeSize(value.clientId); totalSize += FfiConverterString.computeSize(value.clientName); totalSize += FfiConverterTypeDeviceType.computeSize(value.deviceType); - totalSize += FfiConverterI64.computeSize(value.lastModified); + totalSize += FfiConverterInt64.computeSize(value.lastModified); totalSize += FfiConverterSequenceTypeRemoteTabRecord.computeSize(value.remoteTabs); return totalSize } @@ -1321,7 +805,7 @@ export class FfiConverterTypeClientRemoteTabs extends FfiConverterArrayBuffer { throw e; } try { - FfiConverterI64.checkType(value.lastModified); + FfiConverterInt64.checkType(value.lastModified); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(".lastModified"); @@ -1339,11 +823,137 @@ export class FfiConverterTypeClientRemoteTabs extends FfiConverterArrayBuffer { } } +/** + * A command which should be sent to a remote device. + */ +export class RemoteCommand {} +/** + * CloseTab + */ +RemoteCommand.CloseTab = class extends RemoteCommand{ + constructor( + url + ) { + super(); + this.url = url; + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRemoteCommand extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new RemoteCommand.CloseTab( + FfiConverterString.read(dataStream) + ); + default: + throw new UniFFITypeError("Unknown RemoteCommand variant"); + } + } + + static write(dataStream, value) { + if (value instanceof RemoteCommand.CloseTab) { + dataStream.writeInt32(1); + FfiConverterString.write(dataStream, value.url); + return; + } + throw new UniFFITypeError("Unknown RemoteCommand variant"); + } + + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof RemoteCommand.CloseTab) { + totalSize += FfiConverterString.computeSize(value.url); + return totalSize; + } + throw new UniFFITypeError("Unknown RemoteCommand variant"); + } + + static checkType(value) { + if (!(value instanceof RemoteCommand)) { + throw new UniFFITypeError(`${value} is not a subclass instance of RemoteCommand`); + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeTimestamp extends FfiConverter { + static lift(buf) { + return FfiConverterInt64.lift(buf); + } + + static lower(buf) { + return FfiConverterInt64.lower(buf); + } + + static write(dataStream, value) { + FfiConverterInt64.write(dataStream, value); + } + + static read(buf) { + return FfiConverterInt64.read(buf); + } + + static computeSize(value) { + return FfiConverterInt64.computeSize(value); + } +} + +// TODO: We should also allow JS to customize the type eventually. +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalTypeTimestamp extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterTypeTimestamp.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeTimestamp.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeTimestamp.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeTimestamp.computeSize(value) + } +} /** * Represents a "pending" command. */ export class PendingCommand { - constructor({ deviceId, command, timeRequested, timeSent } = { deviceId: undefined, command: undefined, timeRequested: undefined, timeSent: undefined }) { + constructor( + { + deviceId, + command, + timeRequested, + timeSent + } = { + deviceId: undefined, + command: undefined, + timeRequested: undefined, + timeSent: undefined + } + ) { try { FfiConverterString.checkType(deviceId) } catch (e) { @@ -1377,29 +987,29 @@ export class PendingCommand { throw e; } /** - * @type {string} + * deviceId */ this.deviceId = deviceId; /** - * @type {RemoteCommand} + * command */ this.command = command; /** - * @type {Timestamp} + * timeRequested */ this.timeRequested = timeRequested; /** - * @type {?Timestamp} + * timeSent */ this.timeSent = timeSent; } equals(other) { return ( - this.deviceId == other.deviceId && - this.command == other.command && - this.timeRequested == other.timeRequested && - this.timeSent == other.timeSent + this.deviceId == other.deviceId + && this.command == other.command + && this.timeRequested == other.timeRequested + && this.timeSent == other.timeSent ) } } @@ -1470,223 +1080,6 @@ export class FfiConverterTypePendingCommand extends FfiConverterArrayBuffer { } } -/** - * RemoteTabRecord - */ -export class RemoteTabRecord { - constructor({ title, urlHistory, icon, lastUsed, inactive = false } = { title: undefined, urlHistory: undefined, icon: undefined, lastUsed: undefined, inactive: undefined }) { - try { - FfiConverterString.checkType(title) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("title"); - } - throw e; - } - try { - FfiConverterSequencestring.checkType(urlHistory) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("urlHistory"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(icon) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("icon"); - } - throw e; - } - try { - FfiConverterI64.checkType(lastUsed) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("lastUsed"); - } - throw e; - } - try { - FfiConverterBool.checkType(inactive) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("inactive"); - } - throw e; - } - /** - * @type {string} - */ - this.title = title; - /** - * @type {Array.} - */ - this.urlHistory = urlHistory; - /** - * @type {?string} - */ - this.icon = icon; - /** - * Number of ms since the unix epoch (as reported by the client's clock) - * @type {number} - */ - this.lastUsed = lastUsed; - /** - * @type {Boolean} - */ - this.inactive = inactive; - } - - equals(other) { - return ( - this.title == other.title && - this.urlHistory == other.urlHistory && - this.icon == other.icon && - this.lastUsed == other.lastUsed && - this.inactive == other.inactive - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteTabRecord extends FfiConverterArrayBuffer { - static read(dataStream) { - return new RemoteTabRecord({ - title: FfiConverterString.read(dataStream), - urlHistory: FfiConverterSequencestring.read(dataStream), - icon: FfiConverterOptionalstring.read(dataStream), - lastUsed: FfiConverterI64.read(dataStream), - inactive: FfiConverterBool.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterString.write(dataStream, value.title); - FfiConverterSequencestring.write(dataStream, value.urlHistory); - FfiConverterOptionalstring.write(dataStream, value.icon); - FfiConverterI64.write(dataStream, value.lastUsed); - FfiConverterBool.write(dataStream, value.inactive); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterString.computeSize(value.title); - totalSize += FfiConverterSequencestring.computeSize(value.urlHistory); - totalSize += FfiConverterOptionalstring.computeSize(value.icon); - totalSize += FfiConverterI64.computeSize(value.lastUsed); - totalSize += FfiConverterBool.computeSize(value.inactive); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof RemoteTabRecord)) { - throw new UniFFITypeError(`Expected 'RemoteTabRecord', found '${typeof value}'`); - } - try { - FfiConverterString.checkType(value.title); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".title"); - } - throw e; - } - try { - FfiConverterSequencestring.checkType(value.urlHistory); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".urlHistory"); - } - throw e; - } - try { - FfiConverterOptionalstring.checkType(value.icon); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".icon"); - } - throw e; - } - try { - FfiConverterI64.checkType(value.lastUsed); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".lastUsed"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.inactive); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".inactive"); - } - throw e; - } - } -} - - -/** - * A command which should be sent to a remote device. - */ -export class RemoteCommand {} -/** - * CloseTab - */ -RemoteCommand.CloseTab = class extends RemoteCommand{ - constructor( - url - ) { - super(); - this.url = url; - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRemoteCommand extends FfiConverterArrayBuffer { - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return new RemoteCommand.CloseTab( - FfiConverterString.read(dataStream) - ); - default: - throw new UniFFITypeError("Unknown RemoteCommand variant"); - } - } - - static write(dataStream, value) { - if (value instanceof RemoteCommand.CloseTab) { - dataStream.writeInt32(1); - FfiConverterString.write(dataStream, value.url); - return; - } - throw new UniFFITypeError("Unknown RemoteCommand variant"); - } - - static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof RemoteCommand.CloseTab) { - totalSize += FfiConverterString.computeSize(value.url); - return totalSize; - } - throw new UniFFITypeError("Unknown RemoteCommand variant"); - } - - static checkType(value) { - if (value === undefined || value === null || !(value instanceof RemoteCommand)) { - throw new UniFFITypeError(`${value} is not a subclass instance of RemoteCommand`); - } - } -} - - - - - /** * TabsApiError */ @@ -1805,169 +1198,30 @@ export class FfiConverterTypeTabsApiError extends FfiConverterArrayBuffer { static errorClass = TabsApiError; } - // Export the FFIConverter object to make external types work. -export class FfiConverterOptionalstring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterString.checkType(value) - } +export class FfiConverterTypeTabsGuid extends FfiConverter { + static lift(buf) { + return FfiConverterString.lift(buf); } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } + + static lower(buf) { + return FfiConverterString.lower(buf); } - + static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterString.write(dataStream, value) + FfiConverterString.write(dataStream, value); + } + + static read(buf) { + return FfiConverterString.read(buf); } - + static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterString.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeTimestamp extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeTimestamp.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeTimestamp.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeTimestamp.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeTimestamp.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterString.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterString.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterString.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterString.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeClientRemoteTabs extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeClientRemoteTabs.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeClientRemoteTabs.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeClientRemoteTabs.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeClientRemoteTabs.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) + return FfiConverterString.computeSize(value); } } +// TODO: We should also allow JS to customize the type eventually. // Export the FFIConverter object to make external types work. export class FfiConverterSequenceTypePendingCommand extends FfiConverterArrayBuffer { static read(dataStream) { @@ -2011,51 +1265,158 @@ export class FfiConverterSequenceTypePendingCommand extends FfiConverterArrayBuf }) } } +/** + * RemoteCommandStore + */ +export class RemoteCommandStore { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + /** + * Add a new command, after which it will be pending. Returns false if the command is already active. + */ + async addRemoteCommand( + deviceId, + command) { + + FfiConverterString.checkType(deviceId); + FfiConverterTypeRemoteCommand.checkType(command); + const result = await UniFFIScaffolding.callAsyncWrapper( + 63, // uniffi_tabs_fn_method_remotecommandstore_add_remote_command + FfiConverterTypeRemoteCommandStore.lower(this), + FfiConverterString.lower(deviceId), + FfiConverterTypeRemoteCommand.lower(command), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * Add a new command with an explicit timestamp. Primarily used by tests. + */ + async addRemoteCommandAt( + deviceId, + command, + when) { + + FfiConverterString.checkType(deviceId); + FfiConverterTypeRemoteCommand.checkType(command); + FfiConverterTypeTimestamp.checkType(when); + const result = await UniFFIScaffolding.callAsyncWrapper( + 64, // uniffi_tabs_fn_method_remotecommandstore_add_remote_command_at + FfiConverterTypeRemoteCommandStore.lower(this), + FfiConverterString.lower(deviceId), + FfiConverterTypeRemoteCommand.lower(command), + FfiConverterTypeTimestamp.lower(when), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * Return all unsent commands. This is for the code sending the commands, result is sorted by time_requested. + */ + async getUnsentCommands() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 65, // uniffi_tabs_fn_method_remotecommandstore_get_unsent_commands + FfiConverterTypeRemoteCommandStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterSequenceTypePendingCommand.lift.bind(FfiConverterSequenceTypePendingCommand), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * Removes the remote command. Typically used to implement "undo" but may also be used by the queue + * processor when it gives up trying to send a command. + */ + async removeRemoteCommand( + deviceId, + command) { + + FfiConverterString.checkType(deviceId); + FfiConverterTypeRemoteCommand.checkType(command); + const result = await UniFFIScaffolding.callAsyncWrapper( + 66, // uniffi_tabs_fn_method_remotecommandstore_remove_remote_command + FfiConverterTypeRemoteCommandStore.lower(this), + FfiConverterString.lower(deviceId), + FfiConverterTypeRemoteCommand.lower(command), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * Flag a command as sent. + */ + async setPendingCommandSent( + command) { + + FfiConverterTypePendingCommand.checkType(command); + const result = await UniFFIScaffolding.callAsyncWrapper( + 67, // uniffi_tabs_fn_method_remotecommandstore_set_pending_command_sent + FfiConverterTypeRemoteCommandStore.lower(this), + FfiConverterTypePendingCommand.lower(command), + ) + return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + +} // Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeRemoteTabRecord extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeRemoteTabRecord.read(dataStream)); +export class FfiConverterTypeRemoteCommandStore extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new RemoteCommandStore(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'RemoteCommandStore' instance"); } - return arr; + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(9)); } static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeRemoteTabRecord.write(dataStream, innerValue); - }) + dataStream.writePointer(9, this.lower(value)); } static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeRemoteTabRecord.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeRemoteTabRecord.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) + return 8; } } - // Export the FFIConverter object to make external types work. export class FfiConverterSequenceTypeTabsGuid extends FfiConverterArrayBuffer { static read(dataStream) { @@ -2099,61 +1460,509 @@ export class FfiConverterSequenceTypeTabsGuid extends FfiConverterArrayBuffer { }) } } +/** + * Note the canonical docs for this are in https://searchfox.org/mozilla-central/source/services/interfaces/mozIBridgedSyncEngine.idl + * It's only actually used in desktop, but it's fine to expose this everywhere. + * NOTE: all timestamps here are milliseconds. + */ +export class TabsBridgedEngine { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + /** + * apply + */ + async apply() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 68, // uniffi_tabs_fn_method_tabsbridgedengine_apply + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterSequenceString.lift.bind(FfiConverterSequenceString), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * ensureCurrentSyncId + */ + async ensureCurrentSyncId( + newSyncId) { + + FfiConverterString.checkType(newSyncId); + const result = await UniFFIScaffolding.callAsyncWrapper( + 69, // uniffi_tabs_fn_method_tabsbridgedengine_ensure_current_sync_id + FfiConverterTypeTabsBridgedEngine.lower(this), + FfiConverterString.lower(newSyncId), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * lastSync + */ + async lastSync() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 70, // uniffi_tabs_fn_method_tabsbridgedengine_last_sync + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterInt64.lift.bind(FfiConverterInt64), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * prepareForSync + */ + async prepareForSync( + clientData) { + + FfiConverterString.checkType(clientData); + const result = await UniFFIScaffolding.callAsyncWrapper( + 71, // uniffi_tabs_fn_method_tabsbridgedengine_prepare_for_sync + FfiConverterTypeTabsBridgedEngine.lower(this), + FfiConverterString.lower(clientData), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * reset + */ + async reset() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 72, // uniffi_tabs_fn_method_tabsbridgedengine_reset + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * resetSyncId + */ + async resetSyncId() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 73, // uniffi_tabs_fn_method_tabsbridgedengine_reset_sync_id + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * setLastSync + */ + async setLastSync( + lastSync) { + + FfiConverterInt64.checkType(lastSync); + const result = await UniFFIScaffolding.callAsyncWrapper( + 74, // uniffi_tabs_fn_method_tabsbridgedengine_set_last_sync + FfiConverterTypeTabsBridgedEngine.lower(this), + FfiConverterInt64.lower(lastSync), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * setUploaded + */ + async setUploaded( + newTimestamp, + uploadedIds) { + + FfiConverterInt64.checkType(newTimestamp); + FfiConverterSequenceTypeTabsGuid.checkType(uploadedIds); + const result = await UniFFIScaffolding.callAsyncWrapper( + 75, // uniffi_tabs_fn_method_tabsbridgedengine_set_uploaded + FfiConverterTypeTabsBridgedEngine.lower(this), + FfiConverterInt64.lower(newTimestamp), + FfiConverterSequenceTypeTabsGuid.lower(uploadedIds), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * storeIncoming + */ + async storeIncoming( + incomingEnvelopesAsJson) { + + FfiConverterSequenceString.checkType(incomingEnvelopesAsJson); + const result = await UniFFIScaffolding.callAsyncWrapper( + 76, // uniffi_tabs_fn_method_tabsbridgedengine_store_incoming + FfiConverterTypeTabsBridgedEngine.lower(this), + FfiConverterSequenceString.lower(incomingEnvelopesAsJson), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * syncFinished + */ + async syncFinished() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 77, // uniffi_tabs_fn_method_tabsbridgedengine_sync_finished + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * syncId + */ + async syncId() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 78, // uniffi_tabs_fn_method_tabsbridgedengine_sync_id + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterOptionalString.lift.bind(FfiConverterOptionalString), + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * syncStarted + */ + async syncStarted() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 79, // uniffi_tabs_fn_method_tabsbridgedengine_sync_started + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + + /** + * wipe + */ + async wipe() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 80, // uniffi_tabs_fn_method_tabsbridgedengine_wipe + FfiConverterTypeTabsBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTabsApiError.lift.bind(FfiConverterTypeTabsApiError), + ) + } + +} // Export the FFIConverter object to make external types work. -export class FfiConverterTypeTabsGuid extends FfiConverter { - static lift(buf) { - return FfiConverterString.lift(buf); +export class FfiConverterTypeTabsBridgedEngine extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new TabsBridgedEngine(opts); } - - static lower(buf) { - return FfiConverterString.lower(buf); + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'TabsBridgedEngine' instance"); + } + return ptr; } - + + static read(dataStream) { + return this.lift(dataStream.readPointer(10)); + } + static write(dataStream, value) { - FfiConverterString.write(dataStream, value); - } - - static read(buf) { - return FfiConverterString.read(buf); + dataStream.writePointer(10, this.lower(value)); } - + static computeSize(value) { - return FfiConverterString.computeSize(value); + return 8; } } -// TODO: We should also allow JS to customize the type eventually. - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeTimestamp extends FfiConverter { - static lift(buf) { - return FfiConverterI64.lift(buf); +export class FfiConverterSequenceTypeClientRemoteTabs extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeClientRemoteTabs.read(dataStream)); + } + return arr; } - - static lower(buf) { - return FfiConverterI64.lower(buf); - } - + static write(dataStream, value) { - FfiConverterI64.write(dataStream, value); - } - - static read(buf) { - return FfiConverterI64.read(buf); + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeClientRemoteTabs.write(dataStream, innerValue); + }) } - + static computeSize(value) { - return FfiConverterI64.computeSize(value); + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeClientRemoteTabs.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeClientRemoteTabs.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) } } -// TODO: We should also allow JS to customize the type eventually. +/** + * TabsStore + */ +export class TabsStore { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static async init( + path) { + + FfiConverterString.checkType(path); + const result = await UniFFIScaffolding.callAsyncWrapper( + 81, // uniffi_tabs_fn_constructor_tabsstore_new + FfiConverterString.lower(path), + ) + return handleRustResult( + result, + FfiConverterTypeTabsStore.lift.bind(FfiConverterTypeTabsStore), + null, + ) + } -import { - FfiConverterTypeDeviceType, - DeviceType, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSync15.sys.mjs"; + /** + * bridgedEngine + */ + async bridgedEngine() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 82, // uniffi_tabs_fn_method_tabsstore_bridged_engine + FfiConverterTypeTabsStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeTabsBridgedEngine.lift.bind(FfiConverterTypeTabsBridgedEngine), + null, + ) + } + + /** + * closeConnection + */ + async closeConnection() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 83, // uniffi_tabs_fn_method_tabsstore_close_connection + FfiConverterTypeTabsStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + + /** + * getAll + */ + async getAll() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 84, // uniffi_tabs_fn_method_tabsstore_get_all + FfiConverterTypeTabsStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterSequenceTypeClientRemoteTabs.lift.bind(FfiConverterSequenceTypeClientRemoteTabs), + null, + ) + } + + /** + * newRemoteCommandStore + */ + async newRemoteCommandStore() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 85, // uniffi_tabs_fn_method_tabsstore_new_remote_command_store + FfiConverterTypeTabsStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeRemoteCommandStore.lift.bind(FfiConverterTypeRemoteCommandStore), + null, + ) + } + + /** + * registerWithSyncManager + */ + async registerWithSyncManager() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 86, // uniffi_tabs_fn_method_tabsstore_register_with_sync_manager + FfiConverterTypeTabsStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + + /** + * setLocalTabs + */ + async setLocalTabs( + remoteTabs) { + + FfiConverterSequenceTypeRemoteTabRecord.checkType(remoteTabs); + const result = await UniFFIScaffolding.callAsyncWrapper( + 87, // uniffi_tabs_fn_method_tabsstore_set_local_tabs + FfiConverterTypeTabsStore.lower(this), + FfiConverterSequenceTypeRemoteTabRecord.lower(remoteTabs), + ) + return handleRustResult( + result, + (result) => undefined, + null, + ) + } + +} // Export the FFIConverter object to make external types work. -export { FfiConverterTypeDeviceType, DeviceType }; +export class FfiConverterTypeTabsStore extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new TabsStore(opts); + } + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'TabsStore' instance"); + } + return ptr; + } + static read(dataStream) { + return this.lift(dataStream.readPointer(11)); + } + + static write(dataStream, value) { + dataStream.writePointer(11, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustWebextstorage.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustWebextstorage.sys.mjs index aba8299ab166..604b13dd9dee 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustWebextstorage.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustWebextstorage.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,45 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a WebExtStorageBridgedEngine pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerWebExtStorageBridgedEngine() { - const pointerId = 11; // webextstorage:WebExtStorageBridgedEngine + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a WebExtStorageBridgedEngine pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerWebExtStorageBridgedEngine(value) { - const pointerId = 11; // webextstorage:WebExtStorageBridgedEngine + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - - - // Reads a WebExtStorageStore pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerWebExtStorageStore() { - const pointerId = 12; // webextstorage:WebExtStorageStore - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a WebExtStorageStore pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerWebExtStorageStore(value) { - const pointerId = 12; // webextstorage:WebExtStorageStore - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -308,59 +283,6 @@ const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; -// Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint64(value) - } - static read(dataStream) { - return dataStream.readUint64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt64(value) - } - static read(dataStream) { - return dataStream.readInt64() - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterString extends FfiConverter { static checkType(value) { @@ -390,739 +312,81 @@ export class FfiConverterString extends FfiConverter { return 4 + lazy.encoder.encode(value).length } } - -/** - * WebExtStorageBridgedEngine - */ -export class WebExtStorageBridgedEngine { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * apply - * @returns {Array.} - */ - apply() { - const liftResult = (result) => FfiConverterSequencestring.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 87, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_apply - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * ensureCurrentSyncId - * @returns {string} - */ - ensureCurrentSyncId(newSyncId) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(newSyncId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("newSyncId"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 88, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_ensure_current_sync_id - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - FfiConverterString.lower(newSyncId), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * lastSync - * @returns {number} - */ - lastSync() { - const liftResult = (result) => FfiConverterI64.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 89, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_last_sync - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * prepareForSync - */ - prepareForSync(clientData) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(clientData) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("clientData"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 90, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_prepare_for_sync - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - FfiConverterString.lower(clientData), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * reset - */ - reset() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 91, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_reset - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * resetSyncId - * @returns {string} - */ - resetSyncId() { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 92, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_reset_sync_id - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * setLastSync - */ - setLastSync(lastSync) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterI64.checkType(lastSync) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("lastSync"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 93, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_set_last_sync - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - FfiConverterI64.lower(lastSync), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * setUploaded - */ - setUploaded(serverModifiedMillis,guids) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterI64.checkType(serverModifiedMillis) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("serverModifiedMillis"); - } - throw e; - } - try { - FfiConverterSequenceTypeGuid.checkType(guids) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("guids"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 94, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_set_uploaded - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - FfiConverterI64.lower(serverModifiedMillis), - FfiConverterSequenceTypeGuid.lower(guids), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * storeIncoming - */ - storeIncoming(incoming) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterSequencestring.checkType(incoming) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("incoming"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 95, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_store_incoming - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - FfiConverterSequencestring.lower(incoming), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * syncFinished - */ - syncFinished() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 96, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_finished - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * syncId - * @returns {?string} - */ - syncId() { - const liftResult = (result) => FfiConverterOptionalstring.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 97, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_id - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * syncStarted - */ - syncStarted() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 98, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_started - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * wipe - */ - wipe() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 99, // webextstorage:uniffi_webext_storage_fn_method_webextstoragebridgedengine_wipe - FfiConverterTypeWebExtStorageBridgedEngine.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeWebExtStorageBridgedEngine extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new WebExtStorageBridgedEngine(opts); +export class FfiConverterTypeJsonValue extends FfiConverter { + static lift(buf) { + return FfiConverterString.lift(buf); } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'WebExtStorageBridgedEngine' instance"); - } - return ptr; + + static lower(buf) { + return FfiConverterString.lower(buf); } - - static read(dataStream) { - return this.lift(dataStream.readPointerWebExtStorageBridgedEngine()); - } - + static write(dataStream, value) { - dataStream.writePointerWebExtStorageBridgedEngine(value[uniffiObjectPtr]); + FfiConverterString.write(dataStream, value); + } + + static read(buf) { + return FfiConverterString.read(buf); } - + static computeSize(value) { - return 8; + return FfiConverterString.computeSize(value); } } -/** - * WebExtStorageStore - */ -export class WebExtStorageStore { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {WebExtStorageStore} - */ - static init(path) { - const liftResult = (result) => FfiConverterTypeWebExtStorageStore.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(path) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("path"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 108, // webextstorage:uniffi_webext_storage_fn_constructor_webextstoragestore_new - FfiConverterString.lower(path), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * bridgedEngine - * @returns {WebExtStorageBridgedEngine} - */ - bridgedEngine() { - const liftResult = (result) => FfiConverterTypeWebExtStorageBridgedEngine.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 100, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_bridged_engine - FfiConverterTypeWebExtStorageStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * clear - * @returns {StorageChanges} - */ - clear(extId) { - const liftResult = (result) => FfiConverterTypeStorageChanges.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(extId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("extId"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 101, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_clear - FfiConverterTypeWebExtStorageStore.lower(this), - FfiConverterString.lower(extId), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * close - */ - close() { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 102, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_close - FfiConverterTypeWebExtStorageStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * get - * @returns {JsonValue} - */ - get(extId,keys) { - const liftResult = (result) => FfiConverterTypeJsonValue.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(extId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("extId"); - } - throw e; - } - try { - FfiConverterTypeJsonValue.checkType(keys) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("keys"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 103, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_get - FfiConverterTypeWebExtStorageStore.lower(this), - FfiConverterString.lower(extId), - FfiConverterTypeJsonValue.lower(keys), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getBytesInUse - * @returns {number} - */ - getBytesInUse(extId,keys) { - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(extId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("extId"); - } - throw e; - } - try { - FfiConverterTypeJsonValue.checkType(keys) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("keys"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 104, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_get_bytes_in_use - FfiConverterTypeWebExtStorageStore.lower(this), - FfiConverterString.lower(extId), - FfiConverterTypeJsonValue.lower(keys), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getSyncedChanges - * @returns {Array.} - */ - getSyncedChanges() { - const liftResult = (result) => FfiConverterSequenceTypeSyncedExtensionChange.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 105, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_get_synced_changes - FfiConverterTypeWebExtStorageStore.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * remove - * @returns {StorageChanges} - */ - remove(extId,keys) { - const liftResult = (result) => FfiConverterTypeStorageChanges.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(extId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("extId"); - } - throw e; - } - try { - FfiConverterTypeJsonValue.checkType(keys) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("keys"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 106, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_remove - FfiConverterTypeWebExtStorageStore.lower(this), - FfiConverterString.lower(extId), - FfiConverterTypeJsonValue.lower(keys), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * set - * @returns {StorageChanges} - */ - set(extId,val) { - const liftResult = (result) => FfiConverterTypeStorageChanges.lift(result); - const liftError = (data) => FfiConverterTypeWebExtStorageApiError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(extId) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("extId"); - } - throw e; - } - try { - FfiConverterTypeJsonValue.checkType(val) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("val"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 107, // webextstorage:uniffi_webext_storage_fn_method_webextstoragestore_set - FfiConverterTypeWebExtStorageStore.lower(this), - FfiConverterString.lower(extId), - FfiConverterTypeJsonValue.lower(val), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - +// TODO: We should also allow JS to customize the type eventually. // Export the FFIConverter object to make external types work. -export class FfiConverterTypeWebExtStorageStore extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new WebExtStorageStore(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'WebExtStorageStore' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerWebExtStorageStore()); - } - - static write(dataStream, value) { - dataStream.writePointerWebExtStorageStore(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * StorageChanges - */ -export class StorageChanges { - constructor({ changes } = { changes: undefined }) { - try { - FfiConverterSequenceTypeStorageValueChange.checkType(changes) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("changes"); - } - throw e; - } - /** - * @type {Array.} - */ - this.changes = changes; - } - - equals(other) { - return ( - this.changes == other.changes - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeStorageChanges extends FfiConverterArrayBuffer { - static read(dataStream) { - return new StorageChanges({ - changes: FfiConverterSequenceTypeStorageValueChange.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterSequenceTypeStorageValueChange.write(dataStream, value.changes); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterSequenceTypeStorageValueChange.computeSize(value.changes); - return totalSize - } - +export class FfiConverterOptionalTypeJsonValue extends FfiConverterArrayBuffer { static checkType(value) { - super.checkType(value); - if (!(value instanceof StorageChanges)) { - throw new UniFFITypeError(`Expected 'StorageChanges', found '${typeof value}'`); - } - try { - FfiConverterSequenceTypeStorageValueChange.checkType(value.changes); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".changes"); - } - throw e; + if (value !== undefined && value !== null) { + FfiConverterTypeJsonValue.checkType(value) } } -} + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterTypeJsonValue.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterTypeJsonValue.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterTypeJsonValue.computeSize(value) + } +} /** * StorageValueChange */ export class StorageValueChange { - constructor({ key, oldValue, newValue } = { key: undefined, oldValue: undefined, newValue: undefined }) { + constructor( + { + key, + oldValue, + newValue + } = { + key: undefined, + oldValue: undefined, + newValue: undefined + } + ) { try { FfiConverterString.checkType(key) } catch (e) { @@ -1148,24 +412,24 @@ export class StorageValueChange { throw e; } /** - * @type {string} + * key */ this.key = key; /** - * @type {?JsonValue} + * oldValue */ this.oldValue = oldValue; /** - * @type {?JsonValue} + * newValue */ this.newValue = newValue; } equals(other) { return ( - this.key == other.key && - this.oldValue == other.oldValue && - this.newValue == other.newValue + this.key == other.key + && this.oldValue == other.oldValue + && this.newValue == other.newValue ) } } @@ -1224,12 +488,126 @@ export class FfiConverterTypeStorageValueChange extends FfiConverterArrayBuffer } } } +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeStorageValueChange extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeStorageValueChange.read(dataStream)); + } + return arr; + } + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeStorageValueChange.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeStorageValueChange.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeStorageValueChange.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +/** + * StorageChanges + */ +export class StorageChanges { + constructor( + { + changes + } = { + changes: undefined + } + ) { + try { + FfiConverterSequenceTypeStorageValueChange.checkType(changes) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("changes"); + } + throw e; + } + /** + * changes + */ + this.changes = changes; + } + + equals(other) { + return ( + this.changes == other.changes + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeStorageChanges extends FfiConverterArrayBuffer { + static read(dataStream) { + return new StorageChanges({ + changes: FfiConverterSequenceTypeStorageValueChange.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterSequenceTypeStorageValueChange.write(dataStream, value.changes); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterSequenceTypeStorageValueChange.computeSize(value.changes); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof StorageChanges)) { + throw new UniFFITypeError(`Expected 'StorageChanges', found '${typeof value}'`); + } + try { + FfiConverterSequenceTypeStorageValueChange.checkType(value.changes); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".changes"); + } + throw e; + } + } +} /** * SyncedExtensionChange */ export class SyncedExtensionChange { - constructor({ extId, changes } = { extId: undefined, changes: undefined }) { + constructor( + { + extId, + changes + } = { + extId: undefined, + changes: undefined + } + ) { try { FfiConverterString.checkType(extId) } catch (e) { @@ -1247,19 +625,19 @@ export class SyncedExtensionChange { throw e; } /** - * @type {string} + * extId */ this.extId = extId; /** - * @type {string} + * changes */ this.changes = changes; } equals(other) { return ( - this.extId == other.extId && - this.changes == other.changes + this.extId == other.extId + && this.changes == other.changes ) } } @@ -1308,7 +686,6 @@ export class FfiConverterTypeSyncedExtensionChange extends FfiConverterArrayBuff } } - /** * QuotaReason */ @@ -1316,24 +693,21 @@ export const QuotaReason = { /** * TOTAL_BYTES */ - TOTAL_BYTES:0, + TOTAL_BYTES: 1, /** * ITEM_BYTES */ - ITEM_BYTES:1, + ITEM_BYTES: 2, /** * MAX_ITEMS */ - MAX_ITEMS:2, + MAX_ITEMS: 3, }; - Object.freeze(QuotaReason); + // Export the FFIConverter object to make external types work. export class FfiConverterTypeQuotaReason extends FfiConverterArrayBuffer { - static #validValues = Object.values(QuotaReason); - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { case 1: return QuotaReason.TOTAL_BYTES @@ -1367,17 +741,12 @@ export class FfiConverterTypeQuotaReason extends FfiConverterArrayBuffer { } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { + if (!Number.isInteger(value) || value < 1 || value > 3) { throw new UniFFITypeError(`${value} is not a valid value for QuotaReason`); } } } - - - - /** * WebExtStorageApiError */ @@ -1496,83 +865,32 @@ export class FfiConverterTypeWebExtStorageApiError extends FfiConverterArrayBuff static errorClass = WebExtStorageApiError; } - // Export the FFIConverter object to make external types work. -export class FfiConverterOptionalstring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterString.checkType(value) - } +export class FfiConverterTypeGuid extends FfiConverter { + static lift(buf) { + return FfiConverterString.lift(buf); } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } + + static lower(buf) { + return FfiConverterString.lower(buf); } - + static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterString.write(dataStream, value) + FfiConverterString.write(dataStream, value); + } + + static read(buf) { + return FfiConverterString.read(buf); } - + static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterString.computeSize(value) + return FfiConverterString.computeSize(value); } } +// TODO: We should also allow JS to customize the type eventually. // Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeJsonValue extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeJsonValue.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeJsonValue.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeJsonValue.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeJsonValue.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { +export class FfiConverterSequenceString extends FfiConverterArrayBuffer { static read(dataStream) { const len = dataStream.readInt32(); const arr = []; @@ -1614,95 +932,30 @@ export class FfiConverterSequencestring extends FfiConverterArrayBuffer { }) } } - // Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeStorageValueChange extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeStorageValueChange.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeStorageValueChange.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeStorageValueChange.computeSize(innerValue); - } - return size; - } - +export class FfiConverterInt64 extends FfiConverter { static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeStorageValueChange.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt64(value) + } + static read(dataStream) { + return dataStream.readInt64() } } - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeSyncedExtensionChange extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeSyncedExtensionChange.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeSyncedExtensionChange.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeSyncedExtensionChange.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeSyncedExtensionChange.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - // Export the FFIConverter object to make external types work. export class FfiConverterSequenceTypeGuid extends FfiConverterArrayBuffer { static read(dataStream) { @@ -1746,55 +999,626 @@ export class FfiConverterSequenceTypeGuid extends FfiConverterArrayBuffer { }) } } - // Export the FFIConverter object to make external types work. -export class FfiConverterTypeGuid extends FfiConverter { - static lift(buf) { - return FfiConverterString.lift(buf); +export class FfiConverterOptionalString extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterString.checkType(value) + } } - - static lower(buf) { - return FfiConverterString.lower(buf); + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterString.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } } - + static write(dataStream, value) { - FfiConverterString.write(dataStream, value); - } - - static read(buf) { - return FfiConverterString.read(buf); + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterString.write(dataStream, value) } - + static computeSize(value) { - return FfiConverterString.computeSize(value); + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterString.computeSize(value) } } -// TODO: We should also allow JS to customize the type eventually. +/** + * WebExtStorageBridgedEngine + */ +export class WebExtStorageBridgedEngine { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + /** + * apply + */ + async apply() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 88, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_apply + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterSequenceString.lift.bind(FfiConverterSequenceString), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * ensureCurrentSyncId + */ + async ensureCurrentSyncId( + newSyncId) { + + FfiConverterString.checkType(newSyncId); + const result = await UniFFIScaffolding.callAsyncWrapper( + 89, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_ensure_current_sync_id + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + FfiConverterString.lower(newSyncId), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * lastSync + */ + async lastSync() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 90, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_last_sync + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterInt64.lift.bind(FfiConverterInt64), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * prepareForSync + */ + async prepareForSync( + clientData) { + + FfiConverterString.checkType(clientData); + const result = await UniFFIScaffolding.callAsyncWrapper( + 91, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_prepare_for_sync + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + FfiConverterString.lower(clientData), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * reset + */ + async reset() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 92, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_reset + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * resetSyncId + */ + async resetSyncId() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 93, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_reset_sync_id + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * setLastSync + */ + async setLastSync( + lastSync) { + + FfiConverterInt64.checkType(lastSync); + const result = await UniFFIScaffolding.callAsyncWrapper( + 94, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_set_last_sync + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + FfiConverterInt64.lower(lastSync), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * setUploaded + */ + async setUploaded( + serverModifiedMillis, + guids) { + + FfiConverterInt64.checkType(serverModifiedMillis); + FfiConverterSequenceTypeGuid.checkType(guids); + const result = await UniFFIScaffolding.callAsyncWrapper( + 95, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_set_uploaded + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + FfiConverterInt64.lower(serverModifiedMillis), + FfiConverterSequenceTypeGuid.lower(guids), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * storeIncoming + */ + async storeIncoming( + incoming) { + + FfiConverterSequenceString.checkType(incoming); + const result = await UniFFIScaffolding.callAsyncWrapper( + 96, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_store_incoming + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + FfiConverterSequenceString.lower(incoming), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * syncFinished + */ + async syncFinished() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 97, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_finished + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * syncId + */ + async syncId() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 98, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_id + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + FfiConverterOptionalString.lift.bind(FfiConverterOptionalString), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * syncStarted + */ + async syncStarted() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 99, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_started + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * wipe + */ + async wipe() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 100, // uniffi_webext_storage_fn_method_webextstoragebridgedengine_wipe + FfiConverterTypeWebExtStorageBridgedEngine.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + +} // Export the FFIConverter object to make external types work. -export class FfiConverterTypeJsonValue extends FfiConverter { - static lift(buf) { - return FfiConverterString.lift(buf); +export class FfiConverterTypeWebExtStorageBridgedEngine extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new WebExtStorageBridgedEngine(opts); } - - static lower(buf) { - return FfiConverterString.lower(buf); + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'WebExtStorageBridgedEngine' instance"); + } + return ptr; } - + + static read(dataStream) { + return this.lift(dataStream.readPointer(12)); + } + static write(dataStream, value) { - FfiConverterString.write(dataStream, value); - } - - static read(buf) { - return FfiConverterString.read(buf); + dataStream.writePointer(12, this.lower(value)); } - + static computeSize(value) { - return FfiConverterString.computeSize(value); + return 8; } } -// TODO: We should also allow JS to customize the type eventually. +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); + } + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint64(value) + } + static read(dataStream) { + return dataStream.readUint64() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceTypeSyncedExtensionChange extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterTypeSyncedExtensionChange.read(dataStream)); + } + return arr; + } + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterTypeSyncedExtensionChange.write(dataStream, innerValue); + }) + } + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterTypeSyncedExtensionChange.computeSize(innerValue); + } + return size; + } + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterTypeSyncedExtensionChange.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +/** + * WebExtStorageStore + */ +export class WebExtStorageStore { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static async init( + path) { + + FfiConverterString.checkType(path); + const result = await UniFFIScaffolding.callAsyncWrapper( + 101, // uniffi_webext_storage_fn_constructor_webextstoragestore_new + FfiConverterString.lower(path), + ) + return handleRustResult( + result, + FfiConverterTypeWebExtStorageStore.lift.bind(FfiConverterTypeWebExtStorageStore), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + /** + * bridgedEngine + */ + async bridgedEngine() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 102, // uniffi_webext_storage_fn_method_webextstoragestore_bridged_engine + FfiConverterTypeWebExtStorageStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterTypeWebExtStorageBridgedEngine.lift.bind(FfiConverterTypeWebExtStorageBridgedEngine), + null, + ) + } + + /** + * clear + */ + async clear( + extId) { + + FfiConverterString.checkType(extId); + const result = await UniFFIScaffolding.callAsyncWrapper( + 103, // uniffi_webext_storage_fn_method_webextstoragestore_clear + FfiConverterTypeWebExtStorageStore.lower(this), + FfiConverterString.lower(extId), + ) + return handleRustResult( + result, + FfiConverterTypeStorageChanges.lift.bind(FfiConverterTypeStorageChanges), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * close + */ + async close() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 104, // uniffi_webext_storage_fn_method_webextstoragestore_close + FfiConverterTypeWebExtStorageStore.lower(this), + ) + return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * get + */ + async get( + extId, + keys) { + + FfiConverterString.checkType(extId); + FfiConverterTypeJsonValue.checkType(keys); + const result = await UniFFIScaffolding.callAsyncWrapper( + 105, // uniffi_webext_storage_fn_method_webextstoragestore_get + FfiConverterTypeWebExtStorageStore.lower(this), + FfiConverterString.lower(extId), + FfiConverterTypeJsonValue.lower(keys), + ) + return handleRustResult( + result, + FfiConverterTypeJsonValue.lift.bind(FfiConverterTypeJsonValue), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * getBytesInUse + */ + async getBytesInUse( + extId, + keys) { + + FfiConverterString.checkType(extId); + FfiConverterTypeJsonValue.checkType(keys); + const result = await UniFFIScaffolding.callAsyncWrapper( + 106, // uniffi_webext_storage_fn_method_webextstoragestore_get_bytes_in_use + FfiConverterTypeWebExtStorageStore.lower(this), + FfiConverterString.lower(extId), + FfiConverterTypeJsonValue.lower(keys), + ) + return handleRustResult( + result, + FfiConverterUInt64.lift.bind(FfiConverterUInt64), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * getSyncedChanges + */ + async getSyncedChanges() { + + const result = await UniFFIScaffolding.callAsyncWrapper( + 107, // uniffi_webext_storage_fn_method_webextstoragestore_get_synced_changes + FfiConverterTypeWebExtStorageStore.lower(this), + ) + return handleRustResult( + result, + FfiConverterSequenceTypeSyncedExtensionChange.lift.bind(FfiConverterSequenceTypeSyncedExtensionChange), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * remove + */ + async remove( + extId, + keys) { + + FfiConverterString.checkType(extId); + FfiConverterTypeJsonValue.checkType(keys); + const result = await UniFFIScaffolding.callAsyncWrapper( + 108, // uniffi_webext_storage_fn_method_webextstoragestore_remove + FfiConverterTypeWebExtStorageStore.lower(this), + FfiConverterString.lower(extId), + FfiConverterTypeJsonValue.lower(keys), + ) + return handleRustResult( + result, + FfiConverterTypeStorageChanges.lift.bind(FfiConverterTypeStorageChanges), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + + /** + * set + */ + async set( + extId, + val) { + + FfiConverterString.checkType(extId); + FfiConverterTypeJsonValue.checkType(val); + const result = await UniFFIScaffolding.callAsyncWrapper( + 109, // uniffi_webext_storage_fn_method_webextstoragestore_set + FfiConverterTypeWebExtStorageStore.lower(this), + FfiConverterString.lower(extId), + FfiConverterTypeJsonValue.lower(val), + ) + return handleRustResult( + result, + FfiConverterTypeStorageChanges.lift.bind(FfiConverterTypeStorageChanges), + FfiConverterTypeWebExtStorageApiError.lift.bind(FfiConverterTypeWebExtStorageApiError), + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeWebExtStorageStore extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new WebExtStorageStore(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'WebExtStorageStore' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(13)); + } + + static write(dataStream, value) { + dataStream.writePointer(13, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/config.toml b/toolkit/components/uniffi-bindgen-gecko-js/config.toml index 0b2bf0c934f0..dcbbe9e71960 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/config.toml +++ b/toolkit/components/uniffi-bindgen-gecko-js/config.toml @@ -75,29 +75,45 @@ enable = true [webext_storage.async_wrappers] enable = true -[arithmetical.async_wrappers] -enable = true - -[uniffi_custom_types.async_wrappers] -enable = true - -[uniffi_fixture_callbacks.async_wrappers] +[uniffi_bindings_tests.async_wrappers] enable = true main_thread = [ - "log_even_numbers_main_thread", + "clone_interface", + "func_with_default", + "func_with_error", + "func_with_flat_error", + "func_roundtrip_custom_type", + "swap_test_interfaces", + "invoke_test_callback_interface_method", + "roundtrip_u8", + "roundtrip_i8", + "roundtrip_u16", + "roundtrip_i16", + "roundtrip_u32", + "roundtrip_i32", + "roundtrip_u64", + "roundtrip_i64", + "roundtrip_f32", + "roundtrip_f64", + "roundtrip_bool", + "roundtrip_custom_type", + "roundtrip_string", + "sum_with_many_types", + "test_func", + "func_with_multi_word_arg", + "roundtrip_option", + "roundtrip_vec", + "roundtrip_hash_map", + "roundtrip_complex_compound", + "roundtrip_complex_rec", + "roundtrip_enum_no_data", + "roundtrip_enum_with_data", + "roundtrip_complex_enum", + "AsyncInterface.new", + "ComplexMethods.method_with_default", + "ComplexMethods.method_with_multi_word_arg", + "ComplexMethods.new", + "TestInterface.new", + "TestInterface.get_value", + "TestInterface.ref_count", ] - -[uniffi_fixture_external_types.async_wrappers] -enable = true - -[uniffi_geometry.async_wrappers] -enable = true - -[uniffi_rondpoint.async_wrappers] -enable = true - -[uniffi_sprites.async_wrappers] -enable = true - -[uniffi_todolist.async_wrappers] -enable = true diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/Cargo.toml deleted file mode 100644 index 1ef89ff94280..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/Cargo.toml +++ /dev/null @@ -1,34 +0,0 @@ -[package] -edition = "2015" -name = "gkrust-uniffi-fixtures" -version = "0.1.0" -authors = ["The Mozilla Project Developers"] -license = "MPL-2.0" -description = "UniFFI-enabled Rust components for libxul" - -[lib] -crate-type = ["rlib", "staticlib"] -path = "lib.rs" -test = false -doctest = false -bench = false -doc = false -harness = false - -[dependencies] -uniffi = { workspace = true } -uniffi-example-arithmetic = { path = "arithmetic/" } -uniffi-example-geometry = { path = "geometry/" } -uniffi-example-rondpoint = { path = "rondpoint/" } -uniffi-example-sprites = { path = "sprites/" } -uniffi-example-todolist = { path = "todolist/" } -uniffi-example-custom-types = { path = "custom-types/" } -uniffi-fixture-callbacks = { path = "callbacks/" } -uniffi-fixture-external-types = { path = "external-types/" } -uniffi-fixture-futures = { path = "futures/" } -uniffi-fixture-refcounts = { path = "refcounts/" } -uniffi-trait-interfaces = { path = "trait-interfaces/" } - -[features] -# Should we depend on xpcom crates? -xpcom = ["uniffi-fixture-futures/moz_task"] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/README.md b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/README.md deleted file mode 100644 index 632ba88e006f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/README.md +++ /dev/null @@ -1,36 +0,0 @@ -This directory contains generated code for the UniFFI examples/fixtures and JS -unit tests for it. - -This is only built if the `--enable-uniffi-fixtures` flag is present in -`mozconfig`. There's no benefit to including this in a release build. - -To add additional examples/fixtures: - - For most of these steps, find the code for existing fixtures and use it as a template for the new code. - - Edit `toolkit/components/uniffi-bindgen-gecko-js/mach_commands.py` - - Add an entry to `FIXTURE_UDL_FILES` - - Edit `toolkit/library/rust/shared/Cargo.toml` - - Add an optional dependency for the fixture. - - Add the feature to the list of features enabled by `uniffi_fixtures`. - - Edit `toolkit/library/rust/shared/lib.rs`: - - Add an `extern crate [name]` to the `uniffi_fixtures` mod - - Note: [name] is the name from the `[lib]` section in the Cargo.toml - for the example/fixture crate. This does not always match the package - name for the crate. - - Add `[name]::reexport_uniffi_scaffolding` to the `uniffi_fixtures` mod - - Edit `toolkit/components/uniffi-bindgen-gecko-js/fixtures/moz.build` and add the fixture name to the `components` - list. - - Add a test module to the `toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/` directory and an entry for it - in `toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell.ini` - - Run `mach vendor rust` to vendor in the Rust code. - - Run `mach uniffi generate` to generate the scaffolding code. - - Check in any new files - -To run the tests: - - Make sure you have a `mozconfig` file containing the line `ac_add_options --enable-uniffi-fixtures` - - Run `mach uniffi generate` if: - - You've added or updated a fixture - - You've made changes to `uniffi-bindgen-gecko-js` - - Run `mach build` - - Run `mach xpcshell-test toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/` - - You can also use a path to specific test file - - For subsequent runs, if you only modify the test files, then you can re-run this step directly diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/Cargo.toml deleted file mode 100644 index b497b8cccc8b..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "uniffi-example-arithmetic" -edition = "2021" -version = "0.22.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "arithmetical" - -[dependencies] -uniffi = { workspace = true } -thiserror = "1.0" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/src/arithmetic.udl b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/src/arithmetic.udl deleted file mode 100644 index 117df4834aa4..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/src/arithmetic.udl +++ /dev/null @@ -1,16 +0,0 @@ -[Error] -enum ArithmeticError { - "IntegerOverflow", -}; - -namespace arithmetic { - [Throws=ArithmeticError] - u64 add(u64 a, u64 b); - - [Throws=ArithmeticError] - u64 sub(u64 a, u64 b); - - u64 div(u64 dividend, u64 divisor); - - boolean equal(u64 a, u64 b); -}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/src/lib.rs deleted file mode 100644 index 92ab8c072bd1..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/src/lib.rs +++ /dev/null @@ -1,34 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[derive(Debug, thiserror::Error)] -pub enum ArithmeticError { - #[error("Integer overflow on an operation with {a} and {b}")] - IntegerOverflow { a: u64, b: u64 }, -} - -fn add(a: u64, b: u64) -> Result { - a.checked_add(b) - .ok_or(ArithmeticError::IntegerOverflow { a, b }) -} - -fn sub(a: u64, b: u64) -> Result { - a.checked_sub(b) - .ok_or(ArithmeticError::IntegerOverflow { a, b }) -} - -fn div(dividend: u64, divisor: u64) -> u64 { - if divisor == 0 { - panic!("Can't divide by zero"); - } - dividend / divisor -} - -fn equal(a: u64, b: u64) -> bool { - a == b -} - -type Result = std::result::Result; - -uniffi::include_scaffolding!("arithmetic"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.kts b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.kts deleted file mode 100644 index ef11850ae23f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.kts +++ /dev/null @@ -1,29 +0,0 @@ -import org.mozilla.uniffi.example.arithmetic.*; - -assert(add(2u, 4u) == 6uL) -assert(add(4u, 8u) == 12uL) - -try { - sub(0u, 2u) - throw RuntimeException("Should have thrown a IntegerOverflow exception!") -} catch (e: ArithmeticException) { - // It's okay! -} - -assert(sub(4u, 2u) == 2uL) -assert(sub(8u, 4u) == 4uL) - -assert(div(8u, 4u) == 2uL) - -try { - div(8u, 0u) - throw RuntimeException("Should have panicked when dividing by zero") -} catch (e: InternalException) { - // It's okay! -} - -assert(equal(2u, 2uL)) -assert(equal(4u, 4uL)) - -assert(!equal(2u, 4uL)) -assert(!equal(4u, 8uL)) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.py b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.py deleted file mode 100644 index e1b4f7127748..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.py +++ /dev/null @@ -1,37 +0,0 @@ -from arithmetic import InternalError, add, div, equal, sub - -try: - add(18446744073709551615, 1) - assert not ("Should have thrown a IntegerOverflow exception!") -except ArithmeticError.IntegerOverflow: - # It's okay! - pass - -assert add(2, 4) == 6 -assert add(4, 8) == 12 - -try: - sub(0, 1) - assert not ("Should have thrown a IntegerOverflow exception!") -except ArithmeticError.IntegerOverflow: - # It's okay! - pass - -assert sub(4, 2) == 2 -assert sub(8, 4) == 4 - -assert div(8, 4) == 2 - -try: - div(8, 0) -except InternalError: - # It's okay! - pass -else: - assert not ("Should have panicked when dividing by zero") - -assert equal(2, 2) -assert equal(4, 4) - -assert not equal(2, 4) -assert not equal(4, 8) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.rb b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.rb deleted file mode 100644 index 6669eb279f28..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.rb +++ /dev/null @@ -1,31 +0,0 @@ -# frozen_string_literal: true - -require 'test/unit' -require 'arithmetic' - -include Test::Unit::Assertions - -assert_raise Arithmetic::ArithmeticError::IntegerOverflow do - Arithmetic.add 18_446_744_073_709_551_615, 1 -end - -assert_equal Arithmetic.add(2, 4), 6 -assert_equal Arithmetic.add(4, 8), 12 - -assert_raise Arithmetic::ArithmeticError::IntegerOverflow do - Arithmetic.sub 0, 1 -end - -assert_equal Arithmetic.sub(4, 2), 2 -assert_equal Arithmetic.sub(8, 4), 4 -assert_equal Arithmetic.div(8, 4), 2 - -assert_raise Arithmetic::InternalError do - Arithmetic.div 8, 0 -end - -assert Arithmetic.equal(2, 2) -assert Arithmetic.equal(4, 4) - -assert !Arithmetic.equal(2, 4) -assert !Arithmetic.equal(4, 8) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.swift b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.swift deleted file mode 100644 index a8e34680e4f4..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/bindings/test_arithmetic.swift +++ /dev/null @@ -1,32 +0,0 @@ -import arithmetic - -do { - let _ = try add(a: 18446744073709551615, b: 1) - fatalError("Should have thrown a IntegerOverflow exception!") -} catch ArithmeticError.IntegerOverflow { - // It's okay! -} - -assert(try! add(a: 2, b: 4) == 6, "add work") -assert(try! add(a: 4, b: 8) == 12, "add work") - -do { - let _ = try sub(a: 0, b: 1) - fatalError("Should have thrown a IntegerOverflow exception!") -} catch ArithmeticError.IntegerOverflow { - // It's okay! -} - -assert(try! sub(a: 4, b: 2) == 2, "sub work") -assert(try! sub(a: 8, b: 4) == 4, "sub work") - -assert(div(dividend: 8, divisor: 4) == 2, "div works") - -// We can't test panicking in Swift because we force unwrap the error in -// `div`, which we can't catch. - -assert(equal(a: 2, b: 2), "equal works") -assert(equal(a: 4, b: 4), "equal works") - -assert(!equal(a: 2, b: 4), "non-equal works") -assert(!equal(a: 4, b: 8), "non-equal works") diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/test_generated_bindings.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/test_generated_bindings.rs deleted file mode 100644 index 168e6e1d4c32..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/tests/test_generated_bindings.rs +++ /dev/null @@ -1,6 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_arithmetic.rb", - "tests/bindings/test_arithmetic.py", - "tests/bindings/test_arithmetic.kts", - "tests/bindings/test_arithmetic.swift", -); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/uniffi.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/uniffi.toml deleted file mode 100644 index 883231dcaadb..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/uniffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -[bindings.kotlin] -package_name = "org.mozilla.uniffi.example.arithmetic" diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/callbacks/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/callbacks/Cargo.toml deleted file mode 100644 index 67b2b01b6585..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/callbacks/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "uniffi-fixture-callbacks" -edition = "2021" -version = "0.21.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[dependencies] -uniffi = { workspace = true } -thiserror = "1.0" diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/callbacks/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/callbacks/src/lib.rs deleted file mode 100644 index 1cf44cbcdbc8..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/callbacks/src/lib.rs +++ /dev/null @@ -1,35 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#[uniffi::export(callback_interface)] -pub trait Logger: Send + Sync { - fn log(&self, message: String); - // Log a message N times each prefixed with the current index, except when that index is one of - // the items in the exclude vec. The point here is to test sending a bunch of arguments at once - fn log_repeat(&self, message: String, count: u32, exclude: Vec); - fn finished(&self); -} - -#[uniffi::export] -fn log_even_numbers(logger: Box, items: Vec) { - for i in items { - if i % 2 == 0 { - logger.log(format!("Saw even number: {i}")) - } - } - logger.finished(); -} - -#[uniffi::export] -fn log_even_numbers_main_thread(logger: Box, items: Vec) { - log_even_numbers(logger, items) -} - -#[uniffi::export] -fn call_log_repeat(logger: Box, message: String, count: u32, exclude: Vec) { - logger.log_repeat(message, count, exclude); - logger.finished(); -} - -uniffi::setup_scaffolding!("fixture_callbacks"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/Cargo.toml deleted file mode 100644 index a05324952e06..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "uniffi-example-custom-types" -edition = "2021" -version = "0.19.6" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_custom_types" - -[dependencies] -anyhow = "1" -bytes = "1.0" -serde_json = "1" -uniffi = { workspace = true } -url = "2.4" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/build.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/build.rs deleted file mode 100644 index 10b6d220daad..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("./src/custom-types.udl").unwrap(); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/src/custom-types.udl b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/src/custom-types.udl deleted file mode 100644 index 19e1ab299c16..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/src/custom-types.udl +++ /dev/null @@ -1,28 +0,0 @@ -[Custom] -typedef string Url; - -[Custom] -typedef i64 Handle; - -dictionary CustomTypesDemo { - Url url; - Handle handle; -}; - -// Enum with sequential values (default) - only defined in UDL -enum SequentialEnum { - "First", - "Second", - "Fourth", - "Tenth", - "Eleventh", - "Thirteenth" -}; - -namespace custom_types { - CustomTypesDemo get_custom_types_demo(CustomTypesDemo? demo); - - // Functions for sequential enum (UDL-defined) - u8 get_sequential_discriminant(SequentialEnum value); - SequentialEnum echo_sequential_value(SequentialEnum value); -}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/src/lib.rs deleted file mode 100644 index a3345d78b367..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/src/lib.rs +++ /dev/null @@ -1,125 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::collections::HashMap; -use url::Url; - -// Custom Handle type which trivially wraps an i64. -pub struct Handle(pub i64); - -// We must implement the UniffiCustomTypeConverter trait for each custom type on the scaffolding side -uniffi::custom_type!(Handle, i64, { - try_lift: |val| Ok(Handle(val)), - lower: |obj| obj.0, -}); - -// Use `url::Url` as a custom type, with `String` as the Builtin -uniffi::custom_type!(Url, String, { - remote, - try_lift: |val| Ok(Url::parse(&val)?), - lower: |obj| obj.to_string(), -}); - -// And a little struct and function that ties them together. -pub struct CustomTypesDemo { - url: Url, - handle: Handle, -} - -// Define the enum that matches the UDL definition -// We don't need to derive uniffi::Enum for this one -#[derive(Debug, Clone, Copy)] -pub enum SequentialEnum { - First, - Second, - Fourth, - Tenth, - Eleventh, - Thirteenth, -} - -// Test enum with explicit discriminant values and gaps -#[repr(u8)] -#[derive(Debug, Clone, Copy, uniffi::Enum)] -pub enum ExplicitValuedEnum { - First = 1, - Second = 2, - Fourth = 4, - Tenth = 10, - Eleventh = 11, - Thirteenth = 13, -} - -// Example with sequential and explicit values mixed -#[repr(u8)] -#[derive(Debug, Clone, Copy, uniffi::Enum)] -pub enum GappedEnum { - One = 10, - Two, // should be 11 - Three = 14, -} - -pub fn get_custom_types_demo(v: Option) -> CustomTypesDemo { - v.unwrap_or_else(|| CustomTypesDemo { - url: Url::parse("http://example.com/").unwrap(), - handle: Handle(123), - }) -} - -// Functions for sequential enum (UDL-defined) -pub fn get_sequential_discriminant(value: SequentialEnum) -> u8 { - value as u8 -} - -pub fn echo_sequential_value(value: SequentialEnum) -> SequentialEnum { - value -} - -// Export proc-macro based enum to JS via scaffolding -#[uniffi::export] -pub fn get_explicit_enum_values() -> HashMap { - let mut values = HashMap::new(); - values.insert("First".to_string(), ExplicitValuedEnum::First as u8); - values.insert("Second".to_string(), ExplicitValuedEnum::Second as u8); - values.insert("Fourth".to_string(), ExplicitValuedEnum::Fourth as u8); - values.insert("Tenth".to_string(), ExplicitValuedEnum::Tenth as u8); - values.insert("Eleventh".to_string(), ExplicitValuedEnum::Eleventh as u8); - values.insert( - "Thirteenth".to_string(), - ExplicitValuedEnum::Thirteenth as u8, - ); - values -} - -#[uniffi::export] -pub fn get_explicit_discriminant(value: ExplicitValuedEnum) -> u8 { - value as u8 -} - -#[uniffi::export] -pub fn echo_explicit_value(value: ExplicitValuedEnum) -> ExplicitValuedEnum { - value -} - -// Functions for GappedEnum -#[uniffi::export] -pub fn get_gapped_enum_values() -> HashMap { - let mut values = HashMap::new(); - values.insert("One".to_string(), GappedEnum::One as u8); - values.insert("Two".to_string(), GappedEnum::Two as u8); - values.insert("Three".to_string(), GappedEnum::Three as u8); - values -} - -#[uniffi::export] -pub fn get_gapped_discriminant(value: GappedEnum) -> u8 { - value as u8 -} - -#[uniffi::export] -pub fn echo_gapped_value(value: GappedEnum) -> GappedEnum { - value -} - -include!(concat!(env!("OUT_DIR"), "/custom-types.uniffi.rs")); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/bindings/test_custom_types.kts b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/bindings/test_custom_types.kts deleted file mode 100644 index d75bd99eee28..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/bindings/test_custom_types.kts +++ /dev/null @@ -1,21 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import java.net.URL - -import customtypes.* - -// TODO: use an actual test runner. - -// Get the custom types and check their data -val demo = getCustomTypesDemo(null) -// URL is customized on the bindings side -assert(demo.url == URL("http://example.com/")) -// Handle isn't so it appears as a plain Long -assert(demo.handle == 123L) - -// Change some data and ensure that the round-trip works -demo.url = URL("http://new.example.com/") -demo.handle = 456; -assert(demo == getCustomTypesDemo(demo)) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/bindings/test_custom_types.swift b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/bindings/test_custom_types.swift deleted file mode 100644 index 5aaf6ff3b089..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/bindings/test_custom_types.swift +++ /dev/null @@ -1,20 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -import custom_types -import Foundation - -// TODO: use an actual test runner. - -do { - // Test simple values. - var demo = getCustomTypesDemo(demo: nil) - assert(demo.url == URL(string: "http://example.com/")) - assert(demo.handle == 123) - - // Change some data and ensure that the round-trip works - demo.url = URL(string: "http://new.example.com/")! - demo.handle = 456 - assert(demo == getCustomTypesDemo(demo: demo)) -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/test_generated_bindings.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/test_generated_bindings.rs deleted file mode 100644 index 38db89790ef2..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/tests/test_generated_bindings.rs +++ /dev/null @@ -1,7 +0,0 @@ -uniffi::build_foreign_language_testcases!( - ["src/custom-types.udl"], - [ - "tests/bindings/test_custom_types.kts", - "tests/bindings/test_custom_types.swift", - ] -); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/uniffi.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/uniffi.toml deleted file mode 100644 index 873fa090fbb1..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/custom-types/uniffi.toml +++ /dev/null @@ -1,40 +0,0 @@ -[bindings.swift] -cdylib_name = "custom_types" - -[bindings.swift.custom_types.Url] -# Name of the type in the Swift code -type_name = "URL" -# Modules that need to be imported -imports = ["Foundation"] -# Functions to convert between strings and URLs -into_custom = "URL(string: {})!" -from_custom = "String(describing: {})" - -[bindings.kotlin] -cdylib_name = "custom_types" -package_name = "customtypes" - -[bindings.kotlin.custom_types.Url] -# Name of the type in the Kotlin code -type_name = "URL" -# Classes that need to be imported -imports = [ "java.net.URL" ] -# Functions to convert between strings and URLs -into_custom = "URL({})" -from_custom = "{}.toString()" - -[bindings.python] -cdylib_name = "custom_types" - -[bindings.python.custom_types.Url] -# We're going to be the urllib.parse.ParseResult class, which is the closest -# thing Python has to a Url class. No need to specify `type_name` though, -# since Python is loosely typed. -# modules to import -imports = ["urllib.parse"] -# Functions to convert between strings and the ParsedUrl class -into_custom = "urllib.parse.urlparse({})" -from_custom = "urllib.parse.urlunparse({})" - -[bindings.ruby] -cdylib_name = "custom_types" diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/external-types/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/external-types/Cargo.toml deleted file mode 100644 index 64f13965569d..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/external-types/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "uniffi-fixture-external-types" -edition = "2021" -version = "0.21.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[dependencies] -uniffi-example-geometry = { path = "../geometry/" } -uniffi-example-sprites = { path = "../sprites/" } -uniffi = { workspace = true } -thiserror = "1.0" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/external-types/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/external-types/src/lib.rs deleted file mode 100644 index e4556e800795..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/external-types/src/lib.rs +++ /dev/null @@ -1,27 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -use uniffi_geometry::{Line, Point}; - -#[uniffi::export] -pub fn gradient(value: Option) -> f64 { - match value { - None => 0.0, - Some(value) => uniffi_geometry::gradient(value), - } -} - -#[uniffi::export] -pub fn intersection(ln1: Line, ln2: Line) -> Option { - uniffi_geometry::intersection(ln1, ln2) -} - -#[uniffi::export] -pub fn move_sprite_to_origin(sprite: Arc) { - sprite.move_to(uniffi_sprites::Point { x: 0.0, y: 0.0 }) -} - -uniffi::setup_scaffolding!("external_types"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/Cargo.toml deleted file mode 100644 index 96d4e79a3084..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-fixture-futures" -version = "0.21.0" -edition = "2021" -license = "MPL-2.0" -publish = false - -[lib] -name = "uniffi_fixture_futures" - -[dependencies] -log = "0.4" -# This needs to be optional, since we want to build this library to generate the bindings from, but -# moz-task can only currently be built from inside `./mach build`. -moz_task = { path = "../../../../../xpcom/rust/moz_task/", optional = true } -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/future_tester.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/future_tester.rs deleted file mode 100644 index 2ddddc4a99a7..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/future_tester.rs +++ /dev/null @@ -1,52 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Test basic interop between Rust futures and JS async code -//! -//! [FutureTester::make_future] returns a future and the other methods manipulate it manually. - -use std::sync::Mutex; - -use crate::oneshot; - -#[derive(uniffi::Object, Default)] -pub struct FutureTester { - inner: Mutex>>, -} - -#[uniffi::export] -impl FutureTester { - #[uniffi::constructor] - pub fn init() -> Self { - Self::default() - } - - /// Make a new future that can be manipulated with the other FutureTester methods - async fn make_future(&self) -> u8 { - let (tx, rx) = oneshot::channel(); - self.inner.lock().unwrap().push(tx); - rx.await - } - - /// Store a value in all futures created via `make_future()`, then wake up any wakers. - /// This will cause the C++ code to poll the future and get a `Ready` result. - /// - /// Returns the number of futures completed - fn complete_futures(&self, value: u8) -> u32 { - let mut count = 0; - for sender in self.inner.lock().unwrap().drain(..) { - sender.send(value); - count += 1; - } - count - } - - /// Wake up the waker for all futures created via `make_future()`. This will cause the C++ - /// code to poll the future, but it will get another `Pending` result - fn wake_futures(&self) { - for sender in self.inner.lock().unwrap().iter() { - sender.wake() - } - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/lib.rs deleted file mode 100644 index bb275f48939d..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/lib.rs +++ /dev/null @@ -1,14 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -mod future_tester; -mod oneshot; -mod roundtrip; -mod wrapped_sync_call; - -pub use future_tester::*; -pub use wrapped_sync_call::*; -pub use roundtrip::*; - -uniffi::setup_scaffolding!("futures"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/oneshot.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/oneshot.rs deleted file mode 100644 index 33db5003e0e2..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/oneshot.rs +++ /dev/null @@ -1,66 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Simple oneshot channel implementation. -//! -//! In practice, we would probably use the `oneshot` crate for this, but it's not worth bringing in -//! that dependency for this test fixture. - -use std::{ - future::Future, - pin::Pin, - sync::{Arc, Mutex}, - task::{Context, Poll, Waker}, -}; - -struct Channel { - value: Option, - waker: Option, -} - -pub struct Sender(Arc>>); -pub struct Receiver(Arc>>); - -pub fn channel() -> (Sender, Receiver) { - let channel = Arc::new(Mutex::new(Channel { - value: None, - waker: None, - })); - (Sender(channel.clone()), Receiver(channel)) -} - -impl Sender { - pub fn send(self, value: T) { - let mut channel = self.0.lock().unwrap(); - channel.value = Some(value); - if let Some(waker) = channel.waker.take() { - waker.wake(); - } - } - - // Wake all receivers, without sending a value. - // - // This causes them to poll again and receive another `Poll::Pending` result - pub fn wake(&self) { - let mut channel = self.0.lock().unwrap(); - if let Some(waker) = channel.waker.take() { - waker.wake(); - } - } -} - -impl Future for Receiver { - type Output = T; - - fn poll(self: Pin<&mut Self>, context: &mut Context) -> Poll { - let mut channel = self.0.lock().unwrap(); - match channel.value.take() { - Some(v) => Poll::Ready(v), - None => { - channel.waker = Some(context.waker().clone()); - Poll::Pending - } - } - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/roundtrip.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/roundtrip.rs deleted file mode 100644 index 2455bd0e5dbc..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/roundtrip.rs +++ /dev/null @@ -1,97 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Some barely async functions that round-trip data. -//! -//! The purpose of these is to test the lift/lower implementations in the async code. - -use std::{collections::HashMap, sync::Arc}; - - -#[uniffi::export] -async fn roundtrip_u8(v: u8) -> u8 { - v -} - -#[uniffi::export] -async fn roundtrip_i8(v: i8) -> i8 { - v -} - -#[uniffi::export] -async fn roundtrip_u16(v: u16) -> u16 { - v -} - -#[uniffi::export] -async fn roundtrip_i16(v: i16) -> i16 { - v -} - -#[uniffi::export] -async fn roundtrip_u32(v: u32) -> u32 { - v -} - -#[uniffi::export] -async fn roundtrip_i32(v: i32) -> i32 { - v -} - -#[uniffi::export] -async fn roundtrip_u64(v: u64) -> u64 { - v -} - -#[uniffi::export] -async fn roundtrip_i64(v: i64) -> i64 { - v -} - -#[uniffi::export] -async fn roundtrip_f32(v: f32) -> f32 { - v -} - -#[uniffi::export] -async fn roundtrip_f64(v: f64) -> f64 { - v -} - -#[uniffi::export] -async fn roundtrip_string(v: String) -> String { - v -} - -#[uniffi::export] -async fn roundtrip_vec(v: Vec) -> Vec { - v -} - -#[uniffi::export] -async fn roundtrip_map(v: HashMap) -> HashMap { - v -} - -#[derive(uniffi::Object)] -struct Traveller { - name: String, -} - -#[uniffi::export] -impl Traveller { - #[uniffi::constructor] - pub fn new(name: String) -> Arc { - Arc::new(Traveller { name }) - } - - pub fn name(&self) -> String { - self.name.clone() - } -} - -#[uniffi::export] -async fn roundtrip_obj(v: Arc) -> Arc { - v -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/wrapped_sync_call.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/wrapped_sync_call.rs deleted file mode 100644 index f265cf447118..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/futures/src/wrapped_sync_call.rs +++ /dev/null @@ -1,131 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Test wrapping sync Rust calls and making them async. -//! -//! This is intended to mimic what we do in application-services: create a synchrounous API, then -//! wrap it so that most methods are async and run in a worker queue. -//! -//! -//! This provides the essentially same functionality as the automatic async wrapping that is -//! available by editing `config.toml` so why do it? -//! -//! - Implementing the async wrapping in Rust leads to better docs. The auto-generated API -//! reference will show which functions are sync and which are async. Telling users that -//! sync functions are actually actually async because of UniFFI magic would lead to confusion. -//! -//! - It opens the door to future performance improvements. Some methods could be async without -//! this wrapper and without sending anything to a background thread. Fxa API calls using an -//! async HTTP client would be one example. Some methods could be split into a "real" async part -//! and a wrapped async part. -//! -//! - Async Rust code allows for new patterns. Maybe the FxA state machine would be better -//! modelled as an async actor rather than a bunch of sync methods protected by a Mutex. - -use std::{sync::{Arc, Mutex, OnceLock}, thread::sleep, time::Duration}; - -use crate::oneshot; - -/// Worker queue scheduler trait -/// -/// This is a trait that the foreign code implements to schedule Rust tasks in a worker queue. On -/// Swift/Kotlin, we can implement this trait using a DispatchQueue/CoroutineContext. -/// -/// On JS we can't implement it directly, since JS is single-threaded and we don't want to start up -/// a web worker. Instead, we implement the trait in Rust using `moz_task`. -#[uniffi::export] -pub trait WorkerQueue: Send + Sync { - fn add_task(&self, task: Arc); -} - - -#[uniffi::export] -pub trait RustTask: Send + Sync { - fn run(&self); -} - -/// Initialize the global worker queue. The Rust code will use this schedule sync tasks in the -/// background in order to present an async interface. -#[uniffi::export] -pub fn initialize_global_worker_queue(worker_queue: Arc) { - GLOBAL_WORKER_QUEUE.set(worker_queue) - .unwrap_or_else(|_| panic!("init_global_worker_queue called twice")); -} - -static GLOBAL_WORKER_QUEUE: OnceLock> = OnceLock::new(); - -/// Schedule a closure to run in the global worker queue. Returns the result of the closure -/// asynchronously -pub async fn run_in_background(task: impl FnOnce() -> T + Send + Sync + 'static) -> T { - let (tx, rx) = oneshot::channel(); - - GLOBAL_WORKER_QUEUE.get() - .unwrap_or_else(|| panic!("init_global_worker_queue never called")) - .add_task(RustTaskContainer::new_arc(move || { - tx.send(task()) - })); - rx.await -} - -/// Implements RustTask for any closure -/// -/// The one tricky part is that the task can only be run once, but the foreign language gets a -/// shared reference to it. This implementation uses a Mutex, in the real world, `UnsafeCell` + -/// `Once` might be a better option. -struct RustTaskContainer(Mutex>); - -impl RustTaskContainer { - fn new_arc(task: T) -> Arc { - Arc::new(Self(Mutex::new(Some(task)))) - } -} - -impl RustTask for RustTaskContainer { - fn run(&self) { - if let Some(f) = self.0.lock().unwrap().take() { - f() - } - } -} - -/// Initialize the global worker for JS. -/// -/// All code above here is generalized task code that works for JS, Kotlin, and Swift. -/// -/// This function and the GeckoWorkerQueue struct are Gecko-specific. -#[uniffi::export] -pub fn initialize_gecko_global_worker_queue() { - initialize_global_worker_queue(Arc::new(GeckoWorkerQueue)); -} - -struct GeckoWorkerQueue; - -impl WorkerQueue for GeckoWorkerQueue { - // This version is what runs when we're linked into libgecko - #[cfg(feature = "moz_task")] - fn add_task(&self, task: Arc) { - if let Err(e) = moz_task::dispatch_background_task("UniFFI task", move || task.run()) { - log::error!("Failed to dispatch background task: {e}"); - } - } - - // This is as stub that allows us to build a library for uniffi-bindgen to use, but without - // depending on gecko. Gecko can only be built inside of `./mach build` and we want to build - // the library using plain `cargo build`. - #[cfg(not(feature = "moz_task"))] - fn add_task(&self, _task: Arc) { - panic!("moz_task not enabled"); - } -} - -/// Function to test the global worker queue -/// -/// This is how Rust components can wrap synchronous tasks to present an async interface. -#[uniffi::export] -pub async fn expensive_computation() -> u32 { - run_in_background(|| { - sleep(Duration::from_millis(1)); - 1000 - }).await -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/README.md b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/README.md deleted file mode 100644 index 91372fd31c61..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/README.md +++ /dev/null @@ -1 +0,0 @@ -This directory is where files generated by Uniffi will be created. diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustArithmetic.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustArithmetic.sys.mjs deleted file mode 100644 index 39ff545d3083..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustArithmetic.sys.mjs +++ /dev/null @@ -1,558 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint64(value) - } - static read(dataStream) { - return dataStream.readUint64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - - - - -/** - * ArithmeticError - */ -export class ArithmeticError extends Error {} - - -/** - * INTEGER_OVERFLOW - */ -export class IntegerOverflow extends ArithmeticError { - - constructor(message, ...params) { - super(...params); - this.message = message; - } - toString() { - return `IntegerOverflow: ${super.toString()}` - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeArithmeticError extends FfiConverterArrayBuffer { - static read(dataStream) { - switch (dataStream.readInt32()) { - case 1: - return new IntegerOverflow(FfiConverterString.read(dataStream)); - default: - throw new UniFFITypeError("Unknown ArithmeticError variant"); - } - } - static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof IntegerOverflow) { - return totalSize; - } - throw new UniFFITypeError("Unknown ArithmeticError variant"); - } - static write(dataStream, value) { - if (value instanceof IntegerOverflow) { - dataStream.writeInt32(1); - return; - } - throw new UniFFITypeError("Unknown ArithmeticError variant"); - } - - static errorClass = ArithmeticError; -} - - - - - -/** - * add - * @returns {number} - */ -export function add(a,b) { - - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = (data) => FfiConverterTypeArithmeticError.lift(data); - const functionCall = () => { - try { - FfiConverterU64.checkType(a) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("a"); - } - throw e; - } - try { - FfiConverterU64.checkType(b) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("b"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 109, // arithmetic:uniffi_arithmetical_fn_func_add - FfiConverterU64.lower(a), - FfiConverterU64.lower(b), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * div - * @returns {number} - */ -export function div(dividend,divisor) { - - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(dividend) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("dividend"); - } - throw e; - } - try { - FfiConverterU64.checkType(divisor) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("divisor"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 110, // arithmetic:uniffi_arithmetical_fn_func_div - FfiConverterU64.lower(dividend), - FfiConverterU64.lower(divisor), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * equal - * @returns {Boolean} - */ -export function equal(a,b) { - - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(a) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("a"); - } - throw e; - } - try { - FfiConverterU64.checkType(b) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("b"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 111, // arithmetic:uniffi_arithmetical_fn_func_equal - FfiConverterU64.lower(a), - FfiConverterU64.lower(b), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * sub - * @returns {number} - */ -export function sub(a,b) { - - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = (data) => FfiConverterTypeArithmeticError.lift(data); - const functionCall = () => { - try { - FfiConverterU64.checkType(a) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("a"); - } - throw e; - } - try { - FfiConverterU64.checkType(b) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("b"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 112, // arithmetic:uniffi_arithmetical_fn_func_sub - FfiConverterU64.lower(a), - FfiConverterU64.lower(b), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustCustomTypes.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustCustomTypes.sys.mjs deleted file mode 100644 index 292f2db797d4..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustCustomTypes.sys.mjs +++ /dev/null @@ -1,1083 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterU8 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 256) { - throw new UniFFITypeError(`${value} exceeds the U8 bounds`); - } - } - static computeSize(_value) { - return 1; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint8(value) - } - static read(dataStream) { - return dataStream.readUint8() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt64(value) - } - static read(dataStream) { - return dataStream.readInt64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * CustomTypesDemo - */ -export class CustomTypesDemo { - constructor({ url, handle } = { url: undefined, handle: undefined }) { - try { - FfiConverterTypeUrl.checkType(url) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("url"); - } - throw e; - } - try { - FfiConverterTypeHandle.checkType(handle) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("handle"); - } - throw e; - } - /** - * @type {Url} - */ - this.url = url; - /** - * @type {Handle} - */ - this.handle = handle; - } - - equals(other) { - return ( - this.url == other.url && - this.handle == other.handle - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeCustomTypesDemo extends FfiConverterArrayBuffer { - static read(dataStream) { - return new CustomTypesDemo({ - url: FfiConverterTypeUrl.read(dataStream), - handle: FfiConverterTypeHandle.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterTypeUrl.write(dataStream, value.url); - FfiConverterTypeHandle.write(dataStream, value.handle); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterTypeUrl.computeSize(value.url); - totalSize += FfiConverterTypeHandle.computeSize(value.handle); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof CustomTypesDemo)) { - throw new UniFFITypeError(`Expected 'CustomTypesDemo', found '${typeof value}'`); - } - try { - FfiConverterTypeUrl.checkType(value.url); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".url"); - } - throw e; - } - try { - FfiConverterTypeHandle.checkType(value.handle); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".handle"); - } - throw e; - } - } -} - - -/** - * ExplicitValuedEnum - */ -export const ExplicitValuedEnum = { - /** - * FIRST - */ - FIRST:1, - /** - * SECOND - */ - SECOND:2, - /** - * FOURTH - */ - FOURTH:4, - /** - * TENTH - */ - TENTH:10, - /** - * ELEVENTH - */ - ELEVENTH:11, - /** - * THIRTEENTH - */ - THIRTEENTH:13, -}; - -Object.freeze(ExplicitValuedEnum); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeExplicitValuedEnum extends FfiConverterArrayBuffer { - static #validValues = Object.values(ExplicitValuedEnum); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return ExplicitValuedEnum.FIRST - case 2: - return ExplicitValuedEnum.SECOND - case 3: - return ExplicitValuedEnum.FOURTH - case 4: - return ExplicitValuedEnum.TENTH - case 5: - return ExplicitValuedEnum.ELEVENTH - case 6: - return ExplicitValuedEnum.THIRTEENTH - default: - throw new UniFFITypeError("Unknown ExplicitValuedEnum variant"); - } - } - - static write(dataStream, value) { - if (value === ExplicitValuedEnum.FIRST) { - dataStream.writeInt32(1); - return; - } - if (value === ExplicitValuedEnum.SECOND) { - dataStream.writeInt32(2); - return; - } - if (value === ExplicitValuedEnum.FOURTH) { - dataStream.writeInt32(3); - return; - } - if (value === ExplicitValuedEnum.TENTH) { - dataStream.writeInt32(4); - return; - } - if (value === ExplicitValuedEnum.ELEVENTH) { - dataStream.writeInt32(5); - return; - } - if (value === ExplicitValuedEnum.THIRTEENTH) { - dataStream.writeInt32(6); - return; - } - throw new UniFFITypeError("Unknown ExplicitValuedEnum variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for ExplicitValuedEnum`); - } - } -} - - - -/** - * GappedEnum - */ -export const GappedEnum = { - /** - * ONE - */ - ONE:10, - /** - * TWO - */ - TWO:11, - /** - * THREE - */ - THREE:14, -}; - -Object.freeze(GappedEnum); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeGappedEnum extends FfiConverterArrayBuffer { - static #validValues = Object.values(GappedEnum); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return GappedEnum.ONE - case 2: - return GappedEnum.TWO - case 3: - return GappedEnum.THREE - default: - throw new UniFFITypeError("Unknown GappedEnum variant"); - } - } - - static write(dataStream, value) { - if (value === GappedEnum.ONE) { - dataStream.writeInt32(1); - return; - } - if (value === GappedEnum.TWO) { - dataStream.writeInt32(2); - return; - } - if (value === GappedEnum.THREE) { - dataStream.writeInt32(3); - return; - } - throw new UniFFITypeError("Unknown GappedEnum variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for GappedEnum`); - } - } -} - - - -/** - * SequentialEnum - */ -export const SequentialEnum = { - /** - * FIRST - */ - FIRST:0, - /** - * SECOND - */ - SECOND:1, - /** - * FOURTH - */ - FOURTH:2, - /** - * TENTH - */ - TENTH:3, - /** - * ELEVENTH - */ - ELEVENTH:4, - /** - * THIRTEENTH - */ - THIRTEENTH:5, -}; - -Object.freeze(SequentialEnum); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSequentialEnum extends FfiConverterArrayBuffer { - static #validValues = Object.values(SequentialEnum); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return SequentialEnum.FIRST - case 2: - return SequentialEnum.SECOND - case 3: - return SequentialEnum.FOURTH - case 4: - return SequentialEnum.TENTH - case 5: - return SequentialEnum.ELEVENTH - case 6: - return SequentialEnum.THIRTEENTH - default: - throw new UniFFITypeError("Unknown SequentialEnum variant"); - } - } - - static write(dataStream, value) { - if (value === SequentialEnum.FIRST) { - dataStream.writeInt32(1); - return; - } - if (value === SequentialEnum.SECOND) { - dataStream.writeInt32(2); - return; - } - if (value === SequentialEnum.FOURTH) { - dataStream.writeInt32(3); - return; - } - if (value === SequentialEnum.TENTH) { - dataStream.writeInt32(4); - return; - } - if (value === SequentialEnum.ELEVENTH) { - dataStream.writeInt32(5); - return; - } - if (value === SequentialEnum.THIRTEENTH) { - dataStream.writeInt32(6); - return; - } - throw new UniFFITypeError("Unknown SequentialEnum variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for SequentialEnum`); - } - } -} - - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeCustomTypesDemo extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeCustomTypesDemo.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeCustomTypesDemo.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeCustomTypesDemo.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeCustomTypesDemo.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterMapStringU8 extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const map = new Map(); - for (let i = 0; i < len; i++) { - const key = FfiConverterString.read(dataStream); - const value = FfiConverterU8.read(dataStream); - map.set(key, value); - } - - return map; - } - - static write(dataStream, map) { - dataStream.writeInt32(map.size); - for (const [key, value] of map) { - FfiConverterString.write(dataStream, key); - FfiConverterU8.write(dataStream, value); - } - } - - static computeSize(map) { - // The size of the length - let size = 4; - for (const [key, value] of map) { - size += FfiConverterString.computeSize(key); - size += FfiConverterU8.computeSize(value); - } - return size; - } - - static checkType(map) { - for (const [key, value] of map) { - try { - FfiConverterString.checkType(key); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("(key)"); - } - throw e; - } - - try { - FfiConverterU8.checkType(value); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${key}]`); - } - throw e; - } - } - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeHandle extends FfiConverter { - static lift(buf) { - return FfiConverterI64.lift(buf); - } - - static lower(buf) { - return FfiConverterI64.lower(buf); - } - - static write(dataStream, value) { - FfiConverterI64.write(dataStream, value); - } - - static read(buf) { - return FfiConverterI64.read(buf); - } - - static computeSize(value) { - return FfiConverterI64.computeSize(value); - } -} -// TODO: We should also allow JS to customize the type eventually. - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeUrl extends FfiConverter { - static lift(buf) { - return FfiConverterString.lift(buf); - } - - static lower(buf) { - return FfiConverterString.lower(buf); - } - - static write(dataStream, value) { - FfiConverterString.write(dataStream, value); - } - - static read(buf) { - return FfiConverterString.read(buf); - } - - static computeSize(value) { - return FfiConverterString.computeSize(value); - } -} -// TODO: We should also allow JS to customize the type eventually. - - - - - -/** - * echoExplicitValue - * @returns {ExplicitValuedEnum} - */ -export function echoExplicitValue(value) { - - const liftResult = (result) => FfiConverterTypeExplicitValuedEnum.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeExplicitValuedEnum.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 113, // custom_types:uniffi_uniffi_custom_types_fn_func_echo_explicit_value - FfiConverterTypeExplicitValuedEnum.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * echoGappedValue - * @returns {GappedEnum} - */ -export function echoGappedValue(value) { - - const liftResult = (result) => FfiConverterTypeGappedEnum.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeGappedEnum.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 114, // custom_types:uniffi_uniffi_custom_types_fn_func_echo_gapped_value - FfiConverterTypeGappedEnum.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * echoSequentialValue - * @returns {SequentialEnum} - */ -export function echoSequentialValue(value) { - - const liftResult = (result) => FfiConverterTypeSequentialEnum.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeSequentialEnum.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 115, // custom_types:uniffi_uniffi_custom_types_fn_func_echo_sequential_value - FfiConverterTypeSequentialEnum.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getCustomTypesDemo - * @returns {CustomTypesDemo} - */ -export function getCustomTypesDemo(demo) { - - const liftResult = (result) => FfiConverterTypeCustomTypesDemo.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterOptionalTypeCustomTypesDemo.checkType(demo) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("demo"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 116, // custom_types:uniffi_uniffi_custom_types_fn_func_get_custom_types_demo - FfiConverterOptionalTypeCustomTypesDemo.lower(demo), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getExplicitDiscriminant - * @returns {number} - */ -export function getExplicitDiscriminant(value) { - - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeExplicitValuedEnum.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 117, // custom_types:uniffi_uniffi_custom_types_fn_func_get_explicit_discriminant - FfiConverterTypeExplicitValuedEnum.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getExplicitEnumValues - * @returns {object} - */ -export function getExplicitEnumValues() { - - const liftResult = (result) => FfiConverterMapStringU8.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 118, // custom_types:uniffi_uniffi_custom_types_fn_func_get_explicit_enum_values - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getGappedDiscriminant - * @returns {number} - */ -export function getGappedDiscriminant(value) { - - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeGappedEnum.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 119, // custom_types:uniffi_uniffi_custom_types_fn_func_get_gapped_discriminant - FfiConverterTypeGappedEnum.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getGappedEnumValues - * @returns {object} - */ -export function getGappedEnumValues() { - - const liftResult = (result) => FfiConverterMapStringU8.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 120, // custom_types:uniffi_uniffi_custom_types_fn_func_get_gapped_enum_values - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getSequentialDiscriminant - * @returns {number} - */ -export function getSequentialDiscriminant(value) { - - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeSequentialEnum.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 121, // custom_types:uniffi_uniffi_custom_types_fn_func_get_sequential_discriminant - FfiConverterTypeSequentialEnum.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustExternalTypes.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustExternalTypes.sys.mjs deleted file mode 100644 index c81a1b5a779e..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustExternalTypes.sys.mjs +++ /dev/null @@ -1,509 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeLine extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeLine.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeLine.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeLine.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeLine.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypePoint extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypePoint.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypePoint.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypePoint.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypePoint.computeSize(value) - } -} - -import { - FfiConverterTypeSprite, - Sprite, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustSprites.sys.mjs"; - -// Export the FFIConverter object to make external types work. -export { FfiConverterTypeSprite, Sprite };import { - FfiConverterTypeLine, - Line, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustGeometry.sys.mjs"; - -// Export the FFIConverter object to make external types work. -export { FfiConverterTypeLine, Line };import { - FfiConverterTypePoint, - Point, -} from "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/components/generated/RustGeometry.sys.mjs"; - -// Export the FFIConverter object to make external types work. -export { FfiConverterTypePoint, Point }; - - - -/** - * gradient - * @returns {number} - */ -export function gradient(value) { - - const liftResult = (result) => FfiConverterF64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterOptionalTypeLine.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 122, // external_types:uniffi_uniffi_fixture_external_types_fn_func_gradient - FfiConverterOptionalTypeLine.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * intersection - * @returns {?Point} - */ -export function intersection(ln1,ln2) { - - const liftResult = (result) => FfiConverterOptionalTypePoint.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeLine.checkType(ln1) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ln1"); - } - throw e; - } - try { - FfiConverterTypeLine.checkType(ln2) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ln2"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 123, // external_types:uniffi_uniffi_fixture_external_types_fn_func_intersection - FfiConverterTypeLine.lower(ln1), - FfiConverterTypeLine.lower(ln2), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * moveSpriteToOrigin - */ -export function moveSpriteToOrigin(sprite) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeSprite.checkType(sprite) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("sprite"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 124, // external_types:uniffi_uniffi_fixture_external_types_fn_func_move_sprite_to_origin - FfiConverterTypeSprite.lower(sprite), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustFixtureCallbacks.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustFixtureCallbacks.sys.mjs deleted file mode 100644 index 482f231690d3..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustFixtureCallbacks.sys.mjs +++ /dev/null @@ -1,822 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - - -/** - * Handler for a single UniFFI CallbackInterface - * - * This class stores objects that implement a callback interface in a handle - * map, allowing them to be referenced by the Rust code using an integer - * handle. - * - * While the callback object is stored in the map, it allows the Rust code to - * call methods on the object using the callback object handle, a method id, - * and an ArrayBuffer packed with the method arguments. - * - * When the Rust code drops its reference, it sends a call with the methodId=0, - * which causes callback object to be removed from the map. - */ -class UniFFICallbackHandler { - #name; - #interfaceId; - #handleCounter; - #handleMap; - #methodHandlers; - #allowNewCallbacks - - /** - * Create a UniFFICallbackHandler - * @param {string} name - Human-friendly name for this callback interface - * @param {int} interfaceId - Interface ID for this CallbackInterface. - * @param {UniFFICallbackMethodHandler[]} methodHandlers -- UniFFICallbackHandler for each method, in the same order as the UDL file - */ - constructor(name, interfaceId, methodHandlers) { - this.#name = name; - this.#interfaceId = interfaceId; - this.#handleCounter = 0; - this.#handleMap = new Map(); - this.#methodHandlers = methodHandlers; - this.#allowNewCallbacks = true; - - UniFFIScaffolding.registerCallbackHandler(this.#interfaceId, this); - Services.obs.addObserver(this, "xpcom-shutdown"); - } - - /** - * Store a callback object in the handle map and return the handle - * - * @param {obj} callbackObj - Object that implements the callback interface - * @returns {int} - Handle for this callback object, this is what gets passed back to Rust. - */ - storeCallbackObj(callbackObj) { - if (!this.#allowNewCallbacks) { - throw new UniFFIError(`No new callbacks allowed for ${this.#name}`); - } - const handle = this.#handleCounter; - this.#handleCounter += 1; - this.#handleMap.set(handle, new UniFFICallbackHandleMapEntry(callbackObj, Components.stack.caller.formattedStack.trim())); - return handle; - } - - /** - * Get a previously stored callback object - * - * @param {int} handle - Callback object handle, returned from `storeCallbackObj()` - * @returns {obj} - Callback object - */ - getCallbackObj(handle) { - return this.#handleMap.get(handle).callbackObj; - } - - /** - * Set if new callbacks are allowed for this handler - * - * This is called with false during shutdown to ensure the callback maps don't - * prevent JS objects from being GCed. - */ - setAllowNewCallbacks(allow) { - this.#allowNewCallbacks = allow - } - - /** - * Check that no callbacks are currently registered - * - * If there are callbacks registered a UniFFIError will be thrown. This is - * called during shutdown to generate an alert if there are leaked callback - * interfaces. - */ - assertNoRegisteredCallbacks() { - if (this.#handleMap.size > 0) { - const entry = this.#handleMap.values().next().value; - throw new UniFFIError(`UniFFI interface ${this.#name} has ${this.#handleMap.size} registered callbacks at xpcom-shutdown. This likely indicates a UniFFI callback leak.\nStack trace for the first leaked callback:\n${entry.stackTrace}.`); - } - } - - /** - * Invoke a method on a stored callback object - * @param {int} handle - Object handle - * @param {int} methodId - Method index (0-based) - * @param {UniFFIScaffoldingValue[]} args - Arguments to pass to the method - */ - call(handle, methodId, ...args) { - try { - this.#invokeCallbackInner(handle, methodId, args); - } catch (e) { - console.error(`internal error invoking callback: ${e}`) - } - } - - /** - * Destroy a stored callback object - * @param {int} handle - Object handle - */ - destroy(handle) { - this.#handleMap.delete(handle); - } - - #invokeCallbackInner(handle, methodId, args) { - const callbackObj = this.getCallbackObj(handle); - if (callbackObj === undefined) { - throw new UniFFIError(`${this.#name}: invalid callback handle id: ${handle}`); - } - - // Get the method data, converting from 1-based indexing - const methodHandler = this.#methodHandlers[methodId]; - if (methodHandler === undefined) { - throw new UniFFIError(`${this.#name}: invalid method id: ${methodId}`) - } - - methodHandler.call(callbackObj, args); - } - - /** - * xpcom-shutdown observer method - * - * This handles: - * - Deregistering ourselves as the UniFFI callback handler - * - Checks for any leftover stored callbacks which indicate memory leaks - */ - observe(aSubject, aTopic, aData) { - if (aTopic == "xpcom-shutdown") { - try { - this.setAllowNewCallbacks(false); - this.assertNoRegisteredCallbacks(); - UniFFIScaffolding.deregisterCallbackHandler(this.#interfaceId); - } catch (ex) { - console.error(`UniFFI Callback interface error during xpcom-shutdown: ${ex}`); - Cc["@mozilla.org/xpcom/debug;1"] - .getService(Ci.nsIDebug2) - .abort(ex.filename, ex.lineNumber); - } - } - } -} - -/** - * Handles calling a single method for a callback interface - */ -class UniFFICallbackMethodHandler { - #name; - #argsConverters; - - /** - * Create a UniFFICallbackMethodHandler - - * @param {string} name -- Name of the method to call on the callback object - * @param {FfiConverter[]} argsConverters - FfiConverter for each argument type - */ - constructor(name, argsConverters) { - this.#name = name; - this.#argsConverters = argsConverters; - } - - /** - * Invoke the method - * - * @param {obj} callbackObj -- Object implementing the callback interface for this method - * @param {ArrayBuffer} argsArrayBuffer -- Arguments for the method, packed in an ArrayBuffer - */ - call(callbackObj, args) { - const convertedArgs = this.#argsConverters.map((converter, i) => converter.lift(args[i])); - return callbackObj[this.#name](...convertedArgs); - } -} - -/** - * UniFFICallbackHandler.handleMap entry - * - * @property callbackObj - Callback object, this must implement the callback interface. - * @property {string} stackTrace - Stack trace from when the callback object was registered. This is used to proved extra context when debugging leaked callback objects. - */ -class UniFFICallbackHandleMapEntry { - constructor(callbackObj, stackTrace) { - this.callbackObj = callbackObj; - this.stackTrace = stackTrace - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint32(value) - } - static read(dataStream) { - return dataStream.readUint32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -2147483648 || value > 2147483647) { - throw new UniFFITypeError(`${value} exceeds the I32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt32(value) - } - static read(dataStream) { - return dataStream.readInt32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeLogger extends FfiConverter { - static lower(callbackObj) { - return callbackHandlerLogger.storeCallbackObj(callbackObj) - } - - static lift(handleId) { - return callbackHandlerLogger.getCallbackObj(handleId) - } - - static read(dataStream) { - return this.lift(dataStream.readInt64()) - } - - static write(dataStream, callbackObj) { - dataStream.writeInt64(this.lower(callbackObj)) - } - - static computeSize(callbackObj) { - return 8; - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceu32 extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterU32.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterU32.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterU32.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterU32.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencei32 extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterI32.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterI32.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterI32.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterI32.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - - -// Define callback interface handlers, this must come after the type loop since they reference the FfiConverters defined above. - -const callbackHandlerLogger = new UniFFICallbackHandler( - "fixture_callbacks:Logger", - 2, - [ - new UniFFICallbackMethodHandler( - "log", - [ - FfiConverterString, - ], - ), - new UniFFICallbackMethodHandler( - "logRepeat", - [ - FfiConverterString, - FfiConverterU32, - FfiConverterSequenceu32, - ], - ), - new UniFFICallbackMethodHandler( - "finished", - [ - ], - ), - ] -); - -// Allow the shutdown-related functionality to be tested in the unit tests -UnitTestObjs.callbackHandlerLogger = callbackHandlerLogger; - - - - - -/** - * callLogRepeat - */ -export function callLogRepeat(logger,message,count,exclude) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeLogger.checkType(logger) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("logger"); - } - throw e; - } - try { - FfiConverterString.checkType(message) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("message"); - } - throw e; - } - try { - FfiConverterU32.checkType(count) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("count"); - } - throw e; - } - try { - FfiConverterSequenceu32.checkType(exclude) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("exclude"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 125, // fixture_callbacks:uniffi_uniffi_fixture_callbacks_fn_func_call_log_repeat - FfiConverterTypeLogger.lower(logger), - FfiConverterString.lower(message), - FfiConverterU32.lower(count), - FfiConverterSequenceu32.lower(exclude), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * logEvenNumbers - */ -export function logEvenNumbers(logger,items) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeLogger.checkType(logger) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("logger"); - } - throw e; - } - try { - FfiConverterSequencei32.checkType(items) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("items"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 126, // fixture_callbacks:uniffi_uniffi_fixture_callbacks_fn_func_log_even_numbers - FfiConverterTypeLogger.lower(logger), - FfiConverterSequencei32.lower(items), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * logEvenNumbersMainThread - */ -export function logEvenNumbersMainThread(logger,items) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeLogger.checkType(logger) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("logger"); - } - throw e; - } - try { - FfiConverterSequencei32.checkType(items) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("items"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 127, // fixture_callbacks:uniffi_uniffi_fixture_callbacks_fn_func_log_even_numbers_main_thread - FfiConverterTypeLogger.lower(logger), - FfiConverterSequencei32.lower(items), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustFutures.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustFutures.sys.mjs deleted file mode 100644 index 4701514b0689..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustFutures.sys.mjs +++ /dev/null @@ -1,1565 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } - - // Reads a FutureTester pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerFutureTester() { - const pointerId = 13; // futures:FutureTester - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a FutureTester pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerFutureTester(value) { - const pointerId = 13; // futures:FutureTester - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a RustTask pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerRustTask() { - const pointerId = 14; // futures:RustTask - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a RustTask pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerRustTask(value) { - const pointerId = 14; // futures:RustTask - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a Traveller pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerTraveller() { - const pointerId = 15; // futures:Traveller - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a Traveller pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerTraveller(value) { - const pointerId = 15; // futures:Traveller - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a WorkerQueue pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerWorkerQueue() { - const pointerId = 16; // futures:WorkerQueue - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a WorkerQueue pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerWorkerQueue(value) { - const pointerId = 16; // futures:WorkerQueue - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterU8 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 256) { - throw new UniFFITypeError(`${value} exceeds the U8 bounds`); - } - } - static computeSize(_value) { - return 1; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint8(value) - } - static read(dataStream) { - return dataStream.readUint8() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI8 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -128 || value > 127) { - throw new UniFFITypeError(`${value} exceeds the I8 bounds`); - } - } - static computeSize(_value) { - return 1; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt8(value) - } - static read(dataStream) { - return dataStream.readInt8() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU16 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 65535) { - throw new UniFFITypeError(`${value} exceeds the U16 bounds`); - } - } - static computeSize(_value) { - return 2; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint16(value) - } - static read(dataStream) { - return dataStream.readUint16() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI16 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -32768 || value > 32767) { - throw new UniFFITypeError(`${value} exceeds the I16 bounds`); - } - } - static computeSize(_value) { - return 2; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt16(value) - } - static read(dataStream) { - return dataStream.readInt16() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint32(value) - } - static read(dataStream) { - return dataStream.readUint32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -2147483648 || value > 2147483647) { - throw new UniFFITypeError(`${value} exceeds the I32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt32(value) - } - static read(dataStream) { - return dataStream.readInt32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint64(value) - } - static read(dataStream) { - return dataStream.readUint64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt64(value) - } - static read(dataStream) { - return dataStream.readInt64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterF32 extends FfiConverter { - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat32(value) - } - static read(dataStream) { - return dataStream.readFloat32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * FutureTester - */ -export class FutureTester { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {FutureTester} - */ - static init() { - const liftResult = (result) => FfiConverterTypeFutureTester.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 148, // futures:uniffi_uniffi_fixture_futures_fn_constructor_futuretester_init - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * Store a value in all futures created via `make_future()`, then wake up any wakers. - * This will cause the C++ code to poll the future and get a `Ready` result. - * - * Returns the number of futures completed - * @returns {number} - */ - completeFutures(value) { - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 145, // futures:uniffi_uniffi_fixture_futures_fn_method_futuretester_complete_futures - FfiConverterTypeFutureTester.lower(this), - FfiConverterU8.lower(value), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - - /** - * Make a new future that can be manipulated with the other FutureTester methods - * @returns {Promise}} - */ - makeFuture() { - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsync( - 146, // futures:uniffi_uniffi_fixture_futures_fn_method_futuretester_make_future - FfiConverterTypeFutureTester.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * Wake up the waker for all futures created via `make_future()`. This will cause the C++ - * code to poll the future, but it will get another `Pending` result - */ - wakeFutures() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 147, // futures:uniffi_uniffi_fixture_futures_fn_method_futuretester_wake_futures - FfiConverterTypeFutureTester.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeFutureTester extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new FutureTester(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'FutureTester' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerFutureTester()); - } - - static write(dataStream, value) { - dataStream.writePointerFutureTester(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * RustTask - */ -export class RustTask { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * run - */ - run() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 149, // futures:uniffi_uniffi_fixture_futures_fn_method_rusttask_run - FfiConverterTypeRustTask.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRustTask extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new RustTask(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'RustTask' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerRustTask()); - } - - static write(dataStream, value) { - dataStream.writePointerRustTask(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * Traveller - */ -export class Traveller { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {Traveller} - */ - static init(name) { - const liftResult = (result) => FfiConverterTypeTraveller.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(name) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("name"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 151, // futures:uniffi_uniffi_fixture_futures_fn_constructor_traveller_new - FfiConverterString.lower(name), - ) - } - return handleRustResult(functionCall(), liftResult, liftError);} - - /** - * name - * @returns {string} - */ - name() { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 150, // futures:uniffi_uniffi_fixture_futures_fn_method_traveller_name - FfiConverterTypeTraveller.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeTraveller extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new Traveller(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'Traveller' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerTraveller()); - } - - static write(dataStream, value) { - dataStream.writePointerTraveller(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * Worker queue scheduler trait - * - * This is a trait that the foreign code implements to schedule Rust tasks in a worker queue. On - * Swift/Kotlin, we can implement this trait using a DispatchQueue/CoroutineContext. - * - * On JS we can't implement it directly, since JS is single-threaded and we don't want to start up - * a web worker. Instead, we implement the trait in Rust using `moz_task`. - */ -export class WorkerQueue { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * addTask - */ - addTask(task) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeRustTask.checkType(task) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("task"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 152, // futures:uniffi_uniffi_fixture_futures_fn_method_workerqueue_add_task - FfiConverterTypeWorkerQueue.lower(this), - FfiConverterTypeRustTask.lower(task), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeWorkerQueue extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new WorkerQueue(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'WorkerQueue' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerWorkerQueue()); - } - - static write(dataStream, value) { - dataStream.writePointerWorkerQueue(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceu32 extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterU32.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterU32.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterU32.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterU32.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterMapStringString extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const map = new Map(); - for (let i = 0; i < len; i++) { - const key = FfiConverterString.read(dataStream); - const value = FfiConverterString.read(dataStream); - map.set(key, value); - } - - return map; - } - - static write(dataStream, map) { - dataStream.writeInt32(map.size); - for (const [key, value] of map) { - FfiConverterString.write(dataStream, key); - FfiConverterString.write(dataStream, value); - } - } - - static computeSize(map) { - // The size of the length - let size = 4; - for (const [key, value] of map) { - size += FfiConverterString.computeSize(key); - size += FfiConverterString.computeSize(value); - } - return size; - } - - static checkType(map) { - for (const [key, value] of map) { - try { - FfiConverterString.checkType(key); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("(key)"); - } - throw e; - } - - try { - FfiConverterString.checkType(value); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${key}]`); - } - throw e; - } - } - } -} - - - - - -/** - * Function to test the global worker queue - * - * This is how Rust components can wrap synchronous tasks to present an async interface. - * @returns {Promise}} - */ -export function expensiveComputation() { - - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsync( - 128, // futures:uniffi_uniffi_fixture_futures_fn_func_expensive_computation - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * Initialize the global worker for JS. - * - * All code above here is generalized task code that works for JS, Kotlin, and Swift. - * - * This function and the GeckoWorkerQueue struct are Gecko-specific. - */ -export function initializeGeckoGlobalWorkerQueue() { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 129, // futures:uniffi_uniffi_fixture_futures_fn_func_initialize_gecko_global_worker_queue - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} - -/** - * Initialize the global worker queue. The Rust code will use this schedule sync tasks in the - * background in order to present an async interface. - */ -export function initializeGlobalWorkerQueue(workerQueue) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeWorkerQueue.checkType(workerQueue) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("workerQueue"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 130, // futures:uniffi_uniffi_fixture_futures_fn_func_initialize_global_worker_queue - FfiConverterTypeWorkerQueue.lower(workerQueue), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} - -/** - * roundtripF32 - * @returns {Promise}} - */ -export function roundtripF32(v) { - - const liftResult = (result) => FfiConverterF32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF32.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 131, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_f32 - FfiConverterF32.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripF64 - * @returns {Promise}} - */ -export function roundtripF64(v) { - - const liftResult = (result) => FfiConverterF64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF64.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 132, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_f64 - FfiConverterF64.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripI16 - * @returns {Promise}} - */ -export function roundtripI16(v) { - - const liftResult = (result) => FfiConverterI16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI16.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 133, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_i16 - FfiConverterI16.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripI32 - * @returns {Promise}} - */ -export function roundtripI32(v) { - - const liftResult = (result) => FfiConverterI32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI32.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 134, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_i32 - FfiConverterI32.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripI64 - * @returns {Promise}} - */ -export function roundtripI64(v) { - - const liftResult = (result) => FfiConverterI64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI64.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 135, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_i64 - FfiConverterI64.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripI8 - * @returns {Promise}} - */ -export function roundtripI8(v) { - - const liftResult = (result) => FfiConverterI8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI8.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 136, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_i8 - FfiConverterI8.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripMap - * @returns {Promise}} - */ -export function roundtripMap(v) { - - const liftResult = (result) => FfiConverterMapStringString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterMapStringString.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 137, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_map - FfiConverterMapStringString.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripObj - * @returns {Promise}} - */ -export function roundtripObj(v) { - - const liftResult = (result) => FfiConverterTypeTraveller.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeTraveller.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 138, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_obj - FfiConverterTypeTraveller.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripString - * @returns {Promise}} - */ -export function roundtripString(v) { - - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 139, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_string - FfiConverterString.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripU16 - * @returns {Promise}} - */ -export function roundtripU16(v) { - - const liftResult = (result) => FfiConverterU16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU16.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 140, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_u16 - FfiConverterU16.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripU32 - * @returns {Promise}} - */ -export function roundtripU32(v) { - - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 141, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_u32 - FfiConverterU32.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripU64 - * @returns {Promise}} - */ -export function roundtripU64(v) { - - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 142, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_u64 - FfiConverterU64.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripU8 - * @returns {Promise}} - */ -export function roundtripU8(v) { - - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU8.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 143, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_u8 - FfiConverterU8.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * roundtripVec - * @returns {Promise>}} - */ -export function roundtripVec(v) { - - const liftResult = (result) => FfiConverterSequenceu32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterSequenceu32.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsync( - 144, // futures:uniffi_uniffi_fixture_futures_fn_func_roundtrip_vec - FfiConverterSequenceu32.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustGeometry.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustGeometry.sys.mjs deleted file mode 100644 index 82817ef88ccc..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustGeometry.sys.mjs +++ /dev/null @@ -1,592 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * Line - */ -export class Line { - constructor({ start, end } = { start: undefined, end: undefined }) { - try { - FfiConverterTypePoint.checkType(start) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("start"); - } - throw e; - } - try { - FfiConverterTypePoint.checkType(end) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("end"); - } - throw e; - } - /** - * @type {Point} - */ - this.start = start; - /** - * @type {Point} - */ - this.end = end; - } - - equals(other) { - return ( - this.start.equals(other.start) && - this.end.equals(other.end) - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeLine extends FfiConverterArrayBuffer { - static read(dataStream) { - return new Line({ - start: FfiConverterTypePoint.read(dataStream), - end: FfiConverterTypePoint.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterTypePoint.write(dataStream, value.start); - FfiConverterTypePoint.write(dataStream, value.end); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterTypePoint.computeSize(value.start); - totalSize += FfiConverterTypePoint.computeSize(value.end); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof Line)) { - throw new UniFFITypeError(`Expected 'Line', found '${typeof value}'`); - } - try { - FfiConverterTypePoint.checkType(value.start); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".start"); - } - throw e; - } - try { - FfiConverterTypePoint.checkType(value.end); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".end"); - } - throw e; - } - } -} - -/** - * Point - */ -export class Point { - constructor({ coordX, coordY } = { coordX: undefined, coordY: undefined }) { - try { - FfiConverterF64.checkType(coordX) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("coordX"); - } - throw e; - } - try { - FfiConverterF64.checkType(coordY) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("coordY"); - } - throw e; - } - /** - * @type {number} - */ - this.coordX = coordX; - /** - * @type {number} - */ - this.coordY = coordY; - } - - equals(other) { - return ( - this.coordX == other.coordX && - this.coordY == other.coordY - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypePoint extends FfiConverterArrayBuffer { - static read(dataStream) { - return new Point({ - coordX: FfiConverterF64.read(dataStream), - coordY: FfiConverterF64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterF64.write(dataStream, value.coordX); - FfiConverterF64.write(dataStream, value.coordY); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterF64.computeSize(value.coordX); - totalSize += FfiConverterF64.computeSize(value.coordY); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof Point)) { - throw new UniFFITypeError(`Expected 'Point', found '${typeof value}'`); - } - try { - FfiConverterF64.checkType(value.coordX); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".coordX"); - } - throw e; - } - try { - FfiConverterF64.checkType(value.coordY); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".coordY"); - } - throw e; - } - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypePoint extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypePoint.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypePoint.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypePoint.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypePoint.computeSize(value) - } -} - - - - - -/** - * gradient - * @returns {number} - */ -export function gradient(ln) { - - const liftResult = (result) => FfiConverterF64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeLine.checkType(ln) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ln"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 153, // geometry:uniffi_uniffi_geometry_fn_func_gradient - FfiConverterTypeLine.lower(ln), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * intersection - * @returns {?Point} - */ -export function intersection(ln1,ln2) { - - const liftResult = (result) => FfiConverterOptionalTypePoint.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeLine.checkType(ln1) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ln1"); - } - throw e; - } - try { - FfiConverterTypeLine.checkType(ln2) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("ln2"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 154, // geometry:uniffi_uniffi_geometry_fn_func_intersection - FfiConverterTypeLine.lower(ln1), - FfiConverterTypeLine.lower(ln2), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustRondpoint.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustRondpoint.sys.mjs deleted file mode 100644 index 811d4c55c098..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustRondpoint.sys.mjs +++ /dev/null @@ -1,3814 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } - - // Reads a Optionneur pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerOptionneur() { - const pointerId = 18; // rondpoint:Optionneur - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a Optionneur pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerOptionneur(value) { - const pointerId = 18; // rondpoint:Optionneur - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a Retourneur pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerRetourneur() { - const pointerId = 19; // rondpoint:Retourneur - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a Retourneur pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerRetourneur(value) { - const pointerId = 19; // rondpoint:Retourneur - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - - - // Reads a Stringifier pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerStringifier() { - const pointerId = 20; // rondpoint:Stringifier - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a Stringifier pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerStringifier(value) { - const pointerId = 20; // rondpoint:Stringifier - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterU8 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 256) { - throw new UniFFITypeError(`${value} exceeds the U8 bounds`); - } - } - static computeSize(_value) { - return 1; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint8(value) - } - static read(dataStream) { - return dataStream.readUint8() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI8 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -128 || value > 127) { - throw new UniFFITypeError(`${value} exceeds the I8 bounds`); - } - } - static computeSize(_value) { - return 1; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt8(value) - } - static read(dataStream) { - return dataStream.readInt8() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU16 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 65535) { - throw new UniFFITypeError(`${value} exceeds the U16 bounds`); - } - } - static computeSize(_value) { - return 2; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint16(value) - } - static read(dataStream) { - return dataStream.readUint16() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI16 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -32768 || value > 32767) { - throw new UniFFITypeError(`${value} exceeds the I16 bounds`); - } - } - static computeSize(_value) { - return 2; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt16(value) - } - static read(dataStream) { - return dataStream.readInt16() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint32(value) - } - static read(dataStream) { - return dataStream.readUint32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < -2147483648 || value > 2147483647) { - throw new UniFFITypeError(`${value} exceeds the I32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt32(value) - } - static read(dataStream) { - return dataStream.readInt32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterU64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - if (value < 0) { - throw new UniFFITypeError(`${value} exceeds the U64 bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint64(value) - } - static read(dataStream) { - return dataStream.readUint64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterI64 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isSafeInteger(value)) { - throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); - } - } - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeInt64(value) - } - static read(dataStream) { - return dataStream.readInt64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterF32 extends FfiConverter { - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat32(value) - } - static read(dataStream) { - return dataStream.readFloat32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterBool extends FfiConverter { - static computeSize(_value) { - return 1; - } - static lift(value) { - return value == 1; - } - static lower(value) { - if (value) { - return 1; - } else { - return 0; - } - } - static write(dataStream, value) { - dataStream.writeUint8(this.lower(value)) - } - static read(dataStream) { - return this.lift(dataStream.readUint8()) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * Optionneur - */ -export class Optionneur { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {Optionneur} - */ - static init() { - const liftResult = (result) => FfiConverterTypeOptionneur.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 188, // rondpoint:uniffi_uniffi_rondpoint_fn_constructor_optionneur_new - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * sinonBoolean - * @returns {Boolean} - */ - sinonBoolean(value = false) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterBool.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 163, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_boolean - FfiConverterTypeOptionneur.lower(this), - FfiConverterBool.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonEnum - * @returns {Enumeration} - */ - sinonEnum(value = Enumeration.TROIS) { - const liftResult = (result) => FfiConverterTypeEnumeration.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeEnumeration.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 164, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_enum - FfiConverterTypeOptionneur.lower(this), - FfiConverterTypeEnumeration.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonF32 - * @returns {number} - */ - sinonF32(value = 42.0) { - const liftResult = (result) => FfiConverterF32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 165, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_f32 - FfiConverterTypeOptionneur.lower(this), - FfiConverterF32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonF64 - * @returns {number} - */ - sinonF64(value = 42.1) { - const liftResult = (result) => FfiConverterF64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 166, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_f64 - FfiConverterTypeOptionneur.lower(this), - FfiConverterF64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI16Dec - * @returns {number} - */ - sinonI16Dec(value = 42) { - const liftResult = (result) => FfiConverterI16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 167, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i16_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterI16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI16Hex - * @returns {number} - */ - sinonI16Hex(value = 0x7f) { - const liftResult = (result) => FfiConverterI16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 168, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i16_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterI16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI32Dec - * @returns {number} - */ - sinonI32Dec(value = 42) { - const liftResult = (result) => FfiConverterI32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 169, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i32_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterI32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI32Hex - * @returns {number} - */ - sinonI32Hex(value = 0x7fffffff) { - const liftResult = (result) => FfiConverterI32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 170, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i32_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterI32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI64Dec - * @returns {number} - */ - sinonI64Dec(value = 42) { - const liftResult = (result) => FfiConverterI64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 171, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i64_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterI64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI64Hex - * @returns {number} - */ - sinonI64Hex(value = 0x7fffffffffffffff) { - const liftResult = (result) => FfiConverterI64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 172, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i64_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterI64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI8Dec - * @returns {number} - */ - sinonI8Dec(value = -42) { - const liftResult = (result) => FfiConverterI8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 173, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i8_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterI8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonI8Hex - * @returns {number} - */ - sinonI8Hex(value = -127) { - const liftResult = (result) => FfiConverterI8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 174, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i8_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterI8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonNull - * @returns {?string} - */ - sinonNull(value = null) { - const liftResult = (result) => FfiConverterOptionalstring.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterOptionalstring.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 175, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_null - FfiConverterTypeOptionneur.lower(this), - FfiConverterOptionalstring.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonSequence - * @returns {Array.} - */ - sinonSequence(value = []) { - const liftResult = (result) => FfiConverterSequencestring.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterSequencestring.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 176, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_sequence - FfiConverterTypeOptionneur.lower(this), - FfiConverterSequencestring.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonString - * @returns {string} - */ - sinonString(value = "default") { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 177, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_string - FfiConverterTypeOptionneur.lower(this), - FfiConverterString.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU16Dec - * @returns {number} - */ - sinonU16Dec(value = 42) { - const liftResult = (result) => FfiConverterU16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 178, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u16_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterU16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU16Hex - * @returns {number} - */ - sinonU16Hex(value = 0xffff) { - const liftResult = (result) => FfiConverterU16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 179, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u16_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterU16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU32Dec - * @returns {number} - */ - sinonU32Dec(value = 42) { - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 180, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterU32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU32Hex - * @returns {number} - */ - sinonU32Hex(value = 0xffffffff) { - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 181, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterU32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU32Oct - * @returns {number} - */ - sinonU32Oct(value = 0o755) { - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 182, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_oct - FfiConverterTypeOptionneur.lower(this), - FfiConverterU32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU64Dec - * @returns {number} - */ - sinonU64Dec(value = 42) { - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 183, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u64_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterU64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU64Hex - * @returns {number} - */ - sinonU64Hex(value = 0xffffffffffffffff) { - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 184, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u64_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterU64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU8Dec - * @returns {number} - */ - sinonU8Dec(value = 42) { - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 185, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u8_dec - FfiConverterTypeOptionneur.lower(this), - FfiConverterU8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonU8Hex - * @returns {number} - */ - sinonU8Hex(value = 0xff) { - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 186, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u8_hex - FfiConverterTypeOptionneur.lower(this), - FfiConverterU8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * sinonZero - * @returns {?number} - */ - sinonZero(value = 0) { - const liftResult = (result) => FfiConverterOptionali32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterOptionali32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 187, // rondpoint:uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_zero - FfiConverterTypeOptionneur.lower(this), - FfiConverterOptionali32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeOptionneur extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new Optionneur(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'Optionneur' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerOptionneur()); - } - - static write(dataStream, value) { - dataStream.writePointerOptionneur(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * Retourneur - */ -export class Retourneur { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {Retourneur} - */ - static init() { - const liftResult = (result) => FfiConverterTypeRetourneur.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 204, // rondpoint:uniffi_uniffi_rondpoint_fn_constructor_retourneur_new - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * identiqueBoolean - * @returns {Boolean} - */ - identiqueBoolean(value) { - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterBool.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 189, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_boolean - FfiConverterTypeRetourneur.lower(this), - FfiConverterBool.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueDouble - * @returns {number} - */ - identiqueDouble(value) { - const liftResult = (result) => FfiConverterF64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 190, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_double - FfiConverterTypeRetourneur.lower(this), - FfiConverterF64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueFloat - * @returns {number} - */ - identiqueFloat(value) { - const liftResult = (result) => FfiConverterF32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 191, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_float - FfiConverterTypeRetourneur.lower(this), - FfiConverterF32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueI16 - * @returns {number} - */ - identiqueI16(value) { - const liftResult = (result) => FfiConverterI16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 192, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i16 - FfiConverterTypeRetourneur.lower(this), - FfiConverterI16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueI32 - * @returns {number} - */ - identiqueI32(value) { - const liftResult = (result) => FfiConverterI32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 193, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i32 - FfiConverterTypeRetourneur.lower(this), - FfiConverterI32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueI64 - * @returns {number} - */ - identiqueI64(value) { - const liftResult = (result) => FfiConverterI64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 194, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i64 - FfiConverterTypeRetourneur.lower(this), - FfiConverterI64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueI8 - * @returns {number} - */ - identiqueI8(value) { - const liftResult = (result) => FfiConverterI8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 195, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i8 - FfiConverterTypeRetourneur.lower(this), - FfiConverterI8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueNombres - * @returns {DictionnaireNombres} - */ - identiqueNombres(value) { - const liftResult = (result) => FfiConverterTypeDictionnaireNombres.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeDictionnaireNombres.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 196, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_nombres - FfiConverterTypeRetourneur.lower(this), - FfiConverterTypeDictionnaireNombres.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueNombresSignes - * @returns {DictionnaireNombresSignes} - */ - identiqueNombresSignes(value) { - const liftResult = (result) => FfiConverterTypeDictionnaireNombresSignes.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeDictionnaireNombresSignes.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 197, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_nombres_signes - FfiConverterTypeRetourneur.lower(this), - FfiConverterTypeDictionnaireNombresSignes.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueOptionneurDictionnaire - * @returns {OptionneurDictionnaire} - */ - identiqueOptionneurDictionnaire(value) { - const liftResult = (result) => FfiConverterTypeOptionneurDictionnaire.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeOptionneurDictionnaire.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 198, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_optionneur_dictionnaire - FfiConverterTypeRetourneur.lower(this), - FfiConverterTypeOptionneurDictionnaire.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueString - * @returns {string} - */ - identiqueString(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 199, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_string - FfiConverterTypeRetourneur.lower(this), - FfiConverterString.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueU16 - * @returns {number} - */ - identiqueU16(value) { - const liftResult = (result) => FfiConverterU16.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 200, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u16 - FfiConverterTypeRetourneur.lower(this), - FfiConverterU16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueU32 - * @returns {number} - */ - identiqueU32(value) { - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 201, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u32 - FfiConverterTypeRetourneur.lower(this), - FfiConverterU32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueU64 - * @returns {number} - */ - identiqueU64(value) { - const liftResult = (result) => FfiConverterU64.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 202, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u64 - FfiConverterTypeRetourneur.lower(this), - FfiConverterU64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * identiqueU8 - * @returns {number} - */ - identiqueU8(value) { - const liftResult = (result) => FfiConverterU8.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 203, // rondpoint:uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u8 - FfiConverterTypeRetourneur.lower(this), - FfiConverterU8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeRetourneur extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new Retourneur(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'Retourneur' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerRetourneur()); - } - - static write(dataStream, value) { - dataStream.writePointerRetourneur(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * Stringifier - */ -export class Stringifier { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {Stringifier} - */ - static init() { - const liftResult = (result) => FfiConverterTypeStringifier.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 217, // rondpoint:uniffi_uniffi_rondpoint_fn_constructor_stringifier_new - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * toStringBoolean - * @returns {string} - */ - toStringBoolean(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterBool.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 205, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_boolean - FfiConverterTypeStringifier.lower(this), - FfiConverterBool.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringDouble - * @returns {string} - */ - toStringDouble(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 206, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_double - FfiConverterTypeStringifier.lower(this), - FfiConverterF64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringFloat - * @returns {string} - */ - toStringFloat(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterF32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 207, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_float - FfiConverterTypeStringifier.lower(this), - FfiConverterF32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringI16 - * @returns {string} - */ - toStringI16(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 208, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i16 - FfiConverterTypeStringifier.lower(this), - FfiConverterI16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringI32 - * @returns {string} - */ - toStringI32(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 209, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i32 - FfiConverterTypeStringifier.lower(this), - FfiConverterI32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringI64 - * @returns {string} - */ - toStringI64(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 210, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i64 - FfiConverterTypeStringifier.lower(this), - FfiConverterI64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringI8 - * @returns {string} - */ - toStringI8(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterI8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 211, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i8 - FfiConverterTypeStringifier.lower(this), - FfiConverterI8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringU16 - * @returns {string} - */ - toStringU16(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU16.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 212, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u16 - FfiConverterTypeStringifier.lower(this), - FfiConverterU16.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringU32 - * @returns {string} - */ - toStringU32(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 213, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u32 - FfiConverterTypeStringifier.lower(this), - FfiConverterU32.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringU64 - * @returns {string} - */ - toStringU64(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU64.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 214, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u64 - FfiConverterTypeStringifier.lower(this), - FfiConverterU64.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * toStringU8 - * @returns {string} - */ - toStringU8(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU8.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 215, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u8 - FfiConverterTypeStringifier.lower(this), - FfiConverterU8.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * wellKnownString - * @returns {string} - */ - wellKnownString(value) { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterString.checkType(value) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("value"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 216, // rondpoint:uniffi_uniffi_rondpoint_fn_method_stringifier_well_known_string - FfiConverterTypeStringifier.lower(this), - FfiConverterString.lower(value), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeStringifier extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new Stringifier(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'Stringifier' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerStringifier()); - } - - static write(dataStream, value) { - dataStream.writePointerStringifier(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * Dictionnaire - */ -export class Dictionnaire { - constructor({ un, deux, petitNombre, grosNombre } = { un: undefined, deux: undefined, petitNombre: undefined, grosNombre: undefined }) { - try { - FfiConverterTypeEnumeration.checkType(un) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("un"); - } - throw e; - } - try { - FfiConverterBool.checkType(deux) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("deux"); - } - throw e; - } - try { - FfiConverterU8.checkType(petitNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("petitNombre"); - } - throw e; - } - try { - FfiConverterU64.checkType(grosNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("grosNombre"); - } - throw e; - } - /** - * @type {Enumeration} - */ - this.un = un; - /** - * @type {Boolean} - */ - this.deux = deux; - /** - * @type {number} - */ - this.petitNombre = petitNombre; - /** - * @type {number} - */ - this.grosNombre = grosNombre; - } - - equals(other) { - return ( - this.un == other.un && - this.deux == other.deux && - this.petitNombre == other.petitNombre && - this.grosNombre == other.grosNombre - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeDictionnaire extends FfiConverterArrayBuffer { - static read(dataStream) { - return new Dictionnaire({ - un: FfiConverterTypeEnumeration.read(dataStream), - deux: FfiConverterBool.read(dataStream), - petitNombre: FfiConverterU8.read(dataStream), - grosNombre: FfiConverterU64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterTypeEnumeration.write(dataStream, value.un); - FfiConverterBool.write(dataStream, value.deux); - FfiConverterU8.write(dataStream, value.petitNombre); - FfiConverterU64.write(dataStream, value.grosNombre); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterTypeEnumeration.computeSize(value.un); - totalSize += FfiConverterBool.computeSize(value.deux); - totalSize += FfiConverterU8.computeSize(value.petitNombre); - totalSize += FfiConverterU64.computeSize(value.grosNombre); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof Dictionnaire)) { - throw new UniFFITypeError(`Expected 'Dictionnaire', found '${typeof value}'`); - } - try { - FfiConverterTypeEnumeration.checkType(value.un); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".un"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.deux); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".deux"); - } - throw e; - } - try { - FfiConverterU8.checkType(value.petitNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".petitNombre"); - } - throw e; - } - try { - FfiConverterU64.checkType(value.grosNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".grosNombre"); - } - throw e; - } - } -} - -/** - * DictionnaireNombres - */ -export class DictionnaireNombres { - constructor({ petitNombre, courtNombre, nombreSimple, grosNombre } = { petitNombre: undefined, courtNombre: undefined, nombreSimple: undefined, grosNombre: undefined }) { - try { - FfiConverterU8.checkType(petitNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("petitNombre"); - } - throw e; - } - try { - FfiConverterU16.checkType(courtNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("courtNombre"); - } - throw e; - } - try { - FfiConverterU32.checkType(nombreSimple) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("nombreSimple"); - } - throw e; - } - try { - FfiConverterU64.checkType(grosNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("grosNombre"); - } - throw e; - } - /** - * @type {number} - */ - this.petitNombre = petitNombre; - /** - * @type {number} - */ - this.courtNombre = courtNombre; - /** - * @type {number} - */ - this.nombreSimple = nombreSimple; - /** - * @type {number} - */ - this.grosNombre = grosNombre; - } - - equals(other) { - return ( - this.petitNombre == other.petitNombre && - this.courtNombre == other.courtNombre && - this.nombreSimple == other.nombreSimple && - this.grosNombre == other.grosNombre - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeDictionnaireNombres extends FfiConverterArrayBuffer { - static read(dataStream) { - return new DictionnaireNombres({ - petitNombre: FfiConverterU8.read(dataStream), - courtNombre: FfiConverterU16.read(dataStream), - nombreSimple: FfiConverterU32.read(dataStream), - grosNombre: FfiConverterU64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterU8.write(dataStream, value.petitNombre); - FfiConverterU16.write(dataStream, value.courtNombre); - FfiConverterU32.write(dataStream, value.nombreSimple); - FfiConverterU64.write(dataStream, value.grosNombre); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterU8.computeSize(value.petitNombre); - totalSize += FfiConverterU16.computeSize(value.courtNombre); - totalSize += FfiConverterU32.computeSize(value.nombreSimple); - totalSize += FfiConverterU64.computeSize(value.grosNombre); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof DictionnaireNombres)) { - throw new UniFFITypeError(`Expected 'DictionnaireNombres', found '${typeof value}'`); - } - try { - FfiConverterU8.checkType(value.petitNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".petitNombre"); - } - throw e; - } - try { - FfiConverterU16.checkType(value.courtNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".courtNombre"); - } - throw e; - } - try { - FfiConverterU32.checkType(value.nombreSimple); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".nombreSimple"); - } - throw e; - } - try { - FfiConverterU64.checkType(value.grosNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".grosNombre"); - } - throw e; - } - } -} - -/** - * DictionnaireNombresSignes - */ -export class DictionnaireNombresSignes { - constructor({ petitNombre, courtNombre, nombreSimple, grosNombre } = { petitNombre: undefined, courtNombre: undefined, nombreSimple: undefined, grosNombre: undefined }) { - try { - FfiConverterI8.checkType(petitNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("petitNombre"); - } - throw e; - } - try { - FfiConverterI16.checkType(courtNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("courtNombre"); - } - throw e; - } - try { - FfiConverterI32.checkType(nombreSimple) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("nombreSimple"); - } - throw e; - } - try { - FfiConverterI64.checkType(grosNombre) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("grosNombre"); - } - throw e; - } - /** - * @type {number} - */ - this.petitNombre = petitNombre; - /** - * @type {number} - */ - this.courtNombre = courtNombre; - /** - * @type {number} - */ - this.nombreSimple = nombreSimple; - /** - * @type {number} - */ - this.grosNombre = grosNombre; - } - - equals(other) { - return ( - this.petitNombre == other.petitNombre && - this.courtNombre == other.courtNombre && - this.nombreSimple == other.nombreSimple && - this.grosNombre == other.grosNombre - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeDictionnaireNombresSignes extends FfiConverterArrayBuffer { - static read(dataStream) { - return new DictionnaireNombresSignes({ - petitNombre: FfiConverterI8.read(dataStream), - courtNombre: FfiConverterI16.read(dataStream), - nombreSimple: FfiConverterI32.read(dataStream), - grosNombre: FfiConverterI64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterI8.write(dataStream, value.petitNombre); - FfiConverterI16.write(dataStream, value.courtNombre); - FfiConverterI32.write(dataStream, value.nombreSimple); - FfiConverterI64.write(dataStream, value.grosNombre); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterI8.computeSize(value.petitNombre); - totalSize += FfiConverterI16.computeSize(value.courtNombre); - totalSize += FfiConverterI32.computeSize(value.nombreSimple); - totalSize += FfiConverterI64.computeSize(value.grosNombre); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof DictionnaireNombresSignes)) { - throw new UniFFITypeError(`Expected 'DictionnaireNombresSignes', found '${typeof value}'`); - } - try { - FfiConverterI8.checkType(value.petitNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".petitNombre"); - } - throw e; - } - try { - FfiConverterI16.checkType(value.courtNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".courtNombre"); - } - throw e; - } - try { - FfiConverterI32.checkType(value.nombreSimple); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".nombreSimple"); - } - throw e; - } - try { - FfiConverterI64.checkType(value.grosNombre); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".grosNombre"); - } - throw e; - } - } -} - -/** - * OptionneurDictionnaire - */ -export class OptionneurDictionnaire { - constructor({ i8Var = -8, u8Var = 8, i16Var = -16, u16Var = 0x10, i32Var = -32, u32Var = 32, i64Var = -64, u64Var = 64, floatVar = 4.0, doubleVar = 8.0, booleanVar = true, stringVar = "default", listVar = [], enumerationVar = Enumeration.DEUX, dictionnaireVar = null } = { i8Var: undefined, u8Var: undefined, i16Var: undefined, u16Var: undefined, i32Var: undefined, u32Var: undefined, i64Var: undefined, u64Var: undefined, floatVar: undefined, doubleVar: undefined, booleanVar: undefined, stringVar: undefined, listVar: undefined, enumerationVar: undefined, dictionnaireVar: undefined }) { - try { - FfiConverterI8.checkType(i8Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("i8Var"); - } - throw e; - } - try { - FfiConverterU8.checkType(u8Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("u8Var"); - } - throw e; - } - try { - FfiConverterI16.checkType(i16Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("i16Var"); - } - throw e; - } - try { - FfiConverterU16.checkType(u16Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("u16Var"); - } - throw e; - } - try { - FfiConverterI32.checkType(i32Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("i32Var"); - } - throw e; - } - try { - FfiConverterU32.checkType(u32Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("u32Var"); - } - throw e; - } - try { - FfiConverterI64.checkType(i64Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("i64Var"); - } - throw e; - } - try { - FfiConverterU64.checkType(u64Var) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("u64Var"); - } - throw e; - } - try { - FfiConverterF32.checkType(floatVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("floatVar"); - } - throw e; - } - try { - FfiConverterF64.checkType(doubleVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("doubleVar"); - } - throw e; - } - try { - FfiConverterBool.checkType(booleanVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("booleanVar"); - } - throw e; - } - try { - FfiConverterString.checkType(stringVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("stringVar"); - } - throw e; - } - try { - FfiConverterSequencestring.checkType(listVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("listVar"); - } - throw e; - } - try { - FfiConverterTypeEnumeration.checkType(enumerationVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("enumerationVar"); - } - throw e; - } - try { - FfiConverterOptionalTypeminusculeMajusculeEnum.checkType(dictionnaireVar) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("dictionnaireVar"); - } - throw e; - } - /** - * @type {number} - */ - this.i8Var = i8Var; - /** - * @type {number} - */ - this.u8Var = u8Var; - /** - * @type {number} - */ - this.i16Var = i16Var; - /** - * @type {number} - */ - this.u16Var = u16Var; - /** - * @type {number} - */ - this.i32Var = i32Var; - /** - * @type {number} - */ - this.u32Var = u32Var; - /** - * @type {number} - */ - this.i64Var = i64Var; - /** - * @type {number} - */ - this.u64Var = u64Var; - /** - * @type {number} - */ - this.floatVar = floatVar; - /** - * @type {number} - */ - this.doubleVar = doubleVar; - /** - * @type {Boolean} - */ - this.booleanVar = booleanVar; - /** - * @type {string} - */ - this.stringVar = stringVar; - /** - * @type {Array.} - */ - this.listVar = listVar; - /** - * @type {Enumeration} - */ - this.enumerationVar = enumerationVar; - /** - * @type {?MinusculeMajusculeEnum} - */ - this.dictionnaireVar = dictionnaireVar; - } - - equals(other) { - return ( - this.i8Var == other.i8Var && - this.u8Var == other.u8Var && - this.i16Var == other.i16Var && - this.u16Var == other.u16Var && - this.i32Var == other.i32Var && - this.u32Var == other.u32Var && - this.i64Var == other.i64Var && - this.u64Var == other.u64Var && - this.floatVar == other.floatVar && - this.doubleVar == other.doubleVar && - this.booleanVar == other.booleanVar && - this.stringVar == other.stringVar && - this.listVar == other.listVar && - this.enumerationVar == other.enumerationVar && - this.dictionnaireVar == other.dictionnaireVar - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeOptionneurDictionnaire extends FfiConverterArrayBuffer { - static read(dataStream) { - return new OptionneurDictionnaire({ - i8Var: FfiConverterI8.read(dataStream), - u8Var: FfiConverterU8.read(dataStream), - i16Var: FfiConverterI16.read(dataStream), - u16Var: FfiConverterU16.read(dataStream), - i32Var: FfiConverterI32.read(dataStream), - u32Var: FfiConverterU32.read(dataStream), - i64Var: FfiConverterI64.read(dataStream), - u64Var: FfiConverterU64.read(dataStream), - floatVar: FfiConverterF32.read(dataStream), - doubleVar: FfiConverterF64.read(dataStream), - booleanVar: FfiConverterBool.read(dataStream), - stringVar: FfiConverterString.read(dataStream), - listVar: FfiConverterSequencestring.read(dataStream), - enumerationVar: FfiConverterTypeEnumeration.read(dataStream), - dictionnaireVar: FfiConverterOptionalTypeminusculeMajusculeEnum.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterI8.write(dataStream, value.i8Var); - FfiConverterU8.write(dataStream, value.u8Var); - FfiConverterI16.write(dataStream, value.i16Var); - FfiConverterU16.write(dataStream, value.u16Var); - FfiConverterI32.write(dataStream, value.i32Var); - FfiConverterU32.write(dataStream, value.u32Var); - FfiConverterI64.write(dataStream, value.i64Var); - FfiConverterU64.write(dataStream, value.u64Var); - FfiConverterF32.write(dataStream, value.floatVar); - FfiConverterF64.write(dataStream, value.doubleVar); - FfiConverterBool.write(dataStream, value.booleanVar); - FfiConverterString.write(dataStream, value.stringVar); - FfiConverterSequencestring.write(dataStream, value.listVar); - FfiConverterTypeEnumeration.write(dataStream, value.enumerationVar); - FfiConverterOptionalTypeminusculeMajusculeEnum.write(dataStream, value.dictionnaireVar); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterI8.computeSize(value.i8Var); - totalSize += FfiConverterU8.computeSize(value.u8Var); - totalSize += FfiConverterI16.computeSize(value.i16Var); - totalSize += FfiConverterU16.computeSize(value.u16Var); - totalSize += FfiConverterI32.computeSize(value.i32Var); - totalSize += FfiConverterU32.computeSize(value.u32Var); - totalSize += FfiConverterI64.computeSize(value.i64Var); - totalSize += FfiConverterU64.computeSize(value.u64Var); - totalSize += FfiConverterF32.computeSize(value.floatVar); - totalSize += FfiConverterF64.computeSize(value.doubleVar); - totalSize += FfiConverterBool.computeSize(value.booleanVar); - totalSize += FfiConverterString.computeSize(value.stringVar); - totalSize += FfiConverterSequencestring.computeSize(value.listVar); - totalSize += FfiConverterTypeEnumeration.computeSize(value.enumerationVar); - totalSize += FfiConverterOptionalTypeminusculeMajusculeEnum.computeSize(value.dictionnaireVar); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof OptionneurDictionnaire)) { - throw new UniFFITypeError(`Expected 'OptionneurDictionnaire', found '${typeof value}'`); - } - try { - FfiConverterI8.checkType(value.i8Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".i8Var"); - } - throw e; - } - try { - FfiConverterU8.checkType(value.u8Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".u8Var"); - } - throw e; - } - try { - FfiConverterI16.checkType(value.i16Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".i16Var"); - } - throw e; - } - try { - FfiConverterU16.checkType(value.u16Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".u16Var"); - } - throw e; - } - try { - FfiConverterI32.checkType(value.i32Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".i32Var"); - } - throw e; - } - try { - FfiConverterU32.checkType(value.u32Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".u32Var"); - } - throw e; - } - try { - FfiConverterI64.checkType(value.i64Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".i64Var"); - } - throw e; - } - try { - FfiConverterU64.checkType(value.u64Var); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".u64Var"); - } - throw e; - } - try { - FfiConverterF32.checkType(value.floatVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".floatVar"); - } - throw e; - } - try { - FfiConverterF64.checkType(value.doubleVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".doubleVar"); - } - throw e; - } - try { - FfiConverterBool.checkType(value.booleanVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".booleanVar"); - } - throw e; - } - try { - FfiConverterString.checkType(value.stringVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".stringVar"); - } - throw e; - } - try { - FfiConverterSequencestring.checkType(value.listVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".listVar"); - } - throw e; - } - try { - FfiConverterTypeEnumeration.checkType(value.enumerationVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".enumerationVar"); - } - throw e; - } - try { - FfiConverterOptionalTypeminusculeMajusculeEnum.checkType(value.dictionnaireVar); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".dictionnaireVar"); - } - throw e; - } - } -} - -/** - * MinusculeMajusculeDict - */ -export class MinusculeMajusculeDict { - constructor({ minusculeMajusculeField } = { minusculeMajusculeField: undefined }) { - try { - FfiConverterBool.checkType(minusculeMajusculeField) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("minusculeMajusculeField"); - } - throw e; - } - /** - * @type {Boolean} - */ - this.minusculeMajusculeField = minusculeMajusculeField; - } - - equals(other) { - return ( - this.minusculeMajusculeField == other.minusculeMajusculeField - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeminusculeMajusculeDict extends FfiConverterArrayBuffer { - static read(dataStream) { - return new MinusculeMajusculeDict({ - minusculeMajusculeField: FfiConverterBool.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterBool.write(dataStream, value.minusculeMajusculeField); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterBool.computeSize(value.minusculeMajusculeField); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof MinusculeMajusculeDict)) { - throw new UniFFITypeError(`Expected 'MinusculeMajusculeDict', found '${typeof value}'`); - } - try { - FfiConverterBool.checkType(value.minusculeMajusculeField); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".minusculeMajusculeField"); - } - throw e; - } - } -} - - -/** - * Enumeration - */ -export const Enumeration = { - /** - * UN - */ - UN:0, - /** - * DEUX - */ - DEUX:1, - /** - * TROIS - */ - TROIS:2, -}; - -Object.freeze(Enumeration); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeEnumeration extends FfiConverterArrayBuffer { - static #validValues = Object.values(Enumeration); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return Enumeration.UN - case 2: - return Enumeration.DEUX - case 3: - return Enumeration.TROIS - default: - throw new UniFFITypeError("Unknown Enumeration variant"); - } - } - - static write(dataStream, value) { - if (value === Enumeration.UN) { - dataStream.writeInt32(1); - return; - } - if (value === Enumeration.DEUX) { - dataStream.writeInt32(2); - return; - } - if (value === Enumeration.TROIS) { - dataStream.writeInt32(3); - return; - } - throw new UniFFITypeError("Unknown Enumeration variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for Enumeration`); - } - } -} - - - -/** - * EnumerationAvecDonnees - */ -export class EnumerationAvecDonnees {} -/** - * Zero - */ -EnumerationAvecDonnees.Zero = class extends EnumerationAvecDonnees{ - constructor( - ) { - super(); - } -} -/** - * Un - */ -EnumerationAvecDonnees.Un = class extends EnumerationAvecDonnees{ - constructor( - premier - ) { - super(); - this.premier = premier; - } -} -/** - * Deux - */ -EnumerationAvecDonnees.Deux = class extends EnumerationAvecDonnees{ - constructor( - premier, - second - ) { - super(); - this.premier = premier; - this.second = second; - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeEnumerationAvecDonnees extends FfiConverterArrayBuffer { - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return new EnumerationAvecDonnees.Zero( - ); - case 2: - return new EnumerationAvecDonnees.Un( - FfiConverterU32.read(dataStream) - ); - case 3: - return new EnumerationAvecDonnees.Deux( - FfiConverterU32.read(dataStream), - FfiConverterString.read(dataStream) - ); - default: - throw new UniFFITypeError("Unknown EnumerationAvecDonnees variant"); - } - } - - static write(dataStream, value) { - if (value instanceof EnumerationAvecDonnees.Zero) { - dataStream.writeInt32(1); - return; - } - if (value instanceof EnumerationAvecDonnees.Un) { - dataStream.writeInt32(2); - FfiConverterU32.write(dataStream, value.premier); - return; - } - if (value instanceof EnumerationAvecDonnees.Deux) { - dataStream.writeInt32(3); - FfiConverterU32.write(dataStream, value.premier); - FfiConverterString.write(dataStream, value.second); - return; - } - throw new UniFFITypeError("Unknown EnumerationAvecDonnees variant"); - } - - static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof EnumerationAvecDonnees.Zero) { - return totalSize; - } - if (value instanceof EnumerationAvecDonnees.Un) { - totalSize += FfiConverterU32.computeSize(value.premier); - return totalSize; - } - if (value instanceof EnumerationAvecDonnees.Deux) { - totalSize += FfiConverterU32.computeSize(value.premier); - totalSize += FfiConverterString.computeSize(value.second); - return totalSize; - } - throw new UniFFITypeError("Unknown EnumerationAvecDonnees variant"); - } - - static checkType(value) { - if (value === undefined || value === null || !(value instanceof EnumerationAvecDonnees)) { - throw new UniFFITypeError(`${value} is not a subclass instance of EnumerationAvecDonnees`); - } - } -} - - - -/** - * MinusculeMajusculeEnum - */ -export const MinusculeMajusculeEnum = { - /** - * MINUSCULE_MAJUSCULE_VARIANT - */ - MINUSCULE_MAJUSCULE_VARIANT:0, -}; - -Object.freeze(MinusculeMajusculeEnum); -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeminusculeMajusculeEnum extends FfiConverterArrayBuffer { - static #validValues = Object.values(MinusculeMajusculeEnum); - - static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings - switch (dataStream.readInt32()) { - case 1: - return MinusculeMajusculeEnum.MINUSCULE_MAJUSCULE_VARIANT - default: - throw new UniFFITypeError("Unknown MinusculeMajusculeEnum variant"); - } - } - - static write(dataStream, value) { - if (value === MinusculeMajusculeEnum.MINUSCULE_MAJUSCULE_VARIANT) { - dataStream.writeInt32(1); - return; - } - throw new UniFFITypeError("Unknown MinusculeMajusculeEnum variant"); - } - - static computeSize(value) { - return 4; - } - - static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for MinusculeMajusculeEnum`); - } - } -} - - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionali32 extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterI32.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterI32.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterI32.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterI32.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalstring extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterString.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterString.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterString.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterString.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeminusculeMajusculeEnum extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeminusculeMajusculeEnum.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeminusculeMajusculeEnum.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeminusculeMajusculeEnum.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeminusculeMajusculeEnum.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterString.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterString.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterString.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterString.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeEnumeration extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeEnumeration.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeEnumeration.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeEnumeration.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeEnumeration.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterMapStringTypeEnumerationAvecDonnees extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const map = new Map(); - for (let i = 0; i < len; i++) { - const key = FfiConverterString.read(dataStream); - const value = FfiConverterTypeEnumerationAvecDonnees.read(dataStream); - map.set(key, value); - } - - return map; - } - - static write(dataStream, map) { - dataStream.writeInt32(map.size); - for (const [key, value] of map) { - FfiConverterString.write(dataStream, key); - FfiConverterTypeEnumerationAvecDonnees.write(dataStream, value); - } - } - - static computeSize(map) { - // The size of the length - let size = 4; - for (const [key, value] of map) { - size += FfiConverterString.computeSize(key); - size += FfiConverterTypeEnumerationAvecDonnees.computeSize(value); - } - return size; - } - - static checkType(map) { - for (const [key, value] of map) { - try { - FfiConverterString.checkType(key); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("(key)"); - } - throw e; - } - - try { - FfiConverterTypeEnumerationAvecDonnees.checkType(value); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${key}]`); - } - throw e; - } - } - } -} - - - - - -/** - * copieCarte - * @returns {object} - */ -export function copieCarte(c) { - - const liftResult = (result) => FfiConverterMapStringTypeEnumerationAvecDonnees.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterMapStringTypeEnumerationAvecDonnees.checkType(c) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("c"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 158, // rondpoint:uniffi_uniffi_rondpoint_fn_func_copie_carte - FfiConverterMapStringTypeEnumerationAvecDonnees.lower(c), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * copieDictionnaire - * @returns {Dictionnaire} - */ -export function copieDictionnaire(d) { - - const liftResult = (result) => FfiConverterTypeDictionnaire.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeDictionnaire.checkType(d) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("d"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 159, // rondpoint:uniffi_uniffi_rondpoint_fn_func_copie_dictionnaire - FfiConverterTypeDictionnaire.lower(d), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * copieEnumeration - * @returns {Enumeration} - */ -export function copieEnumeration(e) { - - const liftResult = (result) => FfiConverterTypeEnumeration.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeEnumeration.checkType(e) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("e"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 160, // rondpoint:uniffi_uniffi_rondpoint_fn_func_copie_enumeration - FfiConverterTypeEnumeration.lower(e), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * copieEnumerations - * @returns {Array.} - */ -export function copieEnumerations(e) { - - const liftResult = (result) => FfiConverterSequenceTypeEnumeration.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterSequenceTypeEnumeration.checkType(e) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("e"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 161, // rondpoint:uniffi_uniffi_rondpoint_fn_func_copie_enumerations - FfiConverterSequenceTypeEnumeration.lower(e), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * switcheroo - * @returns {Boolean} - */ -export function switcheroo(b) { - - const liftResult = (result) => FfiConverterBool.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterBool.checkType(b) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("b"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 162, // rondpoint:uniffi_uniffi_rondpoint_fn_func_switcheroo - FfiConverterBool.lower(b), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustSprites.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustSprites.sys.mjs deleted file mode 100644 index 327b33a6861d..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustSprites.sys.mjs +++ /dev/null @@ -1,768 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } - - // Reads a Sprite pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerSprite() { - const pointerId = 21; // sprites:Sprite - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a Sprite pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerSprite(value) { - const pointerId = 21; // sprites:Sprite - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterF64 extends FfiConverter { - static computeSize(_value) { - return 8; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeFloat64(value) - } - static read(dataStream) { - return dataStream.readFloat64() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * Sprite - */ -export class Sprite { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {Sprite} - */ - static init(initialPosition) { - const liftResult = (result) => FfiConverterTypeSprite.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterOptionalTypePoint.checkType(initialPosition) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("initialPosition"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 222, // sprites:uniffi_uniffi_sprites_fn_constructor_sprite_new - FfiConverterOptionalTypePoint.lower(initialPosition), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - /** - * newRelativeTo - * @returns {Sprite} - */ - static newRelativeTo(reference,direction) { - const liftResult = (result) => FfiConverterTypeSprite.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypePoint.checkType(reference) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("reference"); - } - throw e; - } - try { - FfiConverterTypeVector.checkType(direction) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("direction"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 223, // sprites:uniffi_uniffi_sprites_fn_constructor_sprite_new_relative_to - FfiConverterTypePoint.lower(reference), - FfiConverterTypeVector.lower(direction), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * getPosition - * @returns {Point} - */ - getPosition() { - const liftResult = (result) => FfiConverterTypePoint.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 219, // sprites:uniffi_uniffi_sprites_fn_method_sprite_get_position - FfiConverterTypeSprite.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * moveBy - */ - moveBy(direction) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeVector.checkType(direction) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("direction"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 220, // sprites:uniffi_uniffi_sprites_fn_method_sprite_move_by - FfiConverterTypeSprite.lower(this), - FfiConverterTypeVector.lower(direction), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * moveTo - */ - moveTo(position) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypePoint.checkType(position) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("position"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 221, // sprites:uniffi_uniffi_sprites_fn_method_sprite_move_to - FfiConverterTypeSprite.lower(this), - FfiConverterTypePoint.lower(position), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSprite extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new Sprite(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'Sprite' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerSprite()); - } - - static write(dataStream, value) { - dataStream.writePointerSprite(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * Point - */ -export class Point { - constructor({ x, y } = { x: undefined, y: undefined }) { - try { - FfiConverterF64.checkType(x) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("x"); - } - throw e; - } - try { - FfiConverterF64.checkType(y) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("y"); - } - throw e; - } - /** - * @type {number} - */ - this.x = x; - /** - * @type {number} - */ - this.y = y; - } - - equals(other) { - return ( - this.x == other.x && - this.y == other.y - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypePoint extends FfiConverterArrayBuffer { - static read(dataStream) { - return new Point({ - x: FfiConverterF64.read(dataStream), - y: FfiConverterF64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterF64.write(dataStream, value.x); - FfiConverterF64.write(dataStream, value.y); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterF64.computeSize(value.x); - totalSize += FfiConverterF64.computeSize(value.y); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof Point)) { - throw new UniFFITypeError(`Expected 'Point', found '${typeof value}'`); - } - try { - FfiConverterF64.checkType(value.x); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".x"); - } - throw e; - } - try { - FfiConverterF64.checkType(value.y); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".y"); - } - throw e; - } - } -} - -/** - * Vector - */ -export class Vector { - constructor({ dx, dy } = { dx: undefined, dy: undefined }) { - try { - FfiConverterF64.checkType(dx) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("dx"); - } - throw e; - } - try { - FfiConverterF64.checkType(dy) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("dy"); - } - throw e; - } - /** - * @type {number} - */ - this.dx = dx; - /** - * @type {number} - */ - this.dy = dy; - } - - equals(other) { - return ( - this.dx == other.dx && - this.dy == other.dy - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeVector extends FfiConverterArrayBuffer { - static read(dataStream) { - return new Vector({ - dx: FfiConverterF64.read(dataStream), - dy: FfiConverterF64.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterF64.write(dataStream, value.dx); - FfiConverterF64.write(dataStream, value.dy); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterF64.computeSize(value.dx); - totalSize += FfiConverterF64.computeSize(value.dy); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof Vector)) { - throw new UniFFITypeError(`Expected 'Vector', found '${typeof value}'`); - } - try { - FfiConverterF64.checkType(value.dx); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".dx"); - } - throw e; - } - try { - FfiConverterF64.checkType(value.dy); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".dy"); - } - throw e; - } - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypePoint extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypePoint.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypePoint.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypePoint.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypePoint.computeSize(value) - } -} - - - - - -/** - * translate - * @returns {Point} - */ -export function translate(p,v) { - - const liftResult = (result) => FfiConverterTypePoint.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypePoint.checkType(p) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("p"); - } - throw e; - } - try { - FfiConverterTypeVector.checkType(v) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("v"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 218, // sprites:uniffi_uniffi_sprites_fn_func_translate - FfiConverterTypePoint.lower(p), - FfiConverterTypeVector.lower(v), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustTodolist.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustTodolist.sys.mjs deleted file mode 100644 index 85ef746b242e..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustTodolist.sys.mjs +++ /dev/null @@ -1,1052 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } - - // Reads a TodoList pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerTodoList() { - const pointerId = 22; // todolist:TodoList - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a TodoList pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerTodoList(value) { - const pointerId = 22; // todolist:TodoList - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * TodoList - */ -export class TodoList { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - /** - * init - * @returns {TodoList} - */ - static init() { - const liftResult = (result) => FfiConverterTypeTodoList.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 238, // todolist:uniffi_uniffi_todolist_fn_constructor_todolist_new - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - }} - - /** - * addEntries - */ - addEntries(entries) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterSequenceTypeTodoEntry.checkType(entries) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("entries"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 227, // todolist:uniffi_uniffi_todolist_fn_method_todolist_add_entries - FfiConverterTypeTodoList.lower(this), - FfiConverterSequenceTypeTodoEntry.lower(entries), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * addEntry - */ - addEntry(entry) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - try { - FfiConverterTypeTodoEntry.checkType(entry) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("entry"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 228, // todolist:uniffi_uniffi_todolist_fn_method_todolist_add_entry - FfiConverterTypeTodoList.lower(this), - FfiConverterTypeTodoEntry.lower(entry), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * addItem - */ - addItem(todo) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(todo) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("todo"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 229, // todolist:uniffi_uniffi_todolist_fn_method_todolist_add_item - FfiConverterTypeTodoList.lower(this), - FfiConverterString.lower(todo), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * addItems - */ - addItems(items) { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterSequencestring.checkType(items) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("items"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 230, // todolist:uniffi_uniffi_todolist_fn_method_todolist_add_items - FfiConverterTypeTodoList.lower(this), - FfiConverterSequencestring.lower(items), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * clearItem - */ - clearItem(todo) { - const liftResult = (result) => undefined; - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(todo) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("todo"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 231, // todolist:uniffi_uniffi_todolist_fn_method_todolist_clear_item - FfiConverterTypeTodoList.lower(this), - FfiConverterString.lower(todo), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getEntries - * @returns {Array.} - */ - getEntries() { - const liftResult = (result) => FfiConverterSequenceTypeTodoEntry.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 232, // todolist:uniffi_uniffi_todolist_fn_method_todolist_get_entries - FfiConverterTypeTodoList.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getFirst - * @returns {string} - */ - getFirst() { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 233, // todolist:uniffi_uniffi_todolist_fn_method_todolist_get_first - FfiConverterTypeTodoList.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getItems - * @returns {Array.} - */ - getItems() { - const liftResult = (result) => FfiConverterSequencestring.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 234, // todolist:uniffi_uniffi_todolist_fn_method_todolist_get_items - FfiConverterTypeTodoList.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getLast - * @returns {string} - */ - getLast() { - const liftResult = (result) => FfiConverterString.lift(result); - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 235, // todolist:uniffi_uniffi_todolist_fn_method_todolist_get_last - FfiConverterTypeTodoList.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * getLastEntry - * @returns {TodoEntry} - */ - getLastEntry() { - const liftResult = (result) => FfiConverterTypeTodoEntry.lift(result); - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 236, // todolist:uniffi_uniffi_todolist_fn_method_todolist_get_last_entry - FfiConverterTypeTodoList.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - - /** - * makeDefault - */ - makeDefault() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 237, // todolist:uniffi_uniffi_todolist_fn_method_todolist_make_default - FfiConverterTypeTodoList.lower(this), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeTodoList extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new TodoList(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'TodoList' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerTodoList()); - } - - static write(dataStream, value) { - dataStream.writePointerTodoList(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - -/** - * TodoEntry - */ -export class TodoEntry { - constructor({ text } = { text: undefined }) { - try { - FfiConverterString.checkType(text) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("text"); - } - throw e; - } - /** - * @type {string} - */ - this.text = text; - } - - equals(other) { - return ( - this.text == other.text - ) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeTodoEntry extends FfiConverterArrayBuffer { - static read(dataStream) { - return new TodoEntry({ - text: FfiConverterString.read(dataStream), - }); - } - static write(dataStream, value) { - FfiConverterString.write(dataStream, value.text); - } - - static computeSize(value) { - let totalSize = 0; - totalSize += FfiConverterString.computeSize(value.text); - return totalSize - } - - static checkType(value) { - super.checkType(value); - if (!(value instanceof TodoEntry)) { - throw new UniFFITypeError(`Expected 'TodoEntry', found '${typeof value}'`); - } - try { - FfiConverterString.checkType(value.text); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".text"); - } - throw e; - } - } -} - - - - -/** - * TodoError - */ -export class TodoError extends Error {} - - -/** - * TODO_DOES_NOT_EXIST - */ -export class TodoDoesNotExist extends TodoError { - - constructor(message, ...params) { - super(...params); - this.message = message; - } - toString() { - return `TodoDoesNotExist: ${super.toString()}` - } -} - -/** - * EMPTY_TODO_LIST - */ -export class EmptyTodoList extends TodoError { - - constructor(message, ...params) { - super(...params); - this.message = message; - } - toString() { - return `EmptyTodoList: ${super.toString()}` - } -} - -/** - * DUPLICATE_TODO - */ -export class DuplicateTodo extends TodoError { - - constructor(message, ...params) { - super(...params); - this.message = message; - } - toString() { - return `DuplicateTodo: ${super.toString()}` - } -} - -/** - * EMPTY_STRING - */ -export class EmptyString extends TodoError { - - constructor(message, ...params) { - super(...params); - this.message = message; - } - toString() { - return `EmptyString: ${super.toString()}` - } -} - -/** - * DELIGATED_ERROR - */ -export class DeligatedError extends TodoError { - - constructor(message, ...params) { - super(...params); - this.message = message; - } - toString() { - return `DeligatedError: ${super.toString()}` - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeTodoError extends FfiConverterArrayBuffer { - static read(dataStream) { - switch (dataStream.readInt32()) { - case 1: - return new TodoDoesNotExist(FfiConverterString.read(dataStream)); - case 2: - return new EmptyTodoList(FfiConverterString.read(dataStream)); - case 3: - return new DuplicateTodo(FfiConverterString.read(dataStream)); - case 4: - return new EmptyString(FfiConverterString.read(dataStream)); - case 5: - return new DeligatedError(FfiConverterString.read(dataStream)); - default: - throw new UniFFITypeError("Unknown TodoError variant"); - } - } - static computeSize(value) { - // Size of the Int indicating the variant - let totalSize = 4; - if (value instanceof TodoDoesNotExist) { - return totalSize; - } - if (value instanceof EmptyTodoList) { - return totalSize; - } - if (value instanceof DuplicateTodo) { - return totalSize; - } - if (value instanceof EmptyString) { - return totalSize; - } - if (value instanceof DeligatedError) { - return totalSize; - } - throw new UniFFITypeError("Unknown TodoError variant"); - } - static write(dataStream, value) { - if (value instanceof TodoDoesNotExist) { - dataStream.writeInt32(1); - return; - } - if (value instanceof EmptyTodoList) { - dataStream.writeInt32(2); - return; - } - if (value instanceof DuplicateTodo) { - dataStream.writeInt32(3); - return; - } - if (value instanceof EmptyString) { - dataStream.writeInt32(4); - return; - } - if (value instanceof DeligatedError) { - dataStream.writeInt32(5); - return; - } - throw new UniFFITypeError("Unknown TodoError variant"); - } - - static errorClass = TodoError; -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterOptionalTypeTodoList extends FfiConverterArrayBuffer { - static checkType(value) { - if (value !== undefined && value !== null) { - FfiConverterTypeTodoList.checkType(value) - } - } - - static read(dataStream) { - const code = dataStream.readUint8(0); - switch (code) { - case 0: - return null - case 1: - return FfiConverterTypeTodoList.read(dataStream) - default: - throw new UniFFIError(`Unexpected code: ${code}`); - } - } - - static write(dataStream, value) { - if (value === null || value === undefined) { - dataStream.writeUint8(0); - return; - } - dataStream.writeUint8(1); - FfiConverterTypeTodoList.write(dataStream, value) - } - - static computeSize(value) { - if (value === null || value === undefined) { - return 1; - } - return 1 + FfiConverterTypeTodoList.computeSize(value) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequencestring extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterString.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterString.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterString.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterString.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterSequenceTypeTodoEntry extends FfiConverterArrayBuffer { - static read(dataStream) { - const len = dataStream.readInt32(); - const arr = []; - for (let i = 0; i < len; i++) { - arr.push(FfiConverterTypeTodoEntry.read(dataStream)); - } - return arr; - } - - static write(dataStream, value) { - dataStream.writeInt32(value.length); - value.forEach((innerValue) => { - FfiConverterTypeTodoEntry.write(dataStream, innerValue); - }) - } - - static computeSize(value) { - // The size of the length - let size = 4; - for (const innerValue of value) { - size += FfiConverterTypeTodoEntry.computeSize(innerValue); - } - return size; - } - - static checkType(value) { - if (!Array.isArray(value)) { - throw new UniFFITypeError(`${value} is not an array`); - } - value.forEach((innerValue, idx) => { - try { - FfiConverterTypeTodoEntry.checkType(innerValue); - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(`[${idx}]`); - } - throw e; - } - }) - } -} - - - - - -/** - * createEntryWith - * @returns {TodoEntry} - */ -export function createEntryWith(todo) { - - const liftResult = (result) => FfiConverterTypeTodoEntry.lift(result); - const liftError = (data) => FfiConverterTypeTodoError.lift(data); - const functionCall = () => { - try { - FfiConverterString.checkType(todo) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("todo"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 224, // todolist:uniffi_uniffi_todolist_fn_func_create_entry_with - FfiConverterString.lower(todo), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * getDefaultList - * @returns {?TodoList} - */ -export function getDefaultList() { - - const liftResult = (result) => FfiConverterOptionalTypeTodoList.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callAsyncWrapper( - 225, // todolist:uniffi_uniffi_todolist_fn_func_get_default_list - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} - -/** - * setDefaultList - */ -export function setDefaultList(list) { - - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - try { - FfiConverterTypeTodoList.checkType(list) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("list"); - } - throw e; - } - return UniFFIScaffolding.callAsyncWrapper( - 226, // todolist:uniffi_uniffi_todolist_fn_func_set_default_list - FfiConverterTypeTodoList.lower(list), - ) - } - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustUniffiTraitInterfaces.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustUniffiTraitInterfaces.sys.mjs deleted file mode 100644 index 23ea21dfd288..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustUniffiTraitInterfaces.sys.mjs +++ /dev/null @@ -1,465 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -let lazy = {}; - -ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); -ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); - -// Write/Read data to/from an ArrayBuffer -class ArrayBufferDataStream { - constructor(arrayBuffer) { - this.dataView = new DataView(arrayBuffer); - this.pos = 0; - } - - readUint8() { - let rv = this.dataView.getUint8(this.pos); - this.pos += 1; - return rv; - } - - writeUint8(value) { - this.dataView.setUint8(this.pos, value); - this.pos += 1; - } - - readUint16() { - let rv = this.dataView.getUint16(this.pos); - this.pos += 2; - return rv; - } - - writeUint16(value) { - this.dataView.setUint16(this.pos, value); - this.pos += 2; - } - - readUint32() { - let rv = this.dataView.getUint32(this.pos); - this.pos += 4; - return rv; - } - - writeUint32(value) { - this.dataView.setUint32(this.pos, value); - this.pos += 4; - } - - readUint64() { - let rv = this.dataView.getBigUint64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeUint64(value) { - this.dataView.setBigUint64(this.pos, BigInt(value)); - this.pos += 8; - } - - - readInt8() { - let rv = this.dataView.getInt8(this.pos); - this.pos += 1; - return rv; - } - - writeInt8(value) { - this.dataView.setInt8(this.pos, value); - this.pos += 1; - } - - readInt16() { - let rv = this.dataView.getInt16(this.pos); - this.pos += 2; - return rv; - } - - writeInt16(value) { - this.dataView.setInt16(this.pos, value); - this.pos += 2; - } - - readInt32() { - let rv = this.dataView.getInt32(this.pos); - this.pos += 4; - return rv; - } - - writeInt32(value) { - this.dataView.setInt32(this.pos, value); - this.pos += 4; - } - - readInt64() { - let rv = this.dataView.getBigInt64(this.pos); - this.pos += 8; - return Number(rv); - } - - writeInt64(value) { - this.dataView.setBigInt64(this.pos, BigInt(value)); - this.pos += 8; - } - - readFloat32() { - let rv = this.dataView.getFloat32(this.pos); - this.pos += 4; - return rv; - } - - writeFloat32(value) { - this.dataView.setFloat32(this.pos, value); - this.pos += 4; - } - - readFloat64() { - let rv = this.dataView.getFloat64(this.pos); - this.pos += 8; - return rv; - } - - writeFloat64(value) { - this.dataView.setFloat64(this.pos, value); - this.pos += 8; - } - - - writeString(value) { - // Note: in order to efficiently write this data, we first write the - // string data, reserving 4 bytes for the size. - const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); - const encodeResult = lazy.encoder.encodeInto(value, dest); - if (encodeResult.read != value.length) { - throw new UniFFIError( - "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" - ); - } - const size = encodeResult.written; - // Next, go back and write the size before the string data - this.dataView.setUint32(this.pos, size); - // Finally, advance our position past both the size and string data - this.pos += size + 4; - } - - readString() { - const size = this.readUint32(); - const source = new Uint8Array(this.dataView.buffer, this.pos, size) - const value = lazy.decoder.decode(source); - this.pos += size; - return value; - } - - readBytes() { - const size = this.readInt32(); - const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); - this.pos += size; - return bytes - } - - writeBytes(value) { - this.writeUint32(value.length); - value.forEach((elt) => { - this.writeUint8(elt); - }) - } - - // Reads a Calc pointer from the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - readPointerCalc() { - const pointerId = 23; // uniffi_trait_interfaces:Calc - const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); - this.pos += 8; - return res; - } - - // Writes a Calc pointer into the data stream - // UniFFI Pointers are **always** 8 bytes long. That is enforced - // by the C++ and Rust Scaffolding code. - writePointerCalc(value) { - const pointerId = 23; // uniffi_trait_interfaces:Calc - UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); - this.pos += 8; - } - -} - -function handleRustResult(result, liftCallback, liftErrCallback) { - switch (result.code) { - case "success": - return liftCallback(result.data); - - case "error": - throw liftErrCallback(result.data); - - case "internal-error": - if (result.data) { - throw new UniFFIInternalError(FfiConverterString.lift(result.data)); - } else { - throw new UniFFIInternalError("Unknown error"); - } - - default: - throw new UniFFIError(`Unexpected status code: ${result.code}`); - } -} - -class UniFFIError { - constructor(message) { - this.message = message; - } - - toString() { - return `UniFFIError: ${this.message}` - } -} - -class UniFFIInternalError extends UniFFIError {} - -// Base class for FFI converters -class FfiConverter { - // throw `UniFFITypeError` if a value to be converted has an invalid type - static checkType(value) { - if (value === undefined ) { - throw new UniFFITypeError(`undefined`); - } - if (value === null ) { - throw new UniFFITypeError(`null`); - } - } -} - -// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer -class FfiConverterArrayBuffer extends FfiConverter { - static lift(buf) { - return this.read(new ArrayBufferDataStream(buf)); - } - - static lower(value) { - const buf = new ArrayBuffer(this.computeSize(value)); - const dataStream = new ArrayBufferDataStream(buf); - this.write(dataStream, value); - return buf; - } - - /** - * Computes the size of the value. - * - * @param {*} _value - * @return {number} - */ - static computeSize(_value) { - throw new UniFFIInternalError("computeSize() should be declared in the derived class"); - } - - /** - * Reads the type from a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @returns {any} - */ - static read(_dataStream) { - throw new UniFFIInternalError("read() should be declared in the derived class"); - } - - /** - * Writes the type to a data stream. - * - * @param {ArrayBufferDataStream} _dataStream - * @param {any} _value - */ - static write(_dataStream, _value) { - throw new UniFFIInternalError("write() should be declared in the derived class"); - } - -} - -// Symbols that are used to ensure that Object constructors -// can only be used with a proper UniFFI pointer -const uniffiObjectPtr = Symbol("uniffiObjectPtr"); -const constructUniffiObject = Symbol("constructUniffiObject"); -UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; - -// Export the FFIConverter object to make external types work. -export class FfiConverterU32 extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (!Number.isInteger(value)) { - throw new UniFFITypeError(`${value} is not an integer`); - } - if (value < 0 || value > 4294967295) { - throw new UniFFITypeError(`${value} exceeds the U32 bounds`); - } - } - static computeSize(_value) { - return 4; - } - static lift(value) { - return value; - } - static lower(value) { - return value; - } - static write(dataStream, value) { - dataStream.writeUint32(value) - } - static read(dataStream) { - return dataStream.readUint32() - } -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * Calc - */ -export class Calc { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * add - * @returns {number} - */ - add(a,b) { - const liftResult = (result) => FfiConverterU32.lift(result); - const liftError = null; - const functionCall = () => { - try { - FfiConverterU32.checkType(a) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("a"); - } - throw e; - } - try { - FfiConverterU32.checkType(b) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("b"); - } - throw e; - } - return UniFFIScaffolding.callSync( - 241, // uniffi_trait_interfaces:uniffi_uniffi_trait_interfaces_fn_method_calc_add - FfiConverterTypeCalc.lower(this), - FfiConverterU32.lower(a), - FfiConverterU32.lower(b), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeCalc extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new Calc(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'Calc' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerCalc()); - } - - static write(dataStream, value) { - dataStream.writePointerCalc(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - - - - - -/** - * makeBuggyCalculator - * @returns {Calc} - */ -export function makeBuggyCalculator() { - - const liftResult = (result) => FfiConverterTypeCalc.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 239, // uniffi_trait_interfaces:uniffi_uniffi_trait_interfaces_fn_func_make_buggy_calculator - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} - -/** - * makeCalculator - * @returns {Calc} - */ -export function makeCalculator() { - - const liftResult = (result) => FfiConverterTypeCalc.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 240, // uniffi_trait_interfaces:uniffi_uniffi_trait_interfaces_fn_func_make_calculator - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/Cargo.toml deleted file mode 100644 index a35ce906aa99..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "uniffi-example-geometry" -edition = "2021" -version = "0.22.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_geometry" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/src/lib.rs deleted file mode 100644 index 12281ef79ece..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/src/lib.rs +++ /dev/null @@ -1,49 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp -// Silence, clippy! -const EPSILON: f64 = 0.0001f64; - -#[derive(Debug, Clone, uniffi::Record)] -pub struct Point { - coord_x: f64, - coord_y: f64, -} - -#[derive(Debug, Clone, uniffi::Record)] -pub struct Line { - start: Point, - end: Point, -} - -#[uniffi::export] -pub fn gradient(ln: Line) -> f64 { - let rise = ln.end.coord_y - ln.start.coord_y; - let run = ln.end.coord_x - ln.start.coord_x; - rise / run -} - -#[uniffi::export] -pub fn intersection(ln1: Line, ln2: Line) -> Option { - // TODO: yuck, should be able to take &Line as argument here - // and have rust figure it out with a bunch of annotations... - let g1 = gradient(ln1.clone()); - let z1 = ln1.start.coord_y - g1 * ln1.start.coord_x; - let g2 = gradient(ln2.clone()); - let z2 = ln2.start.coord_y - g2 * ln2.start.coord_x; - // Parallel lines do not intersect. - if (g1 - g2).abs() < EPSILON { - return None; - } - // Otherwise, they intersect at this fancy calculation that - // I found on wikipedia. - let x = (z2 - z1) / (g1 - g2); - Some(Point { - coord_x: x, - coord_y: g1 * x + z1, - }) -} - -uniffi::setup_scaffolding!("geometry"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.kts b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.kts deleted file mode 100644 index 77bb9932ec02..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.kts +++ /dev/null @@ -1,10 +0,0 @@ -import uniffi.geometry.*; - -val ln1 = Line(Point(0.0,0.0), Point(1.0,2.0)) -val ln2 = Line(Point(1.0,1.0), Point(2.0,2.0)) - -assert( gradient(ln1) == 2.0 ) -assert( gradient(ln2) == 1.0 ) - -assert( intersection(ln1, ln2) == Point(0.0, 0.0) ) -assert( intersection(ln1, ln1) == null ) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.py b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.py deleted file mode 100644 index bfb6560626e7..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.py +++ /dev/null @@ -1,10 +0,0 @@ -from geometry import Line, Point, gradient, intersection - -ln1 = Line(start=Point(coord_x=0, coord_y=0), end=Point(coord_x=1, coord_y=2)) -ln2 = Line(start=Point(coord_x=1, coord_y=1), end=Point(coord_x=2, coord_y=2)) - -assert gradient(ln1) == 2 -assert gradient(ln2) == 1 - -assert intersection(ln1, ln2) == Point(coord_x=0, coord_y=0) -assert intersection(ln1, ln1) is None diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.rb b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.rb deleted file mode 100644 index 90fdff684e4d..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true - -require 'test/unit' -require 'geometry' - -include Test::Unit::Assertions -include Geometry - -ln1 = Line.new(start: Point.new(coord_x: 0.0, coord_y: 0.0), _end: Point.new(coord_x: 1.0, coord_y: 2.0)) -ln2 = Line.new(start: Point.new(coord_x: 1.0, coord_y: 1.0), _end: Point.new(coord_x: 2.0, coord_y: 2.0)) - -assert_equal Geometry.gradient(ln1), 2 -assert_equal Geometry.gradient(ln2), 1 - -assert_equal Geometry.intersection(ln1, ln2), Point.new(coord_x: 0, coord_y: 0) -assert Geometry.intersection(ln1, ln1).nil? diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.swift b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.swift deleted file mode 100644 index 58bd65607f51..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/bindings/test_geometry.swift +++ /dev/null @@ -1,10 +0,0 @@ -import geometry - -let ln1 = Line(start: Point(coordX: 0, coordY: 0), end: Point(coordX: 1, coordY: 2)) -let ln2 = Line(start: Point(coordX: 1, coordY: 1), end: Point(coordX: 2, coordY: 2)) - -assert(gradient(ln: ln1) == 2.0) -assert(gradient(ln: ln2) == 1.0) - -assert(intersection(ln1: ln1, ln2: ln2) == Point(coordX: 0, coordY: 0)) -assert(intersection(ln1: ln1, ln2: ln1) == nil) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/test_generated_bindings.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/test_generated_bindings.rs deleted file mode 100644 index 4638d847c8fc..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/geometry/tests/test_generated_bindings.rs +++ /dev/null @@ -1,6 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_geometry.py", - "tests/bindings/test_geometry.rb", - "tests/bindings/test_geometry.kts", - "tests/bindings/test_geometry.swift", -); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/lib.rs deleted file mode 100644 index 9d9ac91fbc5b..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/lib.rs +++ /dev/null @@ -1,15 +0,0 @@ -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at http://mozilla.org/MPL/2.0/. - -arithmetical::uniffi_reexport_scaffolding!(); -uniffi_fixture_callbacks::uniffi_reexport_scaffolding!(); -uniffi_custom_types::uniffi_reexport_scaffolding!(); -uniffi_fixture_external_types::uniffi_reexport_scaffolding!(); -uniffi_fixture_futures::uniffi_reexport_scaffolding!(); -uniffi_fixture_refcounts::uniffi_reexport_scaffolding!(); -uniffi_geometry::uniffi_reexport_scaffolding!(); -uniffi_rondpoint::uniffi_reexport_scaffolding!(); -uniffi_sprites::uniffi_reexport_scaffolding!(); -uniffi_todolist::uniffi_reexport_scaffolding!(); -uniffi_trait_interfaces::uniffi_reexport_scaffolding!(); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/moz.build b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/moz.build deleted file mode 100644 index 7aeb82a03f9a..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/moz.build +++ /dev/null @@ -1,27 +0,0 @@ -# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- -# vim: set filetype=python: -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -FINAL_LIBRARY = "xul" - -components = [ - "Arithmetic", - "CustomTypes", - "ExternalTypes", - "FixtureCallbacks", - "Futures", - "Geometry", - "Refcounts", - "Rondpoint", - "Sprites", - "Todolist", - "UniffiTraitInterfaces", -] - -EXTRA_JS_MODULES += [ - "generated/Rust{}.sys.mjs".format(component) for component in components -] - -XPCSHELL_TESTS_MANIFESTS += ["tests/xpcshell/xpcshell.toml"] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/Cargo.toml deleted file mode 100644 index 877e5027112e..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "uniffi-fixture-refcounts" -edition = "2021" -version = "0.21.0" -license = "MPL-2.0" -publish = false - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/src/lib.rs deleted file mode 100644 index 6554625c62e4..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/src/lib.rs +++ /dev/null @@ -1,32 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/// This crate exists to test managing the Rust Arc strong counts as JS objects are -/// created/destroyed. See `test_refcounts.js` for how it's used. -use std::sync::{Arc, Mutex}; - -pub struct SingletonObject; - -impl SingletonObject { - pub fn method(&self) {} -} - -static SINGLETON: Mutex>> = Mutex::new(None); - -pub fn get_singleton() -> Arc { - Arc::clone( - SINGLETON - .lock() - .unwrap() - .get_or_insert_with(|| Arc::new(SingletonObject)), - ) -} - -pub fn get_js_refcount() -> i32 { - // Subtract 2: one for the reference in the Mutex and one for the temporary reference that - // we're calling Arc::strong_count on. - (Arc::strong_count(&get_singleton()) as i32) - 2 -} - -include!(concat!(env!("OUT_DIR"), "/refcounts.uniffi.rs")); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/src/refcounts.udl b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/src/refcounts.udl deleted file mode 100644 index 25ec83cfcc5d..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/src/refcounts.udl +++ /dev/null @@ -1,8 +0,0 @@ -namespace refcounts { - SingletonObject get_singleton(); - i32 get_js_refcount(); -}; - -interface SingletonObject { - void method(); -}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/Cargo.toml deleted file mode 100644 index 1d0be84785f6..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "uniffi-example-rondpoint" -edition = "2021" -version = "0.22.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_rondpoint" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/build.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/build.rs deleted file mode 100644 index f830879d091f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/rondpoint.udl").unwrap(); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/src/lib.rs deleted file mode 100644 index 3f2233ddaa77..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/src/lib.rs +++ /dev/null @@ -1,293 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::collections::HashMap; - -#[derive(Debug, Clone)] -pub struct Dictionnaire { - un: Enumeration, - deux: bool, - petit_nombre: u8, - gros_nombre: u64, -} - -#[derive(Debug, Clone)] -pub struct DictionnaireNombres { - petit_nombre: u8, - court_nombre: u16, - nombre_simple: u32, - gros_nombre: u64, -} - -#[derive(Debug, Clone)] -pub struct DictionnaireNombresSignes { - petit_nombre: i8, - court_nombre: i16, - nombre_simple: i32, - gros_nombre: i64, -} - -#[derive(Debug, Clone)] -pub enum Enumeration { - Un, - Deux, - Trois, -} - -#[derive(Debug, Clone)] -pub enum EnumerationAvecDonnees { - Zero, - Un { premier: u32 }, - Deux { premier: u32, second: String }, -} - -#[allow(non_camel_case_types)] -#[allow(non_snake_case)] -pub struct minusculeMAJUSCULEDict { - minusculeMAJUSCULEField: bool, -} - -#[allow(non_camel_case_types)] -pub enum minusculeMAJUSCULEEnum { - minusculeMAJUSCULEVariant, -} - -fn copie_enumeration(e: Enumeration) -> Enumeration { - e -} - -fn copie_enumerations(e: Vec) -> Vec { - e -} - -fn copie_carte( - e: HashMap, -) -> HashMap { - e -} - -fn copie_dictionnaire(d: Dictionnaire) -> Dictionnaire { - d -} - -fn switcheroo(b: bool) -> bool { - !b -} - -// Test that values can traverse both ways across the FFI. -// Even if roundtripping works, it's possible we have -// symmetrical errors that cancel each other out. -#[derive(Debug, Clone)] -struct Retourneur; -impl Retourneur { - fn new() -> Self { - Retourneur - } - fn identique_i8(&self, value: i8) -> i8 { - value - } - fn identique_u8(&self, value: u8) -> u8 { - value - } - fn identique_i16(&self, value: i16) -> i16 { - value - } - fn identique_u16(&self, value: u16) -> u16 { - value - } - fn identique_i32(&self, value: i32) -> i32 { - value - } - fn identique_u32(&self, value: u32) -> u32 { - value - } - fn identique_i64(&self, value: i64) -> i64 { - value - } - fn identique_u64(&self, value: u64) -> u64 { - value - } - fn identique_float(&self, value: f32) -> f32 { - value - } - fn identique_double(&self, value: f64) -> f64 { - value - } - fn identique_boolean(&self, value: bool) -> bool { - value - } - fn identique_string(&self, value: String) -> String { - value - } - fn identique_nombres_signes( - &self, - value: DictionnaireNombresSignes, - ) -> DictionnaireNombresSignes { - value - } - fn identique_nombres(&self, value: DictionnaireNombres) -> DictionnaireNombres { - value - } - fn identique_optionneur_dictionnaire( - &self, - value: OptionneurDictionnaire, - ) -> OptionneurDictionnaire { - value - } -} - -#[derive(Debug, Clone)] -struct Stringifier; - -#[allow(dead_code)] -impl Stringifier { - fn new() -> Self { - Stringifier - } - fn to_string_i8(&self, value: i8) -> String { - value.to_string() - } - fn to_string_u8(&self, value: u8) -> String { - value.to_string() - } - fn to_string_i16(&self, value: i16) -> String { - value.to_string() - } - fn to_string_u16(&self, value: u16) -> String { - value.to_string() - } - fn to_string_i32(&self, value: i32) -> String { - value.to_string() - } - fn to_string_u32(&self, value: u32) -> String { - value.to_string() - } - fn to_string_i64(&self, value: i64) -> String { - value.to_string() - } - fn to_string_u64(&self, value: u64) -> String { - value.to_string() - } - fn to_string_float(&self, value: f32) -> String { - value.to_string() - } - fn to_string_double(&self, value: f64) -> String { - value.to_string() - } - fn to_string_boolean(&self, value: bool) -> String { - value.to_string() - } - fn well_known_string(&self, value: String) -> String { - format!("uniffi 💚 {value}!") - } -} - -#[derive(Debug, Clone)] -struct Optionneur; -impl Optionneur { - fn new() -> Self { - Optionneur - } - fn sinon_string(&self, value: String) -> String { - value - } - fn sinon_null(&self, value: Option) -> Option { - value - } - fn sinon_boolean(&self, value: bool) -> bool { - value - } - fn sinon_sequence(&self, value: Vec) -> Vec { - value - } - - fn sinon_zero(&self, value: Option) -> Option { - value - } - - fn sinon_u8_dec(&self, value: u8) -> u8 { - value - } - fn sinon_i8_dec(&self, value: i8) -> i8 { - value - } - fn sinon_u16_dec(&self, value: u16) -> u16 { - value - } - fn sinon_i16_dec(&self, value: i16) -> i16 { - value - } - fn sinon_u32_dec(&self, value: u32) -> u32 { - value - } - fn sinon_i32_dec(&self, value: i32) -> i32 { - value - } - fn sinon_u64_dec(&self, value: u64) -> u64 { - value - } - fn sinon_i64_dec(&self, value: i64) -> i64 { - value - } - - fn sinon_u8_hex(&self, value: u8) -> u8 { - value - } - fn sinon_i8_hex(&self, value: i8) -> i8 { - value - } - fn sinon_u16_hex(&self, value: u16) -> u16 { - value - } - fn sinon_i16_hex(&self, value: i16) -> i16 { - value - } - fn sinon_u32_hex(&self, value: u32) -> u32 { - value - } - fn sinon_i32_hex(&self, value: i32) -> i32 { - value - } - fn sinon_u64_hex(&self, value: u64) -> u64 { - value - } - fn sinon_i64_hex(&self, value: i64) -> i64 { - value - } - - fn sinon_u32_oct(&self, value: u32) -> u32 { - value - } - - fn sinon_f32(&self, value: f32) -> f32 { - value - } - fn sinon_f64(&self, value: f64) -> f64 { - value - } - - fn sinon_enum(&self, value: Enumeration) -> Enumeration { - value - } -} - -pub struct OptionneurDictionnaire { - i8_var: i8, - u8_var: u8, - i16_var: i16, - u16_var: u16, - i32_var: i32, - u32_var: u32, - i64_var: i64, - u64_var: u64, - float_var: f32, - double_var: f64, - boolean_var: bool, - string_var: String, - list_var: Vec, - enumeration_var: Enumeration, - dictionnaire_var: Option, -} - -uniffi::include_scaffolding!("rondpoint"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/src/rondpoint.udl b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/src/rondpoint.udl deleted file mode 100644 index 7c8261d74e3f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/src/rondpoint.udl +++ /dev/null @@ -1,146 +0,0 @@ -namespace rondpoint { - Dictionnaire copie_dictionnaire(Dictionnaire d); - Enumeration copie_enumeration(Enumeration e); - sequence copie_enumerations(sequence e); - record copie_carte(record c); - boolean switcheroo(boolean b); -}; - -dictionary minusculeMAJUSCULEDict { - boolean minusculeMAJUSCULEField; -}; - -enum minusculeMAJUSCULEEnum { - "minusculeMAJUSCULEVariant", -}; - -enum Enumeration { - "Un", - "Deux", - "Trois", -}; - -[Enum] -interface EnumerationAvecDonnees { - Zero(); - Un(u32 premier); - Deux(u32 premier, string second); -}; - -dictionary Dictionnaire { - Enumeration un; - boolean deux; - u8 petit_nombre; - u64 gros_nombre; -}; - -dictionary DictionnaireNombres { - u8 petit_nombre; - u16 court_nombre; - u32 nombre_simple; - u64 gros_nombre; -}; - -dictionary DictionnaireNombresSignes { - i8 petit_nombre; - i16 court_nombre; - i32 nombre_simple; - i64 gros_nombre; -}; - -interface Retourneur { - constructor(); - i8 identique_i8(i8 value); - u8 identique_u8(u8 value); - i16 identique_i16(i16 value); - u16 identique_u16(u16 value); - i32 identique_i32(i32 value); - u32 identique_u32(u32 value); - i64 identique_i64(i64 value); - u64 identique_u64(u64 value); - float identique_float(float value); - double identique_double(double value); - boolean identique_boolean(boolean value); - string identique_string(string value); - - DictionnaireNombresSignes identique_nombres_signes(DictionnaireNombresSignes value); - DictionnaireNombres identique_nombres(DictionnaireNombres value); - OptionneurDictionnaire identique_optionneur_dictionnaire(OptionneurDictionnaire value); -}; - -interface Stringifier { - constructor(); - string well_known_string(string value); - - string to_string_i8(i8 value); - string to_string_u8(u8 value); - string to_string_i16(i16 value); - string to_string_u16(u16 value); - string to_string_i32(i32 value); - string to_string_u32(u32 value); - string to_string_i64(i64 value); - string to_string_u64(u64 value); - string to_string_float(float value); - string to_string_double(double value); - string to_string_boolean(boolean value); -}; - -interface Optionneur { - constructor(); - boolean sinon_boolean(optional boolean value = false); - string sinon_string(optional string value = "default"); - - sequence sinon_sequence(optional sequence value = []); - - // Either sides of nullable. - string? sinon_null(optional string? value = null); - i32? sinon_zero(optional i32? value = 0); - - // Decimal integers, all 42. - u8 sinon_u8_dec(optional u8 value = 42); - i8 sinon_i8_dec(optional i8 value = -42); - u16 sinon_u16_dec(optional u16 value = 42); - i16 sinon_i16_dec(optional i16 value = 42); - u32 sinon_u32_dec(optional u32 value = 42); - i32 sinon_i32_dec(optional i32 value = 42); - u64 sinon_u64_dec(optional u64 value = 42); - i64 sinon_i64_dec(optional i64 value = 42); - - // Hexadecimal, including negatgives. - u8 sinon_u8_hex(optional u8 value = 0xff); - i8 sinon_i8_hex(optional i8 value = -0x7f); - u16 sinon_u16_hex(optional u16 value = 0xffff); - i16 sinon_i16_hex(optional i16 value = 0x7f); - u32 sinon_u32_hex(optional u32 value = 0xffffffff); - i32 sinon_i32_hex(optional i32 value = 0x7fffffff); - u64 sinon_u64_hex(optional u64 value = 0xffffffffffffffff); - i64 sinon_i64_hex(optional i64 value = 0x7fffffffffffffff); - - // Octal, FWIW. - u32 sinon_u32_oct(optional u32 value = 0755); - - // Floats - f32 sinon_f32(optional f32 value = 42.0); - f64 sinon_f64(optional f64 value = 42.1); - - // Enums, which we have to treat as strings in the UDL frontend. - Enumeration sinon_enum(optional Enumeration value = "Trois"); -}; - -dictionary OptionneurDictionnaire { - i8 i8_var = -8; - u8 u8_var = 8; - i16 i16_var = -0x10; - u16 u16_var = 0x10; - i32 i32_var = -32; - u32 u32_var = 32; - i64 i64_var = -64; - u64 u64_var = 64; - float float_var = 4.0; - double double_var = 8.0; - boolean boolean_var = true; - string string_var = "default"; - sequence list_var = []; - Enumeration enumeration_var = "DEUX"; - minusculeMAJUSCULEEnum? dictionnaire_var = null; -}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.kts b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.kts deleted file mode 100644 index cc5ddf2a86eb..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.kts +++ /dev/null @@ -1,250 +0,0 @@ -import uniffi.rondpoint.* - -val dico = Dictionnaire(Enumeration.DEUX, true, 0u, 123456789u) -val copyDico = copieDictionnaire(dico) -assert(dico == copyDico) - -assert(copieEnumeration(Enumeration.DEUX) == Enumeration.DEUX) -assert(copieEnumerations(listOf(Enumeration.UN, Enumeration.DEUX)) == listOf(Enumeration.UN, Enumeration.DEUX)) -assert(copieCarte(mapOf( - "0" to EnumerationAvecDonnees.Zero, - "1" to EnumerationAvecDonnees.Un(1u), - "2" to EnumerationAvecDonnees.Deux(2u, "deux") -)) == mapOf( - "0" to EnumerationAvecDonnees.Zero, - "1" to EnumerationAvecDonnees.Un(1u), - "2" to EnumerationAvecDonnees.Deux(2u, "deux") -)) - -val var1: EnumerationAvecDonnees = EnumerationAvecDonnees.Zero -val var2: EnumerationAvecDonnees = EnumerationAvecDonnees.Un(1u) -val var3: EnumerationAvecDonnees = EnumerationAvecDonnees.Un(2u) -assert(var1 != var2) -assert(var2 != var3) -assert(var1 == EnumerationAvecDonnees.Zero) -assert(var1 != EnumerationAvecDonnees.Un(1u)) -assert(var2 == EnumerationAvecDonnees.Un(1u)) - -assert(switcheroo(false)) - -// Test the roundtrip across the FFI. -// This shows that the values we send come back in exactly the same state as we sent them. -// i.e. it shows that lowering from kotlin and lifting into rust is symmetrical with -// lowering from rust and lifting into kotlin. -val rt = Retourneur() - -fun List.affirmAllerRetour(fn: (T) -> T) { - this.forEach { v -> - assert(fn.invoke(v) == v) { "$fn($v)" } - } -} - -// Booleans -listOf(true, false).affirmAllerRetour(rt::identiqueBoolean) - -// Bytes. -listOf(Byte.MIN_VALUE, Byte.MAX_VALUE).affirmAllerRetour(rt::identiqueI8) -listOf(0x00, 0xFF).map { it.toUByte() }.affirmAllerRetour(rt::identiqueU8) - -// Shorts -listOf(Short.MIN_VALUE, Short.MAX_VALUE).affirmAllerRetour(rt::identiqueI16) -listOf(0x0000, 0xFFFF).map { it.toUShort() }.affirmAllerRetour(rt::identiqueU16) - -// Ints -listOf(0, 1, -1, Int.MIN_VALUE, Int.MAX_VALUE).affirmAllerRetour(rt::identiqueI32) -listOf(0x00000000, 0xFFFFFFFF).map { it.toUInt() }.affirmAllerRetour(rt::identiqueU32) - -// Longs -listOf(0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE).affirmAllerRetour(rt::identiqueI64) -listOf(0u, 1u, ULong.MIN_VALUE, ULong.MAX_VALUE).affirmAllerRetour(rt::identiqueU64) - -// Floats -listOf(0.0F, 0.5F, 0.25F, Float.MIN_VALUE, Float.MAX_VALUE).affirmAllerRetour(rt::identiqueFloat) - -// Doubles -listOf(0.0, 1.0, Double.MIN_VALUE, Double.MAX_VALUE).affirmAllerRetour(rt::identiqueDouble) - -// Strings -listOf("", "abc", "null\u0000byte", "été", "ښي لاس ته لوستلو لوستل", "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama") - .affirmAllerRetour(rt::identiqueString) - -listOf(-1, 0, 1).map { DictionnaireNombresSignes(it.toByte(), it.toShort(), it.toInt(), it.toLong()) } - .affirmAllerRetour(rt::identiqueNombresSignes) - -listOf(0, 1).map { DictionnaireNombres(it.toUByte(), it.toUShort(), it.toUInt(), it.toULong()) } - .affirmAllerRetour(rt::identiqueNombres) - - -rt.destroy() - -// Test one way across the FFI. -// -// We send one representation of a value to lib.rs, and it transforms it into another, a string. -// lib.rs sends the string back, and then we compare here in kotlin. -// -// This shows that the values are transformed into strings the same way in both kotlin and rust. -// i.e. if we assume that the string return works (we test this assumption elsewhere) -// we show that lowering from kotlin and lifting into rust has values that both kotlin and rust -// both stringify in the same way. i.e. the same values. -// -// If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust t here, -// and this convinces us that lowering/lifting from here to rust is correct, then -// together, we've shown the correctness of the return leg. -val st = Stringifier() - -typealias StringyEquals = (observed: String, expected: T) -> Boolean -fun List.affirmEnchaine( - fn: (T) -> String, - equals: StringyEquals = { obs, exp -> obs == exp.toString() } -) { - this.forEach { exp -> - val obs = fn.invoke(exp) - assert(equals(obs, exp)) { "$fn($exp): observed=$obs, expected=$exp" } - } -} - -// Test the efficacy of the string transport from rust. If this fails, but everything else -// works, then things are very weird. -val wellKnown = st.wellKnownString("kotlin") -assert("uniffi 💚 kotlin!" == wellKnown) { "wellKnownString 'uniffi 💚 kotlin!' == '$wellKnown'" } - -// Booleans -listOf(true, false).affirmEnchaine(st::toStringBoolean) - -// Bytes. -listOf(Byte.MIN_VALUE, Byte.MAX_VALUE).affirmEnchaine(st::toStringI8) -listOf(UByte.MIN_VALUE, UByte.MAX_VALUE).affirmEnchaine(st::toStringU8) - -// Shorts -listOf(Short.MIN_VALUE, Short.MAX_VALUE).affirmEnchaine(st::toStringI16) -listOf(UShort.MIN_VALUE, UShort.MAX_VALUE).affirmEnchaine(st::toStringU16) - -// Ints -listOf(0, 1, -1, Int.MIN_VALUE, Int.MAX_VALUE).affirmEnchaine(st::toStringI32) -listOf(0u, 1u, UInt.MIN_VALUE, UInt.MAX_VALUE).affirmEnchaine(st::toStringU32) - -// Longs -listOf(0L, 1L, -1L, Long.MIN_VALUE, Long.MAX_VALUE).affirmEnchaine(st::toStringI64) -listOf(0u, 1u, ULong.MIN_VALUE, ULong.MAX_VALUE).affirmEnchaine(st::toStringU64) - -// Floats -// MIN_VALUE is 1.4E-45. Accuracy and formatting get weird at small sizes. -listOf(0.0F, 1.0F, -1.0F, Float.MIN_VALUE, Float.MAX_VALUE).affirmEnchaine(st::toStringFloat) { s, n -> s.toFloat() == n } - -// Doubles -// MIN_VALUE is 4.9E-324. Accuracy and formatting get weird at small sizes. -listOf(0.0, 1.0, -1.0, Double.MIN_VALUE, Double.MAX_VALUE).affirmEnchaine(st::toStringDouble) { s, n -> s.toDouble() == n } - -st.destroy() - -// Prove to ourselves that default arguments are being used. -// Step 1: call the methods without arguments, and check against the UDL. -val op = Optionneur() - -assert(op.sinonString() == "default") - -assert(op.sinonBoolean() == false) - -assert(op.sinonSequence() == listOf()) - -// optionals -assert(op.sinonNull() == null) -assert(op.sinonZero() == 0) - -// decimal integers -assert(op.sinonI8Dec() == (-42).toByte()) -assert(op.sinonU8Dec() == 42.toUByte()) -assert(op.sinonI16Dec() == 42.toShort()) -assert(op.sinonU16Dec() == 42.toUShort()) -assert(op.sinonI32Dec() == 42) -assert(op.sinonU32Dec() == 42.toUInt()) -assert(op.sinonI64Dec() == 42L) -assert(op.sinonU64Dec() == 42uL) - -// hexadecimal integers -assert(op.sinonI8Hex() == (-0x7f).toByte()) -assert(op.sinonU8Hex() == 0xff.toUByte()) -assert(op.sinonI16Hex() == 0x7f.toShort()) -assert(op.sinonU16Hex() == 0xffff.toUShort()) -assert(op.sinonI32Hex() == 0x7fffffff) -assert(op.sinonU32Hex() == 0xffffffff.toUInt()) -assert(op.sinonI64Hex() == 0x7fffffffffffffffL) -assert(op.sinonU64Hex() == 0xffffffffffffffffuL) - -// octal integers -assert(op.sinonU32Oct() == 493u) // 0o755 - -// floats -assert(op.sinonF32() == 42.0f) -assert(op.sinonF64() == 42.1) - -// enums -assert(op.sinonEnum() == Enumeration.TROIS) - -// Step 2. Convince ourselves that if we pass something else, then that changes the output. -// We have shown something coming out of the sinon methods, but without eyeballing the Rust -// we can't be sure that the arguments will change the return value. -listOf("foo", "bar").affirmAllerRetour(op::sinonString) -listOf(true, false).affirmAllerRetour(op::sinonBoolean) -listOf(listOf("a", "b"), listOf()).affirmAllerRetour(op::sinonSequence) - -// optionals -listOf("0", "1").affirmAllerRetour(op::sinonNull) -listOf(0, 1).affirmAllerRetour(op::sinonZero) - -// integers -listOf(0, 1).map { it.toUByte() }.affirmAllerRetour(op::sinonU8Dec) -listOf(0, 1).map { it.toByte() }.affirmAllerRetour(op::sinonI8Dec) -listOf(0, 1).map { it.toUShort() }.affirmAllerRetour(op::sinonU16Dec) -listOf(0, 1).map { it.toShort() }.affirmAllerRetour(op::sinonI16Dec) -listOf(0, 1).map { it.toUInt() }.affirmAllerRetour(op::sinonU32Dec) -listOf(0, 1).map { it.toInt() }.affirmAllerRetour(op::sinonI32Dec) -listOf(0, 1).map { it.toULong() }.affirmAllerRetour(op::sinonU64Dec) -listOf(0, 1).map { it.toLong() }.affirmAllerRetour(op::sinonI64Dec) - -listOf(0, 1).map { it.toUByte() }.affirmAllerRetour(op::sinonU8Hex) -listOf(0, 1).map { it.toByte() }.affirmAllerRetour(op::sinonI8Hex) -listOf(0, 1).map { it.toUShort() }.affirmAllerRetour(op::sinonU16Hex) -listOf(0, 1).map { it.toShort() }.affirmAllerRetour(op::sinonI16Hex) -listOf(0, 1).map { it.toUInt() }.affirmAllerRetour(op::sinonU32Hex) -listOf(0, 1).map { it.toInt() }.affirmAllerRetour(op::sinonI32Hex) -listOf(0, 1).map { it.toULong() }.affirmAllerRetour(op::sinonU64Hex) -listOf(0, 1).map { it.toLong() }.affirmAllerRetour(op::sinonI64Hex) - -listOf(0, 1).map { it.toUInt() }.affirmAllerRetour(op::sinonU32Oct) - -// floats -listOf(0.0f, 1.0f).affirmAllerRetour(op::sinonF32) -listOf(0.0, 1.0).affirmAllerRetour(op::sinonF64) - -// enums -Enumeration.values().toList().affirmAllerRetour(op::sinonEnum) - -op.destroy() - -// Testing defaulting properties in record types. -val defaultes = OptionneurDictionnaire() -val explicites = OptionneurDictionnaire( - i8Var = -8, - u8Var = 8u, - i16Var = -16, - u16Var = 0x10u, - i32Var = -32, - u32Var = 32u, - i64Var = -64L, - u64Var = 64uL, - floatVar = 4.0f, - doubleVar = 8.0, - booleanVar = true, - stringVar = "default", - listVar = listOf(), - enumerationVar = Enumeration.DEUX, - dictionnaireVar = null -) -assert(defaultes == explicites) - -// …and makes sure they travel across and back the FFI. -val rt2 = Retourneur() -listOf(defaultes).affirmAllerRetour(rt2::identiqueOptionneurDictionnaire) - -rt2.destroy() diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.py b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.py deleted file mode 100644 index df3e3fab18fc..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.py +++ /dev/null @@ -1,183 +0,0 @@ -import ctypes -import sys - -from rondpoint import ( - Dictionnaire, - Enumeration, - EnumerationAvecDonnees, - Retourneur, - Stringifier, - copie_carte, - copie_dictionnaire, - copie_enumeration, - copie_enumerations, - switcheroo, -) - -dico = Dictionnaire( - un=Enumeration.DEUX, deux=True, petit_nombre=0, gros_nombre=123456789 -) -copyDico = copie_dictionnaire(dico) -assert dico == copyDico - -assert copie_enumeration(Enumeration.DEUX) == Enumeration.DEUX -assert copie_enumerations([Enumeration.UN, Enumeration.DEUX]) == [ - Enumeration.UN, - Enumeration.DEUX, -] -assert copie_carte( - { - "0": EnumerationAvecDonnees.ZERO(), - "1": EnumerationAvecDonnees.UN(1), - "2": EnumerationAvecDonnees.DEUX(2, "deux"), - } -) == { - "0": EnumerationAvecDonnees.ZERO(), - "1": EnumerationAvecDonnees.UN(1), - "2": EnumerationAvecDonnees.DEUX(2, "deux"), -} - -assert switcheroo(False) is True - -assert EnumerationAvecDonnees.ZERO() != EnumerationAvecDonnees.UN(1) -assert EnumerationAvecDonnees.UN(1) == EnumerationAvecDonnees.UN(1) -assert EnumerationAvecDonnees.UN(1) != EnumerationAvecDonnees.UN(2) - -# Test the roundtrip across the FFI. -# This shows that the values we send come back in exactly the same state as we sent them. -# i.e. it shows that lowering from python and lifting into rust is symmetrical with -# lowering from rust and lifting into python. -rt = Retourneur() - - -def affirmAllerRetour(vals, identique): - for v in vals: - id_v = identique(v) - assert id_v == v, f"Round-trip failure: {v} => {id_v}" - - -MIN_I8 = -1 * 2**7 -MAX_I8 = 2**7 - 1 -MIN_I16 = -1 * 2**15 -MAX_I16 = 2**15 - 1 -MIN_I32 = -1 * 2**31 -MAX_I32 = 2**31 - 1 -MIN_I64 = -1 * 2**31 -MAX_I64 = 2**31 - 1 - -# Python floats are always doubles, so won't round-trip through f32 correctly. -# This truncates them appropriately. -F32_ONE_THIRD = ctypes.c_float(1.0 / 3).value - -# Booleans -affirmAllerRetour([True, False], rt.identique_boolean) - -# Bytes. -affirmAllerRetour([MIN_I8, -1, 0, 1, MAX_I8], rt.identique_i8) -affirmAllerRetour([0x00, 0x12, 0xFF], rt.identique_u8) - -# Shorts -affirmAllerRetour([MIN_I16, -1, 0, 1, MAX_I16], rt.identique_i16) -affirmAllerRetour([0x0000, 0x1234, 0xFFFF], rt.identique_u16) - -# Ints -affirmAllerRetour([MIN_I32, -1, 0, 1, MAX_I32], rt.identique_i32) -affirmAllerRetour([0x00000000, 0x12345678, 0xFFFFFFFF], rt.identique_u32) - -# Longs -affirmAllerRetour([MIN_I64, -1, 0, 1, MAX_I64], rt.identique_i64) -affirmAllerRetour( - [0x0000000000000000, 0x1234567890ABCDEF, 0xFFFFFFFFFFFFFFFF], rt.identique_u64 -) - -# Floats -affirmAllerRetour([0.0, 0.5, 0.25, 1.0, F32_ONE_THIRD], rt.identique_float) - -# Doubles -affirmAllerRetour( - [0.0, 0.5, 0.25, 1.0, 1.0 / 3, sys.float_info.max, sys.float_info.min], - rt.identique_double, -) - -# Strings -affirmAllerRetour( - [ - "", - "abc", - "été", - "ښي لاس ته لوستلو لوستل", - "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama", - ], - rt.identique_string, -) - -# Test one way across the FFI. -# -# We send one representation of a value to lib.rs, and it transforms it into another, a string. -# lib.rs sends the string back, and then we compare here in python. -# -# This shows that the values are transformed into strings the same way in both python and rust. -# i.e. if we assume that the string return works (we test this assumption elsewhere) -# we show that lowering from python and lifting into rust has values that both python and rust -# both stringify in the same way. i.e. the same values. -# -# If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust to here, -# and this convinces us that lowering/lifting from here to rust is correct, then -# together, we've shown the correctness of the return leg. -st = Stringifier() - - -def affirmEnchaine(vals, toString, rustyStringify=lambda v: str(v).lower()): - for v in vals: - str_v = toString(v) - assert rustyStringify(v) == str_v, f"String compare error {v} => {str_v}" - - -# Test the efficacy of the string transport from rust. If this fails, but everything else -# works, then things are very weird. -wellKnown = st.well_known_string("python") -assert "uniffi 💚 python!" == wellKnown - -# Booleans -affirmEnchaine([True, False], st.to_string_boolean) - -# Bytes. -affirmEnchaine([MIN_I8, -1, 0, 1, MAX_I8], st.to_string_i8) -affirmEnchaine([0x00, 0x12, 0xFF], st.to_string_u8) - -# Shorts -affirmEnchaine([MIN_I16, -1, 0, 1, MAX_I16], st.to_string_i16) -affirmEnchaine([0x0000, 0x1234, 0xFFFF], st.to_string_u16) - -# Ints -affirmEnchaine([MIN_I32, -1, 0, 1, MAX_I32], st.to_string_i32) -affirmEnchaine([0x00000000, 0x12345678, 0xFFFFFFFF], st.to_string_u32) - -# Longs -affirmEnchaine([MIN_I64, -1, 0, 1, MAX_I64], st.to_string_i64) -affirmEnchaine( - [0x0000000000000000, 0x1234567890ABCDEF, 0xFFFFFFFFFFFFFFFF], st.to_string_u64 -) - - -# Floats -def rustyFloatToStr(v): - """Stringify a float in the same way that rust seems to.""" - # Rust doesn't include the decimal part of whole enumber floats when stringifying. - if int(v) == v: - return str(int(v)) - return str(v) - - -affirmEnchaine([0.0, 0.5, 0.25, 1.0], st.to_string_float, rustyFloatToStr) -assert ( - st.to_string_float(F32_ONE_THIRD) == "0.33333334" -) # annoyingly different string repr - -# Doubles -# TODO: float_info.max/float_info.min don't stringify-roundtrip properly yet, TBD. -affirmEnchaine( - [0.0, 0.5, 0.25, 1.0, 1.0 / 3], - st.to_string_double, - rustyFloatToStr, -) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.rb b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.rb deleted file mode 100644 index faa4062019be..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.rb +++ /dev/null @@ -1,147 +0,0 @@ -# frozen_string_literal: true - -require 'test/unit' -require 'rondpoint' - -include Test::Unit::Assertions -include Rondpoint - -dico = Dictionnaire.new( - un: Enumeration::DEUX, - deux: true, - petit_nombre: 0, - gros_nombre: 123_456_789 -) - -assert_equal dico, Rondpoint.copie_dictionnaire(dico) - -assert_equal Rondpoint.copie_enumeration(Enumeration::DEUX), Enumeration::DEUX - -assert_equal Rondpoint.copie_enumerations([ - Enumeration::UN, - Enumeration::DEUX - ]), [Enumeration::UN, Enumeration::DEUX] - -assert_equal Rondpoint.copie_carte({ - '0' => EnumerationAvecDonnees::ZERO.new, - '1' => EnumerationAvecDonnees::UN.new(1), - '2' => EnumerationAvecDonnees::DEUX.new(2, 'deux') - }), { - '0' => EnumerationAvecDonnees::ZERO.new, - '1' => EnumerationAvecDonnees::UN.new(1), - '2' => EnumerationAvecDonnees::DEUX.new(2, 'deux') - } - -assert Rondpoint.switcheroo(false) - -assert_not_equal EnumerationAvecDonnees::ZERO.new, EnumerationAvecDonnees::UN.new(1) -assert_equal EnumerationAvecDonnees::UN.new(1), EnumerationAvecDonnees::UN.new(1) -assert_not_equal EnumerationAvecDonnees::UN.new(1), EnumerationAvecDonnees::UN.new(2) - -# Test the roundtrip across the FFI. -# This shows that the values we send come back in exactly the same state as we sent them. -# i.e. it shows that lowering from ruby and lifting into rust is symmetrical with -# lowering from rust and lifting into ruby. -RT = Retourneur.new - -def affirm_aller_retour(vals, fn_name) - vals.each do |v| - id_v = RT.public_send fn_name, v - - assert_equal id_v, v, "Round-trip failure: #{v} => #{id_v}" - end -end - -MIN_I8 = -1 * 2**7 -MAX_I8 = 2**7 - 1 -MIN_I16 = -1 * 2**15 -MAX_I16 = 2**15 - 1 -MIN_I32 = -1 * 2**31 -MAX_I32 = 2**31 - 1 -MIN_I64 = -1 * 2**31 -MAX_I64 = 2**31 - 1 - -# Ruby floats are always doubles, so won't round-trip through f32 correctly. -# This truncates them appropriately. -F32_ONE_THIRD = [1.0 / 3].pack('f').unpack('f')[0] - -# Booleans -affirm_aller_retour([true, false], :identique_boolean) - -# Bytes. -affirm_aller_retour([MIN_I8, -1, 0, 1, MAX_I8], :identique_i8) -affirm_aller_retour([0x00, 0x12, 0xFF], :identique_u8) - -# Shorts -affirm_aller_retour([MIN_I16, -1, 0, 1, MAX_I16], :identique_i16) -affirm_aller_retour([0x0000, 0x1234, 0xFFFF], :identique_u16) - -# Ints -affirm_aller_retour([MIN_I32, -1, 0, 1, MAX_I32], :identique_i32) -affirm_aller_retour([0x00000000, 0x12345678, 0xFFFFFFFF], :identique_u32) - -# Longs -affirm_aller_retour([MIN_I64, -1, 0, 1, MAX_I64], :identique_i64) -affirm_aller_retour([0x0000000000000000, 0x1234567890ABCDEF, 0xFFFFFFFFFFFFFFFF], :identique_u64) - -# Floats -affirm_aller_retour([0.0, 0.5, 0.25, 1.0, F32_ONE_THIRD], :identique_float) - -# Doubles -affirm_aller_retour( - [0.0, 0.5, 0.25, 1.0, 1.0 / 3, Float::MAX, Float::MIN], - :identique_double -) - -# Strings -affirm_aller_retour( - ['', 'abc', 'été', 'ښي لاس ته لوستلو لوستل', - '😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama'], - :identique_string -) - -# Test one way across the FFI. -# -# We send one representation of a value to lib.rs, and it transforms it into another, a string. -# lib.rs sends the string back, and then we compare here in ruby. -# -# This shows that the values are transformed into strings the same way in both ruby and rust. -# i.e. if we assume that the string return works (we test this assumption elsewhere) -# we show that lowering from ruby and lifting into rust has values that both ruby and rust -# both stringify in the same way. i.e. the same values. -# -# If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust to here, -# and this convinces us that lowering/lifting from here to rust is correct, then -# together, we've shown the correctness of the return leg. -ST = Stringifier.new - -def affirm_enchaine(vals, fn_name) - vals.each do |v| - str_v = ST.public_send fn_name, v - - assert_equal v.to_s, str_v, "String compare error #{v} => #{str_v}" - end -end - -# Test the efficacy of the string transport from rust. If this fails, but everything else -# works, then things are very weird. -assert_equal ST.well_known_string('ruby'), 'uniffi 💚 ruby!' - -# Booleans -affirm_enchaine([true, false], :to_string_boolean) - -# Bytes. -affirm_enchaine([MIN_I8, -1, 0, 1, MAX_I8], :to_string_i8) -affirm_enchaine([0x00, 0x12, 0xFF], :to_string_u8) - -# Shorts -affirm_enchaine([MIN_I16, -1, 0, 1, MAX_I16], :to_string_i16) -affirm_enchaine([0x0000, 0x1234, 0xFFFF], :to_string_u16) - -# Ints -affirm_enchaine([MIN_I32, -1, 0, 1, MAX_I32], :to_string_i32) -affirm_enchaine([0x00000000, 0x12345678, 0xFFFFFFFF], :to_string_u32) - -# Longs -affirm_enchaine([MIN_I64, -1, 0, 1, MAX_I64], :to_string_i64) -affirm_enchaine([0x0000000000000000, 0x1234567890ABCDEF, 0xFFFFFFFFFFFFFFFF], :to_string_u64) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.swift b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.swift deleted file mode 100644 index d9f47058ed32..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.swift +++ /dev/null @@ -1,232 +0,0 @@ -import rondpoint - -let dico = Dictionnaire(un: .deux, deux: false, petitNombre: 0, grosNombre: 123456789) -let copyDico = copieDictionnaire(d: dico) -assert(dico == copyDico) - -assert(copieEnumeration(e: .deux) == .deux) -assert(copieEnumerations(e: [.un, .deux]) == [.un, .deux]) -assert(copieCarte(c: - ["0": .zero, - "1": .un(premier: 1), - "2": .deux(premier: 2, second: "deux") -]) == [ - "0": .zero, - "1": .un(premier: 1), - "2": .deux(premier: 2, second: "deux") -]) - -assert(EnumerationAvecDonnees.zero != EnumerationAvecDonnees.un(premier: 1)) -assert(EnumerationAvecDonnees.un(premier: 1) == EnumerationAvecDonnees.un(premier: 1)) -assert(EnumerationAvecDonnees.un(premier: 1) != EnumerationAvecDonnees.un(premier: 2)) - - -assert(switcheroo(b: false)) - -// Test the roundtrip across the FFI. -// This shows that the values we send come back in exactly the same state as we sent them. -// i.e. it shows that lowering from swift and lifting into rust is symmetrical with -// lowering from rust and lifting into swift. -let rt = Retourneur() - -// Booleans -[true, false].affirmAllerRetour(rt.identiqueBoolean) - -// Bytes. -[.min, .max].affirmAllerRetour(rt.identiqueI8) -[0x00, 0xFF].map { $0 as UInt8 }.affirmAllerRetour(rt.identiqueU8) - -// Shorts -[.min, .max].affirmAllerRetour(rt.identiqueI16) -[0x0000, 0xFFFF].map { $0 as UInt16 }.affirmAllerRetour(rt.identiqueU16) - -// Ints -[0, 1, -1, .min, .max].affirmAllerRetour(rt.identiqueI32) -[0x00000000, 0xFFFFFFFF].map { $0 as UInt32 }.affirmAllerRetour(rt.identiqueU32) - -// Longs -[.zero, 1, -1, .min, .max].affirmAllerRetour(rt.identiqueI64) -[.zero, 1, .min, .max].affirmAllerRetour(rt.identiqueU64) - -// Floats -[.zero, 1, 0.25, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmAllerRetour(rt.identiqueFloat) - -// Doubles -[0.0, 1.0, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmAllerRetour(rt.identiqueDouble) - -// Strings -["", "abc", "null\0byte", "été", "ښي لاس ته لوستلو لوستل", "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama"] - .affirmAllerRetour(rt.identiqueString) - -// Test one way across the FFI. -// -// We send one representation of a value to lib.rs, and it transforms it into another, a string. -// lib.rs sends the string back, and then we compare here in swift. -// -// This shows that the values are transformed into strings the same way in both swift and rust. -// i.e. if we assume that the string return works (we test this assumption elsewhere) -// we show that lowering from swift and lifting into rust has values that both swift and rust -// both stringify in the same way. i.e. the same values. -// -// If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust t here, -// and this convinces us that lowering/lifting from here to rust is correct, then -// together, we've shown the correctness of the return leg. -let st = Stringifier() - -// Test the effigacy of the string transport from rust. If this fails, but everything else -// works, then things are very weird. -let wellKnown = st.wellKnownString(value: "swift") -assert("uniffi 💚 swift!" == wellKnown, "wellKnownString 'uniffi 💚 swift!' == '\(wellKnown)'") - -// Booleans -[true, false].affirmEnchaine(st.toStringBoolean) - -// Bytes. -[.min, .max].affirmEnchaine(st.toStringI8) -[.min, .max].affirmEnchaine(st.toStringU8) - -// Shorts -[.min, .max].affirmEnchaine(st.toStringI16) -[.min, .max].affirmEnchaine(st.toStringU16) - -// Ints -[0, 1, -1, .min, .max].affirmEnchaine(st.toStringI32) -[0, 1, .min, .max].affirmEnchaine(st.toStringU32) - -// Longs -[.zero, 1, -1, .min, .max].affirmEnchaine(st.toStringI64) -[.zero, 1, .min, .max].affirmEnchaine(st.toStringU64) - -// Floats -[.zero, 1, -1, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmEnchaine(st.toStringFloat) { Float.init($0) == $1 } - -// Doubles -[.zero, 1, -1, .leastNonzeroMagnitude, .greatestFiniteMagnitude].affirmEnchaine(st.toStringDouble) { Double.init($0) == $1 } - -// Some extension functions for testing the results of roundtripping and stringifying -extension Array where Element: Equatable { - static func defaultEquals(_ observed: String, expected: Element) -> Bool { - let exp = "\(expected)" - return observed == exp - } - - func affirmEnchaine(_ fn: (Element) -> String, equals: (String, Element) -> Bool = defaultEquals) { - self.forEach { v in - let obs = fn(v) - assert(equals(obs, v), "toString_\(type(of:v))(\(v)): observed=\(obs), expected=\(v)") - } - } - - func affirmAllerRetour(_ fn: (Element) -> Element) { - self.forEach { v in - assert(fn(v) == v, "identique_\(type(of:v))(\(v))") - } - } -} - -// Prove to ourselves that default arguments are being used. -// Step 1: call the methods without arguments, and check against the UDL. -let op = Optionneur() - -assert(op.sinonString() == "default") - -assert(op.sinonBoolean() == false) - -assert(op.sinonSequence() == []) - -// optionals -assert(op.sinonNull() == nil) -assert(op.sinonZero() == 0) - -// decimal integers -assert(op.sinonU8Dec() == UInt8(42)) -assert(op.sinonI8Dec() == Int8(-42)) -assert(op.sinonU16Dec() == UInt16(42)) -assert(op.sinonI16Dec() == Int16(42)) -assert(op.sinonU32Dec() == UInt32(42)) -assert(op.sinonI32Dec() == Int32(42)) -assert(op.sinonU64Dec() == UInt64(42)) -assert(op.sinonI64Dec() == Int64(42)) - -// hexadecimal integers -assert(op.sinonU8Hex() == UInt8(0xff)) -assert(op.sinonI8Hex() == Int8(-0x7f)) -assert(op.sinonU16Hex() == UInt16(0xffff)) -assert(op.sinonI16Hex() == Int16(0x7f)) -assert(op.sinonU32Hex() == UInt32(0xffffffff)) -assert(op.sinonI32Hex() == Int32(0x7fffffff)) -assert(op.sinonU64Hex() == UInt64(0xffffffffffffffff)) -assert(op.sinonI64Hex() == Int64(0x7fffffffffffffff)) - -// octal integers -assert(op.sinonU32Oct() == UInt32(0o755)) - -// floats -assert(op.sinonF32() == 42.0) -assert(op.sinonF64() == Double(42.1)) - -// enums -assert(op.sinonEnum() == .trois) - -// Step 2. Convince ourselves that if we pass something else, then that changes the output. -// We have shown something coming out of the sinon methods, but without eyeballing the Rust -// we can't be sure that the arguments will change the return value. -["foo", "bar"].affirmAllerRetour(op.sinonString) -[true, false].affirmAllerRetour(op.sinonBoolean) -[["a", "b"], []].affirmAllerRetour(op.sinonSequence) - -// optionals -["0", "1"].affirmAllerRetour(op.sinonNull) -[0, 1].affirmAllerRetour(op.sinonZero) - -// integers -[0, 1].affirmAllerRetour(op.sinonU8Dec) -[0, 1].affirmAllerRetour(op.sinonI8Dec) -[0, 1].affirmAllerRetour(op.sinonU16Dec) -[0, 1].affirmAllerRetour(op.sinonI16Dec) -[0, 1].affirmAllerRetour(op.sinonU32Dec) -[0, 1].affirmAllerRetour(op.sinonI32Dec) -[0, 1].affirmAllerRetour(op.sinonU64Dec) -[0, 1].affirmAllerRetour(op.sinonI64Dec) - -[0, 1].affirmAllerRetour(op.sinonU8Hex) -[0, 1].affirmAllerRetour(op.sinonI8Hex) -[0, 1].affirmAllerRetour(op.sinonU16Hex) -[0, 1].affirmAllerRetour(op.sinonI16Hex) -[0, 1].affirmAllerRetour(op.sinonU32Hex) -[0, 1].affirmAllerRetour(op.sinonI32Hex) -[0, 1].affirmAllerRetour(op.sinonU64Hex) -[0, 1].affirmAllerRetour(op.sinonI64Hex) - -[0, 1].affirmAllerRetour(op.sinonU32Oct) - -// floats -[0.0, 1.0].affirmAllerRetour(op.sinonF32) -[0.0, 1.0].affirmAllerRetour(op.sinonF64) - -// enums -[.un, .deux, .trois].affirmAllerRetour(op.sinonEnum) - -// Testing defaulting properties in record types. -let defaultes = OptionneurDictionnaire() -let explicites = OptionneurDictionnaire( - i8Var: Int8(-8), - u8Var: UInt8(8), - i16Var: Int16(-16), - u16Var: UInt16(0x10), - i32Var: -32, - u32Var: UInt32(32), - i64Var: Int64(-64), - u64Var: UInt64(64), - floatVar: Float(4.0), - doubleVar: Double(8.0), - booleanVar: true, - stringVar: "default", - listVar: [], - enumerationVar: .deux, - dictionnaireVar: nil -) - -// …and makes sure they travel across and back the FFI. -assert(defaultes == explicites) -[defaultes].affirmAllerRetour(rt.identiqueOptionneurDictionnaire) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/test_generated_bindings.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/test_generated_bindings.rs deleted file mode 100644 index d33737433437..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/test_generated_bindings.rs +++ /dev/null @@ -1,6 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_rondpoint.kts", - "tests/bindings/test_rondpoint.swift", - "tests/bindings/test_rondpoint.py", - "tests/bindings/test_rondpoint.rb", -); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/Cargo.toml deleted file mode 100644 index 3b4f96e14356..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "uniffi-example-sprites" -edition = "2021" -version = "0.22.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_sprites" - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/src/lib.rs deleted file mode 100644 index 0b3f3a1eea78..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/src/lib.rs +++ /dev/null @@ -1,69 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::RwLock; - -// A point in two-dimensional space. -#[derive(Debug, Clone, uniffi::Record)] -pub struct Point { - pub x: f64, - pub y: f64, -} - -// A magnitude and direction in two-dimensional space. -// For simplicity we represent this as a point relative to the origin. -#[derive(Debug, Clone, uniffi::Record)] -pub struct Vector { - pub dx: f64, - pub dy: f64, -} - -// Move from the given Point, according to the given Vector. -#[uniffi::export] -pub fn translate(p: &Point, v: Vector) -> Point { - Point { - x: p.x + v.dx, - y: p.y + v.dy, - } -} - -// An entity in our imaginary world, which occupies a position in space -// and which can move about over time. -#[derive(Debug, uniffi::Object)] -pub struct Sprite { - // We must use interior mutability for managing mutable state, hence the `RwLock`. - current_position: RwLock, -} - -#[uniffi::export] -impl Sprite { - #[uniffi::constructor] - pub fn new(initial_position: Option) -> Sprite { - Sprite { - current_position: RwLock::new(initial_position.unwrap_or(Point { x: 0.0, y: 0.0 })), - } - } - - #[uniffi::constructor] - pub fn new_relative_to(reference: Point, direction: Vector) -> Sprite { - Sprite { - current_position: RwLock::new(translate(&reference, direction)), - } - } - - pub fn get_position(&self) -> Point { - self.current_position.read().unwrap().clone() - } - - pub fn move_to(&self, position: Point) { - *self.current_position.write().unwrap() = position; - } - - pub fn move_by(&self, direction: Vector) { - let mut current_position = self.current_position.write().unwrap(); - *current_position = translate(¤t_position, direction) - } -} - -uniffi::setup_scaffolding!("sprites"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/src/sprites.udl b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/src/sprites.udl deleted file mode 100644 index 6781c6cee5fe..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/src/sprites.udl +++ /dev/null @@ -1,22 +0,0 @@ - -namespace sprites { - Point translate([ByRef] Point position, Vector direction); -}; - -dictionary Point { - double x; - double y; -}; - -dictionary Vector { - double dx; - double dy; -}; - -interface Sprite { - constructor(Point? initial_position); - [Name=new_relative_to] constructor(Point reference, Vector direction); - Point get_position(); - void move_to(Point position); - void move_by(Vector direction); -}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.kts b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.kts deleted file mode 100644 index 42451f28ddc8..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.kts +++ /dev/null @@ -1,25 +0,0 @@ -import uniffi.sprites.*; - -val sempty = Sprite(null) -assert( sempty.getPosition() == Point(0.0, 0.0) ) - -val s = Sprite(Point(0.0, 1.0)) -assert( s.getPosition() == Point(0.0, 1.0) ) - -s.moveTo(Point(1.0, 2.0)) -assert( s.getPosition() == Point(1.0, 2.0) ) - -s.moveBy(Vector(-4.0, 2.0)) -assert( s.getPosition() == Point(-3.0, 4.0) ) - -s.destroy() -try { - s.moveBy(Vector(0.0, 0.0)) - assert(false) { "Should not be able to call anything after `destroy`" } -} catch(e: IllegalStateException) { - assert(true) -} - -val srel = Sprite.newRelativeTo(Point(0.0, 1.0), Vector(1.0, 1.5)) -assert( srel.getPosition() == Point(1.0, 2.5) ) - diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.py b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.py deleted file mode 100644 index 1e9199700182..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.py +++ /dev/null @@ -1,16 +0,0 @@ -from sprites import Point, Sprite, Vector - -sempty = Sprite(None) -assert sempty.get_position() == Point(x=0, y=0) - -s = Sprite(Point(x=0, y=1)) -assert s.get_position() == Point(x=0, y=1) - -s.move_to(Point(x=1, y=2)) -assert s.get_position() == Point(x=1, y=2) - -s.move_by(Vector(dx=-4, dy=2)) -assert s.get_position() == Point(x=-3, y=4) - -srel = Sprite.new_relative_to(Point(x=0, y=1), Vector(dx=1, dy=1.5)) -assert srel.get_position() == Point(x=1, y=2.5) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.rb b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.rb deleted file mode 100644 index fa73043979ea..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.rb +++ /dev/null @@ -1,22 +0,0 @@ -# frozen_string_literal: true - -require 'test/unit' -require 'sprites' - -include Test::Unit::Assertions -include Sprites - -sempty = Sprite.new(nil) -assert_equal sempty.get_position, Point.new(x: 0, y: 0) - -s = Sprite.new(Point.new(x: 0, y: 1)) -assert_equal s.get_position, Point.new(x: 0, y: 1) - -s.move_to(Point.new(x: 1, y: 2)) -assert_equal s.get_position, Point.new(x: 1, y: 2) - -s.move_by(Vector.new(dx: -4, dy: 2)) -assert_equal s.get_position, Point.new(x: -3, y: 4) - -srel = Sprite.new_relative_to(Point.new(x: 0, y: 1), Vector.new(dx: 1, dy: 1.5)) -assert_equal srel.get_position, Point.new(x: 1, y: 2.5) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.swift b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.swift deleted file mode 100644 index d5428ac6790f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/bindings/test_sprites.swift +++ /dev/null @@ -1,16 +0,0 @@ -import sprites - -let sempty = Sprite(initialPosition: nil) -assert( sempty.getPosition() == Point(x: 0, y: 0)) - -let s = Sprite(initialPosition: Point(x: 0, y: 1)) -assert( s.getPosition() == Point(x: 0, y: 1)) - -s.moveTo(position: Point(x: 1.0, y: 2.0)) -assert( s.getPosition() == Point(x: 1, y: 2)) - -s.moveBy(direction: Vector(dx: -4, dy: 2)) -assert( s.getPosition() == Point(x: -3, y: 4)) - -let srel = Sprite.newRelativeTo(reference: Point(x: 0.0, y: 1.0), direction: Vector(dx: 1, dy: 1.5)) -assert( srel.getPosition() == Point(x: 1.0, y: 2.5) ) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/test_generated_bindings.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/test_generated_bindings.rs deleted file mode 100644 index 00dd779d68be..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/sprites/tests/test_generated_bindings.rs +++ /dev/null @@ -1,6 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_sprites.py", - "tests/bindings/test_sprites.rb", - "tests/bindings/test_sprites.kts", - "tests/bindings/test_sprites.swift", -); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_arithmetic.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_arithmetic.js deleted file mode 100644 index a221abc39f48..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_arithmetic.js +++ /dev/null @@ -1,48 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Arithmetic = ChromeUtils.importESModule( - "resource://gre/modules/RustArithmetic.sys.mjs" -); - -add_task(async function () { - Assert.ok(Arithmetic.IntegerOverflow); - Assert.equal(await Arithmetic.add(2, 4), 6); - Assert.equal(await Arithmetic.add(4, 8), 12); - // For other backends we would have this test: - // await Assert.rejects( - // Arithmetic.add(18446744073709551615, 1), - // Arithmetic.IntegerOverflow, - // "add() should throw IntegerOverflow") - // - // However, this doesn't work because JS number values are actually 64-bit - // floats, and that number is greater than the maximum "safe" integer. - // - // Instead, let's test that we reject numbers that are that big - await Assert.rejects( - Arithmetic.add(Number.MAX_SAFE_INTEGER + 1, 0), - /TypeError/, - "add() should throw TypeError when an input is > MAX_SAFE_INTEGER" - ); - - Assert.equal(await Arithmetic.sub(4, 2), 2); - Assert.equal(await Arithmetic.sub(8, 4), 4); - await Assert.rejects( - Arithmetic.sub(0, 1), - Arithmetic.IntegerOverflow, - "sub() should throw IntegerOverflow" - ); - - Assert.equal(await Arithmetic.div(8, 4), 2); - // Can't test this, because we don't allow Rust panics in FF - // Assert.rejects( - // Arithmetic.div(8, 0), - // (e) => Assert.equal(e, Arithmetic.UniFFIInternalError), - // "Divide by 0 should throw UniFFIInternalError") - // - Assert.ok(await Arithmetic.equal(2, 2)); - Assert.ok(await Arithmetic.equal(4, 4)); - - Assert.ok(!(await Arithmetic.equal(2, 4))); - Assert.ok(!(await Arithmetic.equal(4, 8))); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_callbacks.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_callbacks.js deleted file mode 100644 index 779c106bcc2f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_callbacks.js +++ /dev/null @@ -1,63 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const { callLogRepeat, logEvenNumbers, logEvenNumbersMainThread } = - ChromeUtils.importESModule( - "resource://gre/modules/RustFixtureCallbacks.sys.mjs" - ); - -class Logger { - constructor() { - this.messages = []; - this.finishedPromise = new Promise((resolve, reject) => { - this.finishedResolve = resolve; - this.finishedReject = reject; - }); - } - - log(message) { - this.messages.push(message); - } - - logRepeat(message, count, exclude) { - for (var i = 0; i < count; i++) { - if (!exclude.includes(i)) { - this.messages.push(`${i}: ${message}`); - } - } - } - - finished() { - this.finishedResolve(true); - } - - async waitForFinish() { - // Set a timeout to avoid hanging the tests if the Rust code fails to call finished(). - do_timeout(2000, () => - this.finishedReject("Timeout waiting for finished()") - ); - return this.finishedPromise; - } -} - -add_task(async function testLogEvenNumbers() { - async function runTest(logEvenNumbersFunc) { - const logger = new Logger(); - logEvenNumbersFunc(logger, [1, 1, 2, 3, 5, 8, 13]); - await logger.waitForFinish(); - Assert.deepEqual(logger.messages, [ - "Saw even number: 2", - "Saw even number: 8", - ]); - } - - await runTest(logEvenNumbers); - await runTest(logEvenNumbersMainThread); -}); - -add_task(async function testLogRepeat() { - const logger = new Logger(); - callLogRepeat(logger, "Hello", 5, [2, 3]); - await logger.waitForFinish(); - Assert.deepEqual(logger.messages, ["0: Hello", "1: Hello", "4: Hello"]); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_custom_types.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_custom_types.js deleted file mode 100644 index c6cdf44d006d..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_custom_types.js +++ /dev/null @@ -1,174 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const CustomTypes = ChromeUtils.importESModule( - "resource://gre/modules/RustCustomTypes.sys.mjs" -); - -add_task(async function testCustomTypes() { - // JS right now doesn't treat custom types as anything but it's native counterparts - let demo = await CustomTypes.getCustomTypesDemo(); - Assert.equal(demo.url, "http://example.com/"); - Assert.equal(demo.handle, 123); -}); - -add_task(async function testExplicitEnumValues() { - // Test that the enum values are preserved correctly, including gaps - Assert.equal(CustomTypes.ExplicitValuedEnum.FIRST, 1); - Assert.equal(CustomTypes.ExplicitValuedEnum.SECOND, 2); - Assert.equal(CustomTypes.ExplicitValuedEnum.FOURTH, 4); - Assert.equal(CustomTypes.ExplicitValuedEnum.TENTH, 10); - Assert.equal(CustomTypes.ExplicitValuedEnum.ELEVENTH, 11); - Assert.equal(CustomTypes.ExplicitValuedEnum.THIRTEENTH, 13); - - // Test that the discriminant function returns the expected values - Assert.equal( - await CustomTypes.getExplicitDiscriminant( - CustomTypes.ExplicitValuedEnum.FIRST - ), - 1 - ); - Assert.equal( - await CustomTypes.getExplicitDiscriminant( - CustomTypes.ExplicitValuedEnum.SECOND - ), - 2 - ); - Assert.equal( - await CustomTypes.getExplicitDiscriminant( - CustomTypes.ExplicitValuedEnum.FOURTH - ), - 4 - ); - Assert.equal( - await CustomTypes.getExplicitDiscriminant( - CustomTypes.ExplicitValuedEnum.TENTH - ), - 10 - ); - Assert.equal( - await CustomTypes.getExplicitDiscriminant( - CustomTypes.ExplicitValuedEnum.ELEVENTH - ), - 11 - ); - Assert.equal( - await CustomTypes.getExplicitDiscriminant( - CustomTypes.ExplicitValuedEnum.THIRTEENTH - ), - 13 - ); - - // Test that the enum values work correctly when passed back to Rust - Assert.equal( - await CustomTypes.echoExplicitValue(CustomTypes.ExplicitValuedEnum.FIRST), - CustomTypes.ExplicitValuedEnum.FIRST - ); - Assert.equal( - await CustomTypes.echoExplicitValue(CustomTypes.ExplicitValuedEnum.FOURTH), - CustomTypes.ExplicitValuedEnum.FOURTH - ); - Assert.equal( - await CustomTypes.echoExplicitValue( - CustomTypes.ExplicitValuedEnum.THIRTEENTH - ), - CustomTypes.ExplicitValuedEnum.THIRTEENTH - ); -}); - -add_task(async function testGappedEnumValues() { - // Import UniFFITypeError to check the error type - const { UniFFITypeError } = ChromeUtils.importESModule( - "resource://gre/modules/UniFFI.sys.mjs" - ); - - // Test that the enum values are preserved correctly for mixed sequential/explicit values - Assert.equal(CustomTypes.GappedEnum.ONE, 10); - Assert.equal(CustomTypes.GappedEnum.TWO, 11); // Sequential value after ONE (10+1) - Assert.equal(CustomTypes.GappedEnum.THREE, 14); // Explicit value again - - // Verify with values from Rust - const valueRecord = await CustomTypes.getGappedEnumValues(); - Assert.equal(valueRecord.One, CustomTypes.GappedEnum.ONE); - Assert.equal(valueRecord.Two, CustomTypes.GappedEnum.TWO); - Assert.equal(valueRecord.Three, CustomTypes.GappedEnum.THREE); - - // Test discriminant function - Assert.equal( - await CustomTypes.getGappedDiscriminant(CustomTypes.GappedEnum.ONE), - 10 - ); - Assert.equal( - await CustomTypes.getGappedDiscriminant(CustomTypes.GappedEnum.TWO), - 11 - ); - Assert.equal( - await CustomTypes.getGappedDiscriminant(CustomTypes.GappedEnum.THREE), - 14 - ); - - // Test echo function - Assert.equal( - await CustomTypes.echoGappedValue(CustomTypes.GappedEnum.ONE), - CustomTypes.GappedEnum.ONE - ); - Assert.equal( - await CustomTypes.echoGappedValue(CustomTypes.GappedEnum.TWO), - CustomTypes.GappedEnum.TWO - ); - Assert.equal( - await CustomTypes.echoGappedValue(CustomTypes.GappedEnum.THREE), - CustomTypes.GappedEnum.THREE - ); - - // Test validation for non-existent values - // Values in gaps should be rejected - await Assert.rejects( - CustomTypes.getGappedDiscriminant(0), - UniFFITypeError, - "Should reject value 0 which is below the lowest enum variant" - ); - - await Assert.rejects( - CustomTypes.getGappedDiscriminant(9), - UniFFITypeError, - "Should reject value 9 which is just below a valid enum variant" - ); - - await Assert.rejects( - CustomTypes.getGappedDiscriminant(12), - UniFFITypeError, - "Should reject value 12 which is in a gap between valid enum variants" - ); - - await Assert.rejects( - CustomTypes.getGappedDiscriminant(13), - UniFFITypeError, - "Should reject value 13 which is in a gap between valid enum variants" - ); - - await Assert.rejects( - CustomTypes.getGappedDiscriminant(15), - UniFFITypeError, - "Should reject value 15 which is above the highest enum variant" - ); - - // Test non-integer values - await Assert.rejects( - CustomTypes.getGappedDiscriminant("ONE"), - UniFFITypeError, - "Should reject string value instead of enum" - ); - - await Assert.rejects( - CustomTypes.getGappedDiscriminant(null), - UniFFITypeError, - "Should reject null value instead of enum" - ); - - await Assert.rejects( - CustomTypes.getGappedDiscriminant(undefined), - UniFFITypeError, - "Should reject undefined value instead of enum" - ); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_external_types.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_external_types.js deleted file mode 100644 index 16894477cca4..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_external_types.js +++ /dev/null @@ -1,25 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const ExternalTypes = ChromeUtils.importESModule( - "resource://gre/modules/RustExternalTypes.sys.mjs" -); -const Sprites = ChromeUtils.importESModule( - "resource://gre/modules/RustSprites.sys.mjs" -); - -add_task(async function testDataTypes() { - const line = new ExternalTypes.Line({ - start: await new ExternalTypes.Point({ coordX: 0, coordY: 0 }), - end: await new ExternalTypes.Point({ coordX: 2, coordY: 1 }), - }); - Assert.equal(await ExternalTypes.gradient(line), 0.5); - - Assert.equal(await ExternalTypes.gradient(null), 0.0); -}); - -add_task(async function testInterface() { - const s = await Sprites.Sprite.init(new Sprites.Point({ x: 100, y: 100 })); - await ExternalTypes.moveSpriteToOrigin(s); - Assert.deepEqual(await s.getPosition(), new Sprites.Point({ x: 0, y: 0 })); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_futures.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_futures.js deleted file mode 100644 index d9786ac3be65..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_futures.js +++ /dev/null @@ -1,90 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const { setTimeout } = ChromeUtils.importESModule( - "resource://gre/modules/Timer.sys.mjs" -); - -const RustFutures = ChromeUtils.importESModule( - "resource://gre/modules/RustFutures.sys.mjs" -); - -RustFutures.initializeGeckoGlobalWorkerQueue(); - -add_task(async function simpleTest() { - const tester = RustFutures.FutureTester.init(); - const f = tester.makeFuture(); - shortDelay().then(() => runCompleteFutures(tester, 42, 1)); - Assert.equal(await f, 42); -}); - -async function runCompleteFutures(tester, value, futureCount) { - var completedCount = 0; - // Call completeFutures in a loop until we've completed the expected number of futures. - // Since makeFuture is an async call, we need to make sure that completeFutures runs after all - // the futures have been made and inserted into the internal vec. - for (;;) { - completedCount += tester.completeFutures(value); - if (completedCount >= futureCount) { - return; - } - await shortDelay(); - } -} - -add_task(async function twoFutures() { - const tester = RustFutures.FutureTester.init(); - // Create a future and complete it using an async task - const f1 = tester.makeFuture(); - const f2 = tester.makeFuture(); - runCompleteFutures(tester, 84, 2); - Assert.deepEqual(await Promise.all([f1, f2]), [84, 84]); -}); - -add_task(async function roundtripFunctions() { - Assert.equal(await RustFutures.roundtripU8(42), 42); - Assert.equal(await RustFutures.roundtripI8(-42), -42); - Assert.equal(await RustFutures.roundtripU16(42), 42); - Assert.equal(await RustFutures.roundtripI16(-42), -42); - Assert.equal(await RustFutures.roundtripU32(42), 42); - Assert.equal(await RustFutures.roundtripI32(-42), -42); - Assert.equal(await RustFutures.roundtripU64(42), 42); - Assert.equal(await RustFutures.roundtripI64(-42), -42); - Assert.equal(await RustFutures.roundtripF32(0.5), 0.5); - Assert.equal(await RustFutures.roundtripF64(-0.5), -0.5); - Assert.equal(await RustFutures.roundtripString("hi"), "hi"); - Assert.deepEqual(await RustFutures.roundtripVec([42]), [42]); - Assert.deepEqual(await RustFutures.roundtripMap({ hello: "world" }), { - hello: "world", - }); - const obj = RustFutures.Traveller.init("Alice"); - Assert.equal((await RustFutures.roundtripObj(obj)).name(), "Alice"); -}); - -add_task(async function wakeWhenNotReady() { - const tester = RustFutures.FutureTester.init(); - var isResolved = false; - const f = tester.makeFuture().then(value => { - isResolved = true; - return value; - }); - // This will wake up the Rust wakers, but while the futures are still not ready - // The JS promises should stay unresolved - tester.wakeFutures(); - await shortDelay(); - Assert.equal(isResolved, false); - // Okay, now let test revolving the futures - runCompleteFutures(tester, 42, 1); - Assert.equal(await f, 42); - Assert.equal(isResolved, true); -}); - -add_task(async function testWorkerQueue() { - Assert.equal(await RustFutures.expensiveComputation(), 1000); -}); - -// Utility function that sleeps for 10ms. -async function shortDelay() { - // eslint-disable-next-line mozilla/no-arbitrary-setTimeout - await new Promise(resolve => setTimeout(resolve, 10)); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_geometry.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_geometry.js deleted file mode 100644 index 1028cd37c25c..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_geometry.js +++ /dev/null @@ -1,21 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Geometry = ChromeUtils.importESModule( - "resource://gre/modules/RustGeometry.sys.mjs" -); - -add_task(async function () { - const ln1 = new Geometry.Line({ - start: new Geometry.Point({ coordX: 0, coordY: 0 }), - end: new Geometry.Point({ coordX: 1, coordY: 2 }), - }); - const ln2 = new Geometry.Line({ - start: new Geometry.Point({ coordX: 1, coordY: 1 }), - end: new Geometry.Point({ coordX: 2, coordY: 2 }), - }); - const origin = new Geometry.Point({ coordX: 0, coordY: 0 }); - Assert.ok((await Geometry.intersection(ln1, ln2)).equals(origin)); - Assert.deepEqual(await Geometry.intersection(ln1, ln2), origin); - Assert.strictEqual(await Geometry.intersection(ln1, ln1), null); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_refcounts.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_refcounts.js deleted file mode 100644 index 790d981104ce..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_refcounts.js +++ /dev/null @@ -1,57 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const { getSingleton, getJsRefcount } = ChromeUtils.importESModule( - "resource://gre/modules/RustRefcounts.sys.mjs" -); - -// Test refcounts when we call methods. -// -// Each method call requires that we clone the Arc pointer on the JS side, then pass it to Rust -// which will consumer the reference. Make sure we get this right - -function createObjectAndCallMethods() { - const obj = getSingleton(); - obj.method(); -} - -add_test(() => { - // Create an object that we'll keep around. If the ref count ends up being low, we don't want - // to reduce it below 0, since the Rust code may catch that and clamp it - const obj = getSingleton(); - createObjectAndCallMethods(); - Cu.forceGC(); - Cu.forceCC(); - do_test_pending(); - do_timeout(500, () => { - Assert.equal(getJsRefcount(), 1); - // Use `obj` to avoid unused warnings and try to ensure that JS doesn't destroy it early - obj.method(); - do_test_finished(); - run_next_test(); - }); -}); - -// Test refcounts when creating/destroying objects -function createAndDeleteObjects() { - [getSingleton(), getSingleton(), getSingleton()]; -} - -add_test(() => { - const obj = getSingleton(); - createAndDeleteObjects(); - Cu.forceGC(); - Cu.forceCC(); - do_timeout(500, () => { - Assert.equal(getJsRefcount(), 1); - obj.method(); - do_test_finished(); - run_next_test(); - }); -}); - -// As we implement more UniFFI features we should probably add refcount tests for it. -// Some features that should probably have tests: -// - Async methods -// - UniFFI builtin trait methods like 'to_string' -// - Rust trait objects diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_rondpoint.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_rondpoint.js deleted file mode 100644 index 4ad76074f952..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_rondpoint.js +++ /dev/null @@ -1,332 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Rondpoint = ChromeUtils.importESModule( - "resource://gre/modules/RustRondpoint.sys.mjs" -); - -const { - Dictionnaire, - Enumeration, - copieDictionnaire, - copieEnumeration, - copieEnumerations, - copieCarte, - EnumerationAvecDonnees, - switcheroo, - Retourneur, - DictionnaireNombresSignes, - DictionnaireNombres, - Stringifier, - Optionneur, - OptionneurDictionnaire, -} = Rondpoint; -add_task(async function () { - const dico = new Dictionnaire({ - un: Enumeration.DEUX, - deux: true, - petitNombre: 0, - grosNombre: 1235, - }); - const copyDico = await copieDictionnaire(dico); - Assert.deepEqual(dico, copyDico); - - Assert.equal(await copieEnumeration(Enumeration.DEUX), Enumeration.DEUX); - Assert.deepEqual( - await copieEnumerations([Enumeration.UN, Enumeration.DEUX]), - [Enumeration.UN, Enumeration.DEUX] - ); - const obj = { - 0: new EnumerationAvecDonnees.Zero(), - 1: new EnumerationAvecDonnees.Un(1), - 2: new EnumerationAvecDonnees.Deux(2, "deux"), - }; - - Assert.deepEqual(await copieCarte(obj), obj); - - const zero = new EnumerationAvecDonnees.Zero(); - const one = new EnumerationAvecDonnees.Un(1); - const two = new EnumerationAvecDonnees.Deux(2); - Assert.notEqual(zero, one); - Assert.notEqual(one, two); - - Assert.deepEqual(zero, new EnumerationAvecDonnees.Zero()); - Assert.deepEqual(one, new EnumerationAvecDonnees.Un(1)); - Assert.notDeepEqual(one, new EnumerationAvecDonnees.Un(4)); - - Assert.ok(await switcheroo(false)); - // Test the roundtrip across the FFI. - // This shows that the values we send come back in exactly the same state as we sent them. - // i.e. it shows that lowering from JS and lifting into rust is symmetrical with - // lowering from rust and lifting into JS. - - const rt = await Retourneur.init(); - - const affirmAllerRetour = async (arr, fn, equalFn) => { - for (const member of arr) { - if (equalFn) { - equalFn(await fn(member), member); - } else { - Assert.equal(await fn(member), member); - } - } - }; - - // Booleans - await affirmAllerRetour([true, false], rt.identiqueBoolean.bind(rt)); - - // Bytes - await affirmAllerRetour([-128, 127], rt.identiqueI8.bind(rt)); - await affirmAllerRetour([0, 0xff], rt.identiqueU8.bind(rt)); - - // Shorts - await affirmAllerRetour([-32768, 32767], rt.identiqueI16.bind(rt)); - await affirmAllerRetour([0, 0xffff], rt.identiqueU16.bind(rt)); - - // Ints - await affirmAllerRetour( - [0, 1, -1, -2147483648, 2147483647], - rt.identiqueI32.bind(rt) - ); - await affirmAllerRetour([0, 0xffffffff], rt.identiqueU32.bind(rt)); - - // Longs - // NOTE: we cannot represent greater than `Number.MAX_SAFE_INTEGER` - await affirmAllerRetour( - [0, 1, -1, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], - rt.identiqueI64.bind(rt) - ); - await affirmAllerRetour( - [0, Number.MAX_SAFE_INTEGER], - rt.identiqueU64.bind(rt) - ); - - // Floats - const equalFloats = (a, b) => Assert.ok(Math.abs(a - b) <= Number.EPSILON); - await affirmAllerRetour( - [0.0, 0.5, 0.25, 1.5], - rt.identiqueFloat.bind(rt), - equalFloats - ); - // Some float value's precision gets messed up, an example is 3.22, 100.223, etc - // await affirmAllerRetour([0.0, 0.5, 0.25, 1.5, 100.223], rt.identiqueFloat.bind(rt), equalFloats); - - // Double (although on the JS side doubles are limited since they are also represented by Number) - await affirmAllerRetour( - [0.0, 0.5, 0.25, 1.5], - rt.identiqueDouble.bind(rt), - equalFloats - ); - - // Strings - await affirmAllerRetour( - [ - "", - "abc", - "null\u0000byte", - "été", - "ښي لاس ته لوستلو لوستل", - "😻emoji 👨‍👧‍👦multi-emoji, 🇨🇭a flag, a canal, panama", - ], - rt.identiqueString.bind(rt) - ); - - await affirmAllerRetour( - [-1, 0, 1].map( - n => - new DictionnaireNombresSignes({ - petitNombre: n, - courtNombre: n, - nombreSimple: n, - grosNombre: n, - }) - ), - rt.identiqueNombresSignes.bind(rt), - (a, b) => Assert.deepEqual(a, b) - ); - - await affirmAllerRetour( - [0, 1].map( - n => - new DictionnaireNombres({ - petitNombre: n, - courtNombre: n, - nombreSimple: n, - grosNombre: n, - }) - ), - rt.identiqueNombres.bind(rt), - (a, b) => Assert.deepEqual(a, b) - ); - - // Test one way across the FFI. - // - // We send one representation of a value to lib.rs, and it transforms it into another, a string. - // lib.rs sends the string back, and then we compare here in js. - // - // This shows that the values are transformed into strings the same way in both js and rust. - // i.e. if we assume that the string return works (we test this assumption elsewhere) - // we show that lowering from js and lifting into rust has values that both js and rust - // both stringify in the same way. i.e. the same values. - // - // If we roundtripping proves the symmetry of our lowering/lifting from here to rust, and lowering/lifting from rust to here, - // and this convinces us that lowering/lifting from here to rust is correct, then - // together, we've shown the correctness of the return leg. - const st = await Stringifier.init(); - - const affirmEnchaine = async (arr, fn) => { - for (const member of arr) { - Assert.equal(await fn(member), String(member)); - } - }; - - // Booleans - await affirmEnchaine([true, false], st.toStringBoolean.bind(st)); - - // Bytes - await affirmEnchaine([-128, 127], st.toStringI8.bind(st)); - await affirmEnchaine([0, 0xff], st.toStringU8.bind(st)); - - // Shorts - await affirmEnchaine([-32768, 32767], st.toStringI16.bind(st)); - await affirmEnchaine([0, 0xffff], st.toStringU16.bind(st)); - - // Ints - await affirmEnchaine( - [0, 1, -1, -2147483648, 2147483647], - st.toStringI32.bind(st) - ); - await affirmEnchaine([0, 0xffffffff], st.toStringU32.bind(st)); - - // Longs - // NOTE: we cannot represent greater than `Number.MAX_SAFE_INTEGER` - await affirmEnchaine( - [0, 1, -1, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER], - st.toStringI64.bind(st) - ); - await affirmEnchaine([0, Number.MAX_SAFE_INTEGER], st.toStringU64.bind(st)); - - // Floats - await affirmEnchaine([0.0, 0.5, 0.25, 1.5], st.toStringFloat.bind(st)); - - // Doubles - await affirmEnchaine([0.0, 0.5, 0.25, 1.5], st.toStringDouble.bind(st)); - - // Prove to ourselves that default arguments are being used. - // Step 1: call the methods without arguments, and check against the UDL. - const op = await Optionneur.init(); - - Assert.equal(await op.sinonString(), "default"); - - Assert.ok(!(await op.sinonBoolean())); - - Assert.deepEqual(await op.sinonSequence(), []); - - Assert.equal(await op.sinonNull(), null); - Assert.equal(await op.sinonZero(), 0); - - // decimal integers - Assert.equal(await op.sinonI8Dec(), -42); - Assert.equal(await op.sinonU8Dec(), 42); - Assert.equal(await op.sinonI16Dec(), 42); - Assert.equal(await op.sinonU16Dec(), 42); - Assert.equal(await op.sinonI32Dec(), 42); - Assert.equal(await op.sinonU32Dec(), 42); - Assert.equal(await op.sinonI64Dec(), 42); - Assert.equal(await op.sinonU64Dec(), 42); - - // hexadecimal integers - Assert.equal(await op.sinonI8Hex(), -0x7f); - Assert.equal(await op.sinonU8Hex(), 0xff); - Assert.equal(await op.sinonI16Hex(), 0x7f); - Assert.equal(await op.sinonU16Hex(), 0xffff); - Assert.equal(await op.sinonI32Hex(), 0x7fffffff); - Assert.equal(await op.sinonU32Hex(), 0xffffffff); - // The following are too big to be represented by js `Number` - // Assert.equal(await op.sinonI64Hex(), 0x7fffffffffffffff); - // Assert.equal(await op.sinonU64Hex(), 0xffffffffffffffff); - - // octal integers - Assert.equal(await op.sinonU32Oct(), 0o755); - - // floats - Assert.equal(await op.sinonF32(), 42.0); - Assert.equal(await op.sinonF64(), 42.1); - - // enums - Assert.equal(await op.sinonEnum(), Enumeration.TROIS); - - // Step 2. Convince ourselves that if we pass something else, then that changes the output. - // We have shown something coming out of the sinon methods, but without eyeballing the Rust - // we can't be sure that the arguments will change the return value. - - await affirmAllerRetour(["foo", "bar"], op.sinonString.bind(op)); - await affirmAllerRetour([true, false], op.sinonBoolean.bind(op)); - await affirmAllerRetour([["a", "b"], []], op.sinonSequence.bind(op), (a, b) => - Assert.deepEqual(a, b) - ); - - // Optionals - await affirmAllerRetour(["0", "1"], op.sinonNull.bind(op)); - await affirmAllerRetour([0, 1], op.sinonZero.bind(op)); - - // integers - await affirmAllerRetour([0, 1], op.sinonU8Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI8Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU16Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI16Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU32Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI32Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU64Dec.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI64Dec.bind(op)); - - await affirmAllerRetour([0, 1], op.sinonU8Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI8Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU16Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI16Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU32Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI32Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU64Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonI64Hex.bind(op)); - await affirmAllerRetour([0, 1], op.sinonU32Oct.bind(op)); - - // Floats - await affirmAllerRetour([0.0, 1.0], op.sinonF32.bind(op)); - await affirmAllerRetour([0.0, 1.0], op.sinonF64.bind(op)); - - // enums - await affirmAllerRetour( - [Enumeration.UN, Enumeration.DEUX, Enumeration.TROIS], - op.sinonEnum.bind(op) - ); - - // Testing defaulting properties in record types. - const defaultes = new OptionneurDictionnaire(); - const explicite = new OptionneurDictionnaire( - -8, - 8, - -16, - 0x10, - -32, - 32, - -64, - 64, - 4.0, - 8.0, - true, - "default", - [], - Enumeration.DEUX, - null - ); - - Assert.deepEqual(defaultes, explicite); - - // …and makes sure they travel across and back the FFI. - - await affirmAllerRetour( - [defaultes, explicite], - rt.identiqueOptionneurDictionnaire.bind(rt), - (a, b) => Assert.deepEqual(a, b) - ); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_sprites.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_sprites.js deleted file mode 100644 index e1f29cd9c857..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_sprites.js +++ /dev/null @@ -1,34 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Sprites = ChromeUtils.importESModule( - "resource://gre/modules/RustSprites.sys.mjs" -); - -add_task(async function () { - Assert.ok(Sprites.Sprite); - - const sempty = await Sprites.Sprite.init(null); - Assert.deepEqual( - await sempty.getPosition(), - new Sprites.Point({ x: 0, y: 0 }) - ); - - const s = await Sprites.Sprite.init(new Sprites.Point({ x: 0, y: 1 })); - Assert.deepEqual(await s.getPosition(), new Sprites.Point({ x: 0, y: 1 })); - - s.moveTo(new Sprites.Point({ x: 1, y: 2 })); - Assert.deepEqual(await s.getPosition(), new Sprites.Point({ x: 1, y: 2 })); - - s.moveBy(new Sprites.Vector({ dx: -4, dy: 2 })); - Assert.deepEqual(await s.getPosition(), new Sprites.Point({ x: -3, y: 4 })); - - const srel = await Sprites.Sprite.newRelativeTo( - new Sprites.Point({ x: 0, y: 1 }), - new Sprites.Vector({ dx: 1, dy: 1.5 }) - ); - Assert.deepEqual( - await srel.getPosition(), - new Sprites.Point({ x: 1, y: 2.5 }) - ); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_todolist.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_todolist.js deleted file mode 100644 index 42cca795c3d8..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_todolist.js +++ /dev/null @@ -1,80 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const { TodoList, TodoEntry, TodoError, getDefaultList, setDefaultList } = - ChromeUtils.importESModule("resource://gre/modules/RustTodolist.sys.mjs"); - -add_task(async function () { - const todo = await TodoList.init(); - - await Assert.rejects( - todo.getLastEntry(), - TodoError, - "getLastEntry called before there were any entries" - ); - - const entry = new TodoEntry({ - text: "Write bindings for strings in records", - }); - - await todo.addItem("Write JS bindings"); - Assert.equal(await todo.getLast(), "Write JS bindings"); - - await todo.addItem("Write tests for bindings"); - Assert.equal(await todo.getLast(), "Write tests for bindings"); - - await todo.addEntry(entry); - Assert.equal(await todo.getLast(), "Write bindings for strings in records"); - Assert.equal( - (await todo.getLastEntry()).text, - "Write bindings for strings in records" - ); - Assert.ok((await todo.getLastEntry()).equals(entry)); - - await todo.addItem( - "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣" - ); - Assert.equal( - await todo.getLast(), - "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣" - ); - - const entry2 = new TodoEntry({ - text: "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣", - }); - await todo.addEntry(entry2); - Assert.equal( - (await todo.getLastEntry()).text, - "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣" - ); - - const todo2 = await TodoList.init(); - Assert.notEqual(todo, todo2); - Assert.notStrictEqual(todo, todo2); - - Assert.strictEqual(await getDefaultList(), null); - - await setDefaultList(todo); - Assert.deepEqual( - await todo.getItems(), - await (await getDefaultList()).getItems() - ); - - todo2.makeDefault(); - Assert.deepEqual( - await todo2.getItems(), - await (await getDefaultList()).getItems() - ); - - await todo.addItem("Test liveness after being demoted from default"); - Assert.equal( - await todo.getLast(), - "Test liveness after being demoted from default" - ); - - todo2.addItem("Test shared state through local vs default reference"); - Assert.equal( - await (await getDefaultList()).getLast(), - "Test shared state through local vs default reference" - ); -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_trait_interfaces.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_trait_interfaces.js deleted file mode 100644 index f3c78cd6e247..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_trait_interfaces.js +++ /dev/null @@ -1,12 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const TraitInterfaces = ChromeUtils.importESModule( - "resource://gre/modules/RustUniffiTraitInterfaces.sys.mjs" -); - -const calculator = TraitInterfaces.makeCalculator(); -Assert.equal(calculator.add(4, 8), 12); - -const buggyCalculator = TraitInterfaces.makeBuggyCalculator(); -Assert.equal(buggyCalculator.add(4, 8), 13); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_type_checking.js b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_type_checking.js deleted file mode 100644 index 6e2159d42085..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_type_checking.js +++ /dev/null @@ -1,127 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Arithmetic = ChromeUtils.importESModule( - "resource://gre/modules/RustArithmetic.sys.mjs" -); -const Geometry = ChromeUtils.importESModule( - "resource://gre/modules/RustGeometry.sys.mjs" -); -const TodoList = ChromeUtils.importESModule( - "resource://gre/modules/RustTodolist.sys.mjs" -); -const Rondpoint = ChromeUtils.importESModule( - "resource://gre/modules/RustRondpoint.sys.mjs" -); -const { UniFFITypeError } = ChromeUtils.importESModule( - "resource://gre/modules/UniFFI.sys.mjs" -); - -add_task(async function testFunctionArguments() { - await Assert.rejects( - Arithmetic.add(2), - UniFFITypeError, - "add() call missing argument" - ); - Assert.throws( - () => new Geometry.Point(0.0), - UniFFITypeError, - "Point constructor missing argument" - ); -}); - -add_task(async function testNumberOverflow() { - // MAX_SAFE_INTEGER + 1 fits in a Rust u64, but overflows a JS Number. - // This overflow should be caught by the C++ code. - await Assert.rejects( - Arithmetic.add(Number.MAX_SAFE_INTEGER, 1), - /RangeError/, - "add() call that overflows Number.MAX_SAFE_INTEGER" - ); -}); - -add_task(async function testObjectPointers() { - const todo = await TodoList.TodoList.init(); - const stringifier = await Rondpoint.Stringifier.init(); - await todo.getEntries(); // OK - todo[TodoList.UnitTestObjs.uniffiObjectPtr] = - stringifier[Rondpoint.UnitTestObjs.uniffiObjectPtr]; - - await Assert.rejects( - todo.getEntries(), // the pointer is incorrect, should throw - /Incorrect UniFFI pointer type/, - "getEntries() with wrong pointer type" - ); - - await Assert.rejects( - TodoList.setDefaultList(1), // expecting an object - /Object is not a 'TodoList' instance/, - "attempting to lift the wrong object type" - ); -}); - -add_task(async function testEnumTypeCheck() { - await Assert.rejects( - Rondpoint.copieEnumeration("invalid"), // Not an integer value - /e:/, // Ensure exception message includes the argument name - "copieEnumeration() with non-Enumeration value should throw" - ); - await Assert.rejects( - Rondpoint.copieEnumeration(99), // Integer, but doesn't map to a variant - /e:/, // Ensure exception message includes the argument name - "copieEnumeration() with non-Enumeration value should throw" - ); - await Assert.rejects( - Rondpoint.copieEnumeration(4), // Integer, but doesn't map to a variant - /e:/, // Ensure exception message includes the argument name - "copieEnumeration() with non-Enumeration value should throw" - ); -}); - -add_task(async function testRecordTypeCheck() { - await Assert.rejects( - Geometry.gradient(123), // Not a Line object - UniFFITypeError, - "gradient with non-Line object should throw" - ); -}); - -add_task(async function testOptionTypeCheck() { - const optionneur = await Rondpoint.Optionneur.init(); - await Assert.rejects( - optionneur.sinonNull(0), - UniFFITypeError, - "sinonNull with non-string should throw" - ); -}); - -add_task(async function testSequenceTypeCheck() { - const todo = await TodoList.TodoList.init(); - await Assert.rejects( - todo.addEntries("not a list"), - UniFFITypeError, - "addEntries with non-list should throw" - ); - - await Assert.rejects( - todo.addEntries(["not TodoEntry"]), - /entries\[0]/, - "addEntries with non TodoEntry item should throw" - ); -}); - -add_task(async function testMapTypeCheck() { - await Assert.rejects( - Rondpoint.copieCarte("not a map"), - UniFFITypeError, - "copieCarte with a non-map should throw" - ); - - await Assert.rejects( - Rondpoint.copieCarte({ x: 1 }), - /c\[x]/, - "copieCarte with a wrong value type should throw" - ); - - // TODO: test key types once we implement https://bugzilla.mozilla.org/show_bug.cgi?id=1809459 -}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/xpcshell.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/xpcshell.toml deleted file mode 100644 index 39ca043f9ebc..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/xpcshell.toml +++ /dev/null @@ -1,25 +0,0 @@ -[DEFAULT] - -["test_arithmetic.js"] - -["test_callbacks.js"] - -["test_custom_types.js"] - -["test_external_types.js"] - -["test_futures.js"] - -["test_geometry.js"] - -["test_refcounts.js"] - -["test_rondpoint.js"] - -["test_sprites.js"] - -["test_todolist.js"] - -["test_trait_interfaces.js"] - -["test_type_checking.js"] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/Cargo.toml deleted file mode 100644 index 6673d01e07a5..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "uniffi-example-todolist" -edition = "2021" -version = "0.22.0" -authors = ["Firefox Sync Team "] -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] -name = "uniffi_todolist" - -[dependencies] -uniffi = { workspace = true } -once_cell = "1.12" -thiserror = "1.0" - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } - -[dev-dependencies] -uniffi = { workspace = true, features = ["bindgen-tests"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/build.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/build.rs deleted file mode 100644 index 2dd2f68b7521..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -fn main() { - uniffi::generate_scaffolding("src/todolist.udl").unwrap(); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/src/lib.rs deleted file mode 100644 index b339e24c617b..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/src/lib.rs +++ /dev/null @@ -1,150 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::{Arc, RwLock}; - -use once_cell::sync::Lazy; - -#[derive(Debug, Clone)] -pub struct TodoEntry { - text: String, -} - -// There is a single "default" TodoList that can be shared -// by all consumers of this component. Depending on requirements, -// a real app might like to use a `Weak<>` rather than an `Arc<>` -// here to reduce the risk of circular references. -static DEFAULT_LIST: Lazy>>> = Lazy::new(|| RwLock::new(None)); - -#[derive(Debug, thiserror::Error)] -pub enum TodoError { - #[error("The todo does not exist!")] - TodoDoesNotExist, - #[error("The todolist is empty!")] - EmptyTodoList, - #[error("That todo already exists!")] - DuplicateTodo, - #[error("Empty String error!: {0}")] - EmptyString(String), - #[error("I am a delegated Error: {0}")] - DeligatedError(#[from] std::io::Error), -} - -/// Get a reference to the global default TodoList, if set. -/// -fn get_default_list() -> Option> { - DEFAULT_LIST.read().unwrap().clone() -} - -/// Set the global default TodoList. -/// -/// This will silently drop any previously set value. -/// -fn set_default_list(list: Arc) { - *DEFAULT_LIST.write().unwrap() = Some(list); -} - -/// Create a new TodoEntry from the given string. -/// -fn create_entry_with>(item: S) -> Result { - let text = item.into(); - if text.is_empty() { - return Err(TodoError::EmptyString( - "Cannot add empty string as entry".to_string(), - )); - } - Ok(TodoEntry { text }) -} - -type Result = std::result::Result; - -// A simple Todolist. -// UniFFI requires that we use interior mutability for managing mutable state, so we wrap our `Vec` in a RwLock. -// (A Mutex would also work, but a RwLock is more appropriate for this use-case, so we use it). -#[derive(Debug)] -pub struct TodoList { - items: RwLock>, -} - -impl TodoList { - pub fn new() -> Self { - Self { - items: RwLock::new(Vec::new()), - } - } - - pub fn add_item>(&self, item: S) -> Result<()> { - let item = item.into(); - if item.is_empty() { - return Err(TodoError::EmptyString( - "Cannot add empty string as item".to_string(), - )); - } - let mut items = self.items.write().unwrap(); - if items.contains(&item) { - return Err(TodoError::DuplicateTodo); - } - items.push(item); - Ok(()) - } - - pub fn get_last(&self) -> Result { - let items = self.items.read().unwrap(); - items.last().cloned().ok_or(TodoError::EmptyTodoList) - } - - pub fn get_first(&self) -> Result { - let items = self.items.read().unwrap(); - items.first().cloned().ok_or(TodoError::EmptyTodoList) - } - - pub fn add_entries(&self, entries: Vec) { - let mut items = self.items.write().unwrap(); - items.extend(entries.into_iter().map(|e| e.text)) - } - - pub fn add_entry(&self, entry: TodoEntry) -> Result<()> { - self.add_item(entry.text) - } - - pub fn add_items>(&self, items: Vec) { - let mut my_items = self.items.write().unwrap(); - my_items.extend(items.into_iter().map(Into::into)) - } - - pub fn get_items(&self) -> Vec { - let items = self.items.read().unwrap(); - items.clone() - } - - pub fn get_entries(&self) -> Vec { - let items = self.items.read().unwrap(); - items - .iter() - .map(|text| TodoEntry { text: text.clone() }) - .collect() - } - - pub fn get_last_entry(&self) -> Result { - let text = self.get_last()?; - Ok(TodoEntry { text }) - } - - pub fn clear_item>(&self, item: S) -> Result<()> { - let item = item.into(); - let mut items = self.items.write().unwrap(); - let idx = items - .iter() - .position(|s| s == &item) - .ok_or(TodoError::TodoDoesNotExist)?; - items.remove(idx); - Ok(()) - } - - pub fn make_default(self: Arc) { - set_default_list(self); - } -} - -uniffi::include_scaffolding!("todolist"); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/src/todolist.udl b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/src/todolist.udl deleted file mode 100644 index 5c923314cd6a..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/src/todolist.udl +++ /dev/null @@ -1,38 +0,0 @@ -namespace todolist { - TodoList? get_default_list(); - undefined set_default_list(TodoList list); - - [Throws=TodoError] - TodoEntry create_entry_with(string todo); -}; - -dictionary TodoEntry { - string text; -}; - -[Error] -enum TodoError { - "TodoDoesNotExist", "EmptyTodoList", "DuplicateTodo", "EmptyString", "DeligatedError" -}; - -interface TodoList { - constructor(); - [Throws=TodoError] - void add_item(string todo); - [Throws=TodoError] - void add_entry(TodoEntry entry); - sequence get_entries(); - sequence get_items(); - void add_entries(sequence entries); - void add_items(sequence items); - [Throws=TodoError] - TodoEntry get_last_entry(); - [Throws=TodoError] - string get_last(); - [Throws=TodoError] - string get_first(); - [Throws=TodoError] - void clear_item(string todo); - [Self=ByArc] - undefined make_default(); -}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.kts b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.kts deleted file mode 100644 index bb2b292224d0..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.kts +++ /dev/null @@ -1,83 +0,0 @@ -import uniffi.todolist.* - -val todo = TodoList() - -// This throws an exception: -try { - todo.getLast() - throw RuntimeException("Should have thrown a TodoError!") -} catch (e: TodoException.EmptyTodoList) { - // It's okay, we don't have any items yet! -} - -try { - createEntryWith("") - throw RuntimeException("Should have thrown a TodoError!") -} catch (e: TodoException) { - // It's okay, the string was empty! - assert(e is TodoException.EmptyString) - assert(e !is TodoException.EmptyTodoList) -} - -todo.addItem("Write strings support") - -assert(todo.getLast() == "Write strings support") - -todo.addItem("Write tests for strings support") - -assert(todo.getLast() == "Write tests for strings support") - -val entry = createEntryWith("Write bindings for strings as record members") - -todo.addEntry(entry) -assert(todo.getLast() == "Write bindings for strings as record members") -assert(todo.getLastEntry().text == "Write bindings for strings as record members") - -todo.addItem("Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") -assert(todo.getLast() == "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") - -val entry2 = TodoEntry("Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") -todo.addEntry(entry2) -assert(todo.getLastEntry().text == "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") - -assert(todo.getEntries().size == 5) - -todo.addEntries(listOf(TodoEntry("foo"), TodoEntry("bar"))) -assert(todo.getEntries().size == 7) -assert(todo.getLastEntry().text == "bar") - -todo.addItems(listOf("bobo", "fofo")) -assert(todo.getItems().size == 9) -assert(todo.getItems()[7] == "bobo") - -assert(getDefaultList() == null) - -// Note that each individual object instance needs to be explicitly destroyed, -// either by using the `.use` helper or explicitly calling its `.destroy` method. -// Failure to do so will leak the underlying Rust object. -TodoList().use { todo2 -> - setDefaultList(todo) - getDefaultList()!!.use { default -> - assert(todo.getEntries() == default.getEntries()) - assert(todo2.getEntries() != default.getEntries()) - } - - todo2.makeDefault() - getDefaultList()!!.use { default -> - assert(todo.getEntries() != default.getEntries()) - assert(todo2.getEntries() == default.getEntries()) - } - - todo.addItem("Test liveness after being demoted from default") - assert(todo.getLast() == "Test liveness after being demoted from default") - - todo2.addItem("Test shared state through local vs default reference") - getDefaultList()!!.use { default -> - assert(default.getLast() == "Test shared state through local vs default reference") - } -} - -// Ensure the kotlin version of deinit doesn't crash, and is idempotent. -todo.destroy() -todo.destroy() - diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.py b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.py deleted file mode 100644 index e4e2cda6d6f8..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.py +++ /dev/null @@ -1,56 +0,0 @@ -from todolist import TodoEntry, TodoList, get_default_list, set_default_list - -todo = TodoList() - -entry = TodoEntry(text="Write bindings for strings in records") - -todo.add_item("Write python bindings") - -assert todo.get_last() == "Write python bindings" - -todo.add_item("Write tests for bindings") - -assert todo.get_last() == "Write tests for bindings" - -todo.add_entry(entry) - -assert todo.get_last() == "Write bindings for strings in records" -assert todo.get_last_entry().text == "Write bindings for strings in records" - -todo.add_item( - "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣" -) -assert ( - todo.get_last() - == "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣" -) - -entry2 = TodoEntry( - text="Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣" -) -todo.add_entry(entry2) -assert ( - todo.get_last_entry().text - == "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣" -) - -todo2 = TodoList() -assert todo != todo2 -assert todo is not todo2 - -assert get_default_list() is None - -set_default_list(todo) -assert todo.get_items() == get_default_list().get_items() - -todo2.make_default() -assert todo2.get_items() == get_default_list().get_items() - -todo.add_item("Test liveness after being demoted from default") -assert todo.get_last() == "Test liveness after being demoted from default" - -todo2.add_item("Test shared state through local vs default reference") -assert ( - get_default_list().get_last() - == "Test shared state through local vs default reference" -) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.rb b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.rb deleted file mode 100644 index fc1a823f52a5..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.rb +++ /dev/null @@ -1,47 +0,0 @@ -# frozen_string_literal: true - -require 'test/unit' -require 'todolist' - -include Test::Unit::Assertions -include Todolist - -todo = TodoList.new -entry = TodoEntry.new(text: 'Write bindings for strings in records') - -todo.add_item('Write ruby bindings') - -assert_equal todo.get_last, 'Write ruby bindings' - -todo.add_item('Write tests for bindings') - -assert_equal todo.get_last, 'Write tests for bindings' - -todo.add_entry(entry) - -assert_equal todo.get_last, 'Write bindings for strings in records' -assert_equal todo.get_last_entry.text, 'Write bindings for strings in records' - -todo.add_item("Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") -assert_equal todo.get_last, "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣" - -entry2 = TodoEntry.new(text: "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") -todo.add_entry(entry2) -assert_equal todo.get_last_entry.text, "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣" - -todo2 = TodoList.new -assert todo2.get_items != todo.get_items - -assert Todolist.get_default_list == nil - -Todolist.set_default_list todo -assert todo.get_items == Todolist.get_default_list.get_items - -todo2.make_default -assert todo2.get_items == Todolist.get_default_list.get_items - -todo.add_item "Test liveness after being demoted from default" -assert todo.get_last == "Test liveness after being demoted from default" - -todo2.add_item "Test shared state through local vs default reference" -assert Todolist.get_default_list.get_last == "Test shared state through local vs default reference" diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.swift b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.swift deleted file mode 100644 index 6ce72cadb225..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/bindings/test_todolist.swift +++ /dev/null @@ -1,69 +0,0 @@ -import todolist - - -let todo = TodoList() -do { - let _ = try todo.getLast() - fatalError("Should have thrown an EmptyTodoList error!") -} catch TodoError.EmptyTodoList{ - //It's okay! There are not todos! -} -try! todo.addItem(todo: "Write swift bindings") -assert( try! todo.getLast() == "Write swift bindings") - -try! todo.addItem(todo: "Write tests for bindings") -assert(try! todo.getLast() == "Write tests for bindings") - -let entry = TodoEntry(text: "Write bindings for strings as record members") -try! todo.addEntry(entry: entry) -assert(try! todo.getLast() == "Write bindings for strings as record members") - -try! todo.addItem(todo: "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") -assert(try! todo.getLast() == "Test Ünicode hàndling without an entry can't believe I didn't test this at first 🤣") - -do { - let _ = try createEntryWith(todo: "") - fatalError("Should have thrown an EmptyString error!") -} catch TodoError.EmptyString { - // It's okay! It was an empty string -} - -let entry2 = TodoEntry(text: "Test Ünicode hàndling in an entry can't believe I didn't test this at first 🤣") -try! todo.addEntry(entry: entry2) -assert(try! todo.getLastEntry() == entry2) - -assert(todo.getEntries().count == 5) - -todo.addEntries(entries: [TodoEntry(text: "foo"), TodoEntry(text: "bar")]) -assert(todo.getEntries().count == 7) -assert(todo.getItems().count == 7) -assert(try! todo.getLast() == "bar") - -todo.addItems(items: ["bobo", "fofo"]) -assert(todo.getItems().count == 9) -assert(todo.getItems()[7] == "bobo") - -// Ensure deinit doesn't crash. -for _ in 0..<10 { - let list = TodoList() - try! list.addItem(todo: "todo") -} - -let todo2 = TodoList() - -assert(getDefaultList() == nil) - -setDefaultList(list: todo) -assert(todo.getItems() == getDefaultList()!.getItems()) -assert(todo2.getItems() != getDefaultList()!.getItems()) - -todo2.makeDefault() -assert(todo.getItems() != getDefaultList()!.getItems()) -assert(todo2.getItems() == getDefaultList()!.getItems()) - -try! todo.addItem(todo: "Test liveness after being demoted from default") -assert(try! todo.getLast() == "Test liveness after being demoted from default") - -try! todo2.addItem(todo: "Test shared state through local vs default reference") -assert(try! getDefaultList()!.getLast() == "Test shared state through local vs default reference") - diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/test_generated_bindings.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/test_generated_bindings.rs deleted file mode 100644 index cefdbfe1dc8f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/todolist/tests/test_generated_bindings.rs +++ /dev/null @@ -1,6 +0,0 @@ -uniffi::build_foreign_language_testcases!( - "tests/bindings/test_todolist.kts", - "tests/bindings/test_todolist.swift", - "tests/bindings/test_todolist.rb", - "tests/bindings/test_todolist.py" -); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/trait-interfaces/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/trait-interfaces/Cargo.toml deleted file mode 100644 index 0fdbc401fa7b..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/trait-interfaces/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "uniffi-trait-interfaces" -edition = "2021" -version = "0.22.0" -license = "MPL-2.0" -publish = false - -[lib] -crate-type = ["lib", "cdylib"] - -[dependencies] -uniffi = { workspace = true } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/trait-interfaces/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/fixtures/trait-interfaces/src/lib.rs deleted file mode 100644 index cf5f0496c6b0..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/trait-interfaces/src/lib.rs +++ /dev/null @@ -1,38 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::sync::Arc; - -#[uniffi::export] -pub trait Calc: Send + Sync { - fn add(&self, a: u32, b: u32) -> u32; -} - -#[uniffi::export] -pub fn make_calculator() -> Arc { - Arc::new(Calculator) -} - -struct Calculator; - -impl Calc for Calculator { - fn add(&self, a: u32, b: u32) -> u32 { - a + b - } -} - -#[uniffi::export] -pub fn make_buggy_calculator() -> Arc { - Arc::new(BuggyCalculator) -} - -struct BuggyCalculator; - -impl Calc for BuggyCalculator { - fn add(&self, a: u32, b: u32) -> u32 { - a + b + 1 - } -} - -uniffi::setup_scaffolding!(); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/mach_commands.py b/toolkit/components/uniffi-bindgen-gecko-js/mach_commands.py index cc2706255177..5bb5b98a7d59 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/mach_commands.py +++ b/toolkit/components/uniffi-bindgen-gecko-js/mach_commands.py @@ -2,18 +2,36 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. +import argparse import os import subprocess +from enum import Enum -from mach.decorators import Command, SubCommand +from mach.decorators import Command, CommandArgument, SubCommand CPP_PATH = "toolkit/components/uniffi-js/GeneratedScaffolding.cpp" JS_DIR = "toolkit/components/uniffi-bindgen-gecko-js/components/generated" -FIXTURE_JS_DIR = "toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated" +FIXTURE_JS_DIR = "toolkit/components/uniffi-bindgen-gecko-js/tests/generated" DOCS_PATH = "docs/rust-components/api/js/" -def build_gkrust_uniffi_library(command_context, package_name): +"""Library to generate bindings from""" + + +class SourceLibrary(Enum): + GKRUST_UNIFFI_COMPONENTS = "gkrust-uniffi-components" + UNIFFI_BINDINGS_BINDGEN_TESTS = "uniffi-bindgen-gecko-js-test-fixtures" + + +def cargo_args_for_library(source_library): + if source_library == SourceLibrary.GKRUST_UNIFFI_COMPONENTS: + return [] + elif source_library == SourceLibrary.UNIFFI_BINDINGS_BINDGEN_TESTS: + return ["--all-features"] + raise ValueError(source_library) + + +def build_gkrust_uniffi_library(command_context, source_library): uniffi_root = crate_root(command_context) print("Building gkrust-uniffi-components") cmdline = [ @@ -23,13 +41,14 @@ def build_gkrust_uniffi_library(command_context, package_name): "--manifest-path", os.path.join(command_context.topsrcdir, "Cargo.toml"), "--package", - package_name, - ] + source_library.value, + ] + cargo_args_for_library(source_library) + print(cmdline) subprocess.check_call(cmdline, cwd=uniffi_root) print() out_dir = os.path.join(command_context.topsrcdir, "target", "release") - lib_basename = "lib{}".format(package_name.replace("-", "_")) + lib_basename = "lib{}".format(source_library.value.replace("-", "_")) for ext in [".a", ".so", ".dll", ".dylib"]: candidate = os.path.join(out_dir, lib_basename + ext) if os.path.exists(candidate): @@ -67,6 +86,12 @@ def uniffi(command_context, *runargs, **lintargs): return 1 +def crate_root(command_context): + return os.path.join( + command_context.topsrcdir, "toolkit", "components", "uniffi-bindgen-gecko-js" + ) + + @SubCommand( "uniffi", "generate", @@ -74,10 +99,12 @@ def uniffi(command_context, *runargs, **lintargs): ) def generate_command(command_context): library_path = build_gkrust_uniffi_library( - command_context, "gkrust-uniffi-components" + command_context, + SourceLibrary.GKRUST_UNIFFI_COMPONENTS, ) fixtures_library_path = build_gkrust_uniffi_library( - command_context, "gkrust-uniffi-fixtures" + command_context, + SourceLibrary.UNIFFI_BINDINGS_BINDGEN_TESTS, ) binary_path = build_uniffi_bindgen_gecko_js(command_context) cmdline = [ @@ -86,6 +113,7 @@ def generate_command(command_context): library_path, "--fixtures-library-path", fixtures_library_path, + "generate", "--js-dir", JS_DIR, "--fixture-js-dir", @@ -99,7 +127,29 @@ def generate_command(command_context): return 0 -def crate_root(command_context): - return os.path.join( - command_context.topsrcdir, "toolkit", "components", "uniffi-bindgen-gecko-js" +@SubCommand( + "uniffi", + "pipeline", + description="Inspect UniFFI bindings pipeline", +) +@CommandArgument("args", nargs=argparse.REMAINDER) +def pipeline_command(command_context, args): + library_path = build_gkrust_uniffi_library( + command_context, + SourceLibrary.GKRUST_UNIFFI_COMPONENTS, ) + fixtures_library_path = build_gkrust_uniffi_library( + command_context, + SourceLibrary.UNIFFI_BINDINGS_BINDGEN_TESTS, + ) + binary_path = build_uniffi_bindgen_gecko_js(command_context) + cmdline = [ + binary_path, + "--library-path", + library_path, + "--fixtures-library-path", + fixtures_library_path, + "pipeline", + ] + args + subprocess.check_call(cmdline, cwd=command_context.topsrcdir) + return 0 diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/ci_list.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/ci_list.rs deleted file mode 100644 index 07b45421385f..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/ci_list.rs +++ /dev/null @@ -1,227 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Manage the universe of ComponentInterfaces / Configs -//! -//! uniffi-bindgen-gecko-js is unique because it generates bindings over a set of UDL files rather -//! than just one. This is because we want to generate the WebIDL statically rather than generate -//! it. To accomplish that, each WebIDL function inputs an opaque integer id that identifies which -//! version of it should run, for example `CallSync` inputs a function id. Operating on all UDL -//! files at once simplifies the task of ensuring those ids are to be unique and consistent between -//! the JS and c++ code. -//! -//! This module manages the list of ComponentInterface and the object ids. - -use std::collections::{BTreeSet, HashMap, HashSet}; - -use anyhow::{anyhow, bail, Context, Result}; -use camino::{Utf8Path, Utf8PathBuf}; -use uniffi_bindgen::interface::{CallbackInterface, ComponentInterface, FfiFunction, Object}; - -use crate::render::cpp::exposed_functions; -use crate::Component; - -pub struct ComponentUniverse { - pub components: Vec, - pub fixture_components: Vec, -} - -impl ComponentUniverse { - pub fn new(library_path: Utf8PathBuf, fixtures_library_path: Utf8PathBuf) -> Result { - let config_supplier = GeckoJsCrateConfigSupplier::new()?; - let universe = Self { - components: find_components(&library_path, &config_supplier)?, - fixture_components: find_components(&fixtures_library_path, &config_supplier)?, - }; - universe.check_udl_namespaces_unique()?; - universe.check_callback_interfaces()?; - Ok(universe) - } - - fn check_udl_namespaces_unique(&self) -> Result<()> { - let mut set = HashSet::new(); - for ci in self.iter_cis() { - if !set.insert(ci.namespace()) { - bail!("UDL files have duplicate namespace: {}", ci.namespace()); - } - } - Ok(()) - } - - fn check_callback_interfaces(&self) -> Result<()> { - // We don't currently support callback interfaces returning values or throwing errors. - for ci in self.iter_cis() { - for cbi in ci.callback_interface_definitions() { - for method in cbi.methods() { - if method.return_type().is_some() { - bail!("Callback interface method {}.{} throws an error, which is not yet supported", cbi.name(), method.name()) - } - if method.throws_type().is_some() { - bail!("Callback interface method {}.{} returns a value, which is not yet supported", cbi.name(), method.name()) - } - } - } - } - Ok(()) - } - - pub fn iter_components(&self) -> impl Iterator { - self.components.iter().chain(self.fixture_components.iter()) - } - - pub fn iter_cis(&self) -> impl Iterator { - self.iter_components().map(|component| &component.ci) - } -} - -fn find_components( - library_path: &Utf8Path, - config_supplier: &GeckoJsCrateConfigSupplier, -) -> Result> { - let mut components = uniffi_bindgen::find_components(library_path, config_supplier)? - .into_iter() - .map(|component| { - Ok(Component { - config: toml::Value::Table(component.config).try_into()?, - ci: component.ci, - }) - }) - .collect::>>()?; - // Sort components entries to ensure consistent output - components.sort_by(|c1, c2| c1.ci.namespace().cmp(c2.ci.namespace())); - Ok(components) -} - -/// Responsible for finding UDL files and config values for crates -struct GeckoJsCrateConfigSupplier { - // Used to lookup the UDL files - cargo_crate_config_supplier: uniffi_bindgen::cargo_metadata::CrateConfigSupplier, - // Used to get config values - config_table: toml::map::Map, -} - -impl GeckoJsCrateConfigSupplier { - fn new() -> Result { - Ok(Self { - cargo_crate_config_supplier: cargo_metadata::MetadataCommand::new() - .exec() - .context("error running cargo metadata")? - .into(), - config_table: toml::from_str(include_str!("../config.toml"))?, - }) - } -} - -impl uniffi_bindgen::BindgenCrateConfigSupplier for GeckoJsCrateConfigSupplier { - fn get_udl(&self, crate_name: &str, udl_name: &str) -> anyhow::Result { - self.cargo_crate_config_supplier - .get_udl(crate_name, udl_name) - } - - fn get_toml(&self, crate_name: &str) -> anyhow::Result> { - self.config_table - .get(crate_name) - .map(|v| { - v.as_table() - .ok_or_else(|| anyhow!("Config value not table")) - .cloned() - }) - .transpose() - } -} - -pub struct FunctionIds<'a> { - // Map (CI namespace, func name) -> Ids - map: HashMap<(&'a str, &'a str), usize>, -} - -impl<'a> FunctionIds<'a> { - pub fn new(cis: &'a ComponentUniverse) -> Self { - Self { - map: cis - .iter_cis() - .flat_map(|ci| exposed_functions(ci).map(move |(_, f)| (ci.namespace(), f.name()))) - .enumerate() - .map(|(i, (namespace, name))| ((namespace, name), i)) - // Sort using BTreeSet to guarantee the IDs remain stable across runs - .collect::>() - .into_iter() - .collect(), - } - } - - pub fn get(&self, ci: &ComponentInterface, func: &FfiFunction) -> usize { - *self.map.get(&(ci.namespace(), func.name())).unwrap() - } - - pub fn name(&self, ci: &ComponentInterface, func: &FfiFunction) -> String { - format!("{}:{}", ci.namespace(), func.name()) - } -} - -pub struct ObjectIds<'a> { - // Map (CI namespace, object name) -> Ids - map: HashMap<(&'a str, &'a str), usize>, -} - -impl<'a> ObjectIds<'a> { - pub fn new(cis: &'a ComponentUniverse) -> Self { - Self { - map: cis - .iter_cis() - .flat_map(|ci| { - ci.object_definitions() - .iter() - .map(move |o| (ci.namespace(), o.name())) - }) - .enumerate() - .map(|(i, (namespace, name))| ((namespace, name), i)) - // Sort using BTreeSet to guarantee the IDs remain stable across runs - .collect::>() - .into_iter() - .collect(), - } - } - - pub fn get(&self, ci: &ComponentInterface, obj: &Object) -> usize { - *self.map.get(&(ci.namespace(), obj.name())).unwrap() - } - - pub fn name(&self, ci: &ComponentInterface, obj: &Object) -> String { - format!("{}:{}", ci.namespace(), obj.name()) - } -} - -pub struct CallbackIds<'a> { - // Map (CI namespace, callback name) -> Ids - map: HashMap<(&'a str, &'a str), usize>, -} - -impl<'a> CallbackIds<'a> { - pub fn new(cis: &'a ComponentUniverse) -> Self { - Self { - map: cis - .iter_cis() - .flat_map(|ci| { - ci.callback_interface_definitions() - .iter() - .map(move |cb| (ci.namespace(), cb.name())) - }) - .enumerate() - .map(|(i, (namespace, name))| ((namespace, name), i)) - // Sort using BTreeSet to guarantee the IDs remain stable across runs - .collect::>() - .into_iter() - .collect(), - } - } - - pub fn get(&self, ci: &ComponentInterface, cb: &CallbackInterface) -> usize { - *self.map.get(&(ci.namespace(), cb.name())).unwrap() - } - - pub fn name(&self, ci: &ComponentInterface, cb: &CallbackInterface) -> String { - format!("{}:{}", ci.namespace(), cb.name()) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/config_supplier.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/config_supplier.rs new file mode 100644 index 000000000000..4a2f1fbc3235 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/config_supplier.rs @@ -0,0 +1,46 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use anyhow::{anyhow, Context, Result}; +use cargo_metadata::MetadataCommand; +use toml::{map::Map, value::Table, Value}; +use uniffi_bindgen::{cargo_metadata::CrateConfigSupplier, BindgenCrateConfigSupplier}; + +/// Responsible for finding UDL files and config values for crates +pub struct GeckoJsCrateConfigSupplier { + // Used to lookup the UDL files + cargo_crate_config_supplier: CrateConfigSupplier, + // Used to get config values + config_table: Map, +} + +impl GeckoJsCrateConfigSupplier { + pub fn new() -> Result { + Ok(Self { + cargo_crate_config_supplier: MetadataCommand::new() + .exec() + .context("error running cargo metadata")? + .into(), + config_table: toml::from_str(include_str!("../config.toml"))?, + }) + } +} + +impl BindgenCrateConfigSupplier for &GeckoJsCrateConfigSupplier { + fn get_udl(&self, crate_name: &str, udl_name: &str) -> Result { + self.cargo_crate_config_supplier + .get_udl(crate_name, udl_name) + } + + fn get_toml(&self, crate_name: &str) -> Result> { + self.config_table + .get(crate_name) + .map(|v| { + v.as_table() + .ok_or_else(|| anyhow!("Config value not table")) + .cloned() + }) + .transpose() + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/docs.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/docs.rs deleted file mode 100644 index e24469e72ec3..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/docs.rs +++ /dev/null @@ -1,103 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use std::fs; - -use anyhow::Context; -use askama::Template; -use camino::Utf8Path; -use uniffi_bindgen::ComponentInterface; - -use crate::{render::js::*, Component, Result}; - -pub fn render_docs(docs_dir: &Utf8Path, components: &[Component]) -> Result<()> { - for entry in fs::read_dir(docs_dir.as_std_path()).unwrap() { - let entry = entry?; - if entry.file_name() == "index.md" { - continue; - } - fs::remove_file(entry.path())?; - } - - for c in components { - let namespace = c.ci.namespace(); - let path = docs_dir.join(format!("{namespace}.md")); - let module_name = js_module_name(namespace); - // The JS doc modulename chops of the trailing `.mjs`, but not the `.sys` - let jsdoc_module_name = module_name - .strip_suffix(".mjs") - .context("js_module_name does not end with `.mjs`")? - .to_string(); - let template = ApiDocTemplate { - module_name, - jsdoc_module_name, - classes: classes(&c.ci), - functions: functions(&c.ci), - }; - if !template.is_empty() { - fs::write(path, template.render()?)?; - } - } - Ok(()) -} - -fn classes(ci: &ComponentInterface) -> Vec { - std::iter::empty() - .chain( - ci.object_definitions() - .iter() - .filter(|o| o.docstring().is_some()) - .map(|o| o.js_name()), - ) - .chain( - ci.record_definitions() - .filter(|r| r.docstring().is_some()) - .map(|r| r.js_name()), - ) - .chain( - ci.enum_definitions() - .filter(|e| e.docstring().is_some()) - .map(|e| e.js_name()), - ) - .chain( - ci.enum_definitions() - .filter(|e| !e.is_flat()) - .flat_map(|e| { - e.variants().iter().filter_map(move |v| { - if ci.is_name_used_as_error(e.name()) { - Some(v.js_name(e.is_flat())) - } else { - None - //format!("{}.{}", e.js_name(), v.js_name(e.is_flat())) - } - }) - }), - ) - // TODO - //.chain(ci.callback_interface_definitions().into_iter().filter(|c| c.docstring().is_some().map(|c| c.js_name())) - .collect() -} - -fn functions(ci: &ComponentInterface) -> Vec { - ci.function_definitions() - .iter() - .filter(|f| f.docstring().is_some()) - .map(|f| f.js_name()) - .collect() -} - -#[derive(Template)] -#[template(path = "api-doc.md", escape = "none")] -pub struct ApiDocTemplate { - jsdoc_module_name: String, - module_name: String, - classes: Vec, - functions: Vec, -} - -impl ApiDocTemplate { - fn is_empty(&self) -> bool { - self.classes.is_empty() && self.functions.is_empty() - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/lib.rs index cc9bf39c5b35..43d47a8e9798 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/lib.rs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/lib.rs @@ -2,22 +2,24 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use std::fs; +use std::io::Write; + use anyhow::{Context, Result}; use askama::Template; use camino::{Utf8Path, Utf8PathBuf}; use clap::Parser; +use indexmap::IndexSet; use serde::{Deserialize, Serialize}; -use std::collections::HashSet; -use std::fs::File; -use std::io::Write; +use uniffi_bindgen::pipeline::initial; +use uniffi_pipeline::PrintOptions; -mod ci_list; -mod docs; -mod render; +mod config_supplier; +pub mod pipeline; -use ci_list::{CallbackIds, ComponentUniverse, FunctionIds, ObjectIds}; -use render::cpp::CPPScaffoldingTemplate; -use render::js::JSBindingsTemplate; +use config_supplier::GeckoJsCrateConfigSupplier; +use pipeline::{gecko_js_pipeline, GeckoPipeline}; +use uniffi_pipeline::Node; #[derive(Debug, Parser)] #[clap(name = "uniffi-bindgen-gecko-js")] @@ -33,29 +35,59 @@ struct CliArgs { #[clap(long, value_name = "FILE")] fixtures_library_path: Utf8PathBuf, + #[clap(subcommand)] + command: Command, +} + +#[derive(clap::Subcommand, Debug, Clone)] +enum Command { + /// Generate new C++ and JS bindings + Generate(GenerateArgs), + /// Execute the UniFFI pipeline for debugging purposes + Pipeline(PipelineArgs), +} + +#[derive(clap::Args, Debug, Clone)] +struct GenerateArgs { #[clap(long, value_name = "FILE")] js_dir: Utf8PathBuf, - #[clap(long, value_name = "FILE")] fixture_js_dir: Utf8PathBuf, - #[clap(long, value_name = "FILE")] cpp_path: Utf8PathBuf, - #[clap(long, value_name = "FILE")] docs_path: Utf8PathBuf, } -type Component = uniffi_bindgen::Component; +#[derive(clap::Args, Debug, Clone)] +struct PipelineArgs { + /// Only show passes that match + /// + /// Use `last` to only show the last pass, this can be useful when you're writing new pipelines + #[clap(short, long)] + pass: Option, + + /// Only show data for types with name + #[clap(short = 't', long = "type")] + filter_type: Option, + + /// Only show data for items with fields that match + #[clap(short = 'n', long = "name")] + filter_name: Option, + + /// Only show data for items with fields that match + #[clap(long)] + no_diff: bool, +} /// Configuration for a single Component -#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[derive(Clone, Debug, Deserialize, Serialize, Node)] pub struct Config { #[serde(default)] async_wrappers: AsyncWrappersConfig, } -#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[derive(Clone, Debug, Deserialize, Serialize, Node)] struct AsyncWrappersConfig { /// This converts synchronous Rust functions into async JS functions, by wrapping them at the /// C++ layer. @@ -63,92 +95,85 @@ struct AsyncWrappersConfig { enable: bool, /// Functions that should be run on the main thread and not be wrapped #[serde(default)] - main_thread: HashSet, + main_thread: IndexSet, } -fn render(out_path: Utf8PathBuf, template: impl Template) -> Result<()> { - println!("rendering {}", out_path); +fn render(out_path: &Utf8Path, template: impl Template) -> Result<()> { let contents = template.render()?; - let mut f = - File::create(&out_path).context(format!("Failed to create {:?}", out_path.file_name()))?; - writeln!(f, "{}", contents).context(format!("Failed to write to {}", out_path)) -} - -fn render_cpp( - path: Utf8PathBuf, - components: &[Component], - fixture_components: &[Component], - function_ids: &FunctionIds, - object_ids: &ObjectIds, - callback_ids: &CallbackIds, -) -> Result<()> { - render( - path, - CPPScaffoldingTemplate::new( - components, - fixture_components, - function_ids, - object_ids, - callback_ids, - ), - ) -} - -fn render_js( - out_dir: &Utf8Path, - components: &[Component], - function_ids: &FunctionIds, - object_ids: &ObjectIds, - callback_ids: &CallbackIds, - js_dir: &Utf8PathBuf, -) -> Result<()> { - for c in components { - let template = JSBindingsTemplate { - ci: &c.ci, - config: &c.config, - function_ids, - object_ids, - callback_ids, - js_dir, - }; - let path = out_dir.join(template.js_module_name()); - render(path, template)?; - } + let mut f = fs::File::create(out_path) + .context(format!("Failed to create file {:?}", out_path.file_name()))?; + writeln!(f, "{}", contents).context(format!("Failed to write file {}", out_path))?; + println!("Generated: {out_path}"); Ok(()) } pub fn run_main() -> Result<()> { let args = CliArgs::parse(); - let components = ComponentUniverse::new(args.library_path, args.fixtures_library_path)?; - let function_ids = FunctionIds::new(&components); - let object_ids = ObjectIds::new(&components); - let callback_ids = CallbackIds::new(&components); + let (root, pipeline) = root_and_pipeline(args.library_path, args.fixtures_library_path)?; - render_cpp( - args.cpp_path, - &components.components, - &components.fixture_components, - &function_ids, - &object_ids, - &callback_ids, - )?; - render_js( - &args.js_dir, - &components.components, - &function_ids, - &object_ids, - &callback_ids, - &args.js_dir, - )?; - render_js( - &args.fixture_js_dir, - &components.fixture_components, - &function_ids, - &object_ids, - &callback_ids, - &args.js_dir, - )?; - docs::render_docs(&args.docs_path, &components.components)?; + match args.command { + Command::Generate(generate_args) => run_generate(root, pipeline, generate_args), + Command::Pipeline(pipeline_args) => run_pipeline(root, pipeline, pipeline_args), + } +} +fn run_generate( + root: initial::Root, + mut pipeline: GeckoPipeline, + args: GenerateArgs, +) -> Result<()> { + let root = pipeline.execute(root)?; + render(&args.cpp_path, root.cpp_scaffolding)?; + for module in root.modules.values() { + let dir = if module.fixture { + &args.fixture_js_dir + } else { + &args.js_dir + }; + render(&dir.join(&module.js_filename), module)?; + } + for entry in fs::read_dir(&args.docs_path)? { + let path = entry?.path(); + if path.file_name().unwrap() != "index.md" { + fs::remove_file(path)?; + } + } + for module_docs in root.module_docs.iter() { + render(&args.docs_path.join(&module_docs.filename), module_docs)?; + } Ok(()) } + +fn run_pipeline( + root: initial::Root, + mut pipeline: GeckoPipeline, + args: PipelineArgs, +) -> Result<()> { + let opts = PrintOptions { + pass: args.pass, + no_diff: args.no_diff, + filter_type: args.filter_type, + filter_name: args.filter_name, + }; + pipeline.print_passes(root, opts) +} + +fn root_and_pipeline( + library_path: Utf8PathBuf, + fixtures_library_path: Utf8PathBuf, +) -> Result<(initial::Root, GeckoPipeline)> { + let config_supplier = GeckoJsCrateConfigSupplier::new()?; + let root = initial::Root::from_library(&config_supplier, &library_path, None)?; + let fixtures_root = + initial::Root::from_library(&config_supplier, &fixtures_library_path, None)?; + let root = initial::Root { + modules: root + .modules + .into_iter() + .chain(fixtures_root.modules) + .collect(), + cdylib: None, + }; + let pipeline = gecko_js_pipeline(toml::from_str(include_str!("../config.toml"))?); + Ok((root, pipeline)) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/callables.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/callables.rs new file mode 100644 index 000000000000..09f3769e74a4 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/callables.rs @@ -0,0 +1,35 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; + +pub fn pass(module: &mut Module) -> Result<()> { + let async_wrappers = module.config.async_wrappers.clone(); + module.visit_mut(|callable: &mut Callable| { + if callable.async_data.is_some() { + callable.is_js_async = true; + callable.uniffi_scaffolding_method = "UniFFIScaffolding.callAsync".to_string(); + return; + } + + let name = &callable.name; + let spec = match &callable.kind { + CallableKind::Function => name.clone(), + CallableKind::Method { interface_name, .. } + | CallableKind::VTableMethod { + trait_name: interface_name, + } + | CallableKind::Constructor { interface_name, .. } => { + format!("{interface_name}.{name}") + } + }; + if async_wrappers.enable && !async_wrappers.main_thread.contains(&spec) { + callable.is_js_async = true; + callable.uniffi_scaffolding_method = "UniFFIScaffolding.callAsyncWrapper".to_string(); + } else { + callable.uniffi_scaffolding_method = "UniFFIScaffolding.callSync".to_string(); + } + }); + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/callback_interfaces.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/callback_interfaces.rs new file mode 100644 index 000000000000..b090c813aedf --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/callback_interfaces.rs @@ -0,0 +1,17 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use heck::ToUpperCamelCase; + +use super::*; + +pub fn pass(module: &mut Module) -> Result<()> { + let mut saw_callback_interface = false; + module.visit_mut(|cbi: &mut CallbackInterface| { + cbi.js_handler_var = format!("uniffiCallbackHandler{}", cbi.name.to_upper_camel_case()); + saw_callback_interface = true; + }); + module.has_callback_interface = saw_callback_interface; + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_callback_interfaces.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_callback_interfaces.rs new file mode 100644 index 000000000000..77a5133636d4 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_callback_interfaces.rs @@ -0,0 +1,117 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use std::collections::HashMap; + +use anyhow::anyhow; +use heck::{ToSnakeCase, ToUpperCamelCase}; + +use super::*; + +pub fn pass(root: &mut Root) -> Result<()> { + root.cpp_scaffolding.callback_interfaces = + CombinedItems::try_new(root, |module, ids, items| { + let module_name = module.name.clone(); + let ffi_func_map: HashMap = module + .ffi_definitions + .iter() + .filter_map(|def| match def { + FfiDefinition::FunctionType(func_type) => Some(func_type), + _ => None, + }) + .map(|func_type| (func_type.name.0.clone(), func_type.clone())) + .collect(); + + module.try_visit_mut(|cbi: &mut CallbackInterface| { + let interface_name = cbi.name.clone(); + cbi.id = ids.new_id(); + items.push(CppCallbackInterface { + id: cbi.id, + name: cbi.name.clone(), + handler_var: format!( + "gUniffiCallbackHandler{}", + cbi.name.to_upper_camel_case() + ), + vtable_var: format!("kUniffiVtable{}", cbi.name.to_upper_camel_case()), + vtable_struct_type: cbi.vtable.struct_type.clone(), + init_fn: cbi.vtable.init_fn.clone(), + free_fn: format!( + "callback_free_{}_{}", + module_name.to_snake_case(), + interface_name.to_snake_case() + ), + methods: cbi + .vtable + .methods + .iter() + .enumerate() + .map(|(i, vtable_meth)| { + let ffi_func = ffi_func_map + .get(&format!("CallbackInterface{interface_name}Method{i}")) + .cloned() + .ok_or_else(|| { + anyhow!( + "Callback interface method not found: {}", + vtable_meth.callable.name + ) + })?; + map_method(vtable_meth, ffi_func, &module_name, &interface_name) + }) + .collect::>>()?, + }); + Ok(()) + })?; + Ok(()) + })?; + + Ok(()) +} + +fn map_method( + meth: &VTableMethod, + ffi_func: FfiFunctionType, + module_name: &str, + interface_name: &str, +) -> Result { + let (return_ty, out_pointer_ty) = match &meth.callable.return_type.ty { + Some(ty) => ( + Some(FfiValueReturnType { + ty: ty.ffi_type.clone(), + ..FfiValueReturnType::default() + }), + FfiType::MutReference(Box::new(ty.ffi_type.ty.clone())), + ), + None => (None, FfiType::VoidPointer), + }; + Ok(CppCallbackInterfaceMethod { + arguments: meth + .callable + .arguments + .iter() + .map(|a| FfiValueArgument { + name: a.name.clone(), + ty: a.ty.ffi_type.clone(), + ..FfiValueArgument::default() + }) + .collect(), + fn_name: format!( + "callback_interface_{}_{}_{}", + module_name.to_snake_case(), + interface_name.to_snake_case(), + meth.callable.name.to_snake_case(), + ), + handler_class_name: format!( + "CallbackInterfaceMethod{}{}{}", + module_name.to_upper_camel_case(), + interface_name.to_upper_camel_case(), + meth.callable.name.to_upper_camel_case(), + ), + return_ty, + out_pointer_ty: FfiTypeNode { + ty: out_pointer_ty, + ..FfiTypeNode::default() + }, + ffi_func, + }) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_ffi_definitions.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_ffi_definitions.rs new file mode 100644 index 000000000000..c593c5f16bd7 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_ffi_definitions.rs @@ -0,0 +1,26 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; + +use std::collections::HashSet; + +pub fn pass(root: &mut Root) -> Result<()> { + // Make sure to only include each FFI definitions once since we're combining FFI definitions + // from different modules. + let mut seen = HashSet::new(); + root.cpp_scaffolding.ffi_definitions = CombinedItems::new(root, |module, _, items| { + module.visit(|def: &FfiDefinition| { + let name = match def { + FfiDefinition::RustFunction(FfiFunction { name, .. }) => name.0.clone(), + FfiDefinition::FunctionType(FfiFunctionType { name, .. }) => name.0.clone(), + FfiDefinition::Struct(FfiStruct { name, .. }) => name.0.clone(), + }; + if seen.insert(name) { + items.push(def.clone()) + } + }) + }); + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_ffi_types.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_ffi_types.rs new file mode 100644 index 000000000000..dd21d5866f58 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_ffi_types.rs @@ -0,0 +1,84 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; +use anyhow::bail; +use heck::ToUpperCamelCase; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|node: &mut FfiTypeNode| { + node.type_name = ffi_type_name(&node.ty); + }); + root.visit_mut(|return_ty: &mut FfiReturnType| { + return_ty.type_name = match &return_ty.ty { + Some(type_node) => type_node.type_name.clone(), + None => "void".to_string(), + }; + }); + root.try_visit_mut(|arg: &mut FfiValueArgument| { + arg.ffi_value_class = ffi_value_class(&arg.ty)?; + Ok(()) + })?; + root.try_visit_mut(|return_ty: &mut FfiValueReturnType| { + return_ty.ffi_value_class = ffi_value_class(&return_ty.ty)?; + Ok(()) + })?; + + Ok(()) +} + +fn ffi_type_name(ty: &FfiType) -> String { + match ty { + FfiType::UInt8 => "uint8_t".to_owned(), + FfiType::Int8 => "int8_t".to_owned(), + FfiType::UInt16 => "uint16_t".to_owned(), + FfiType::Int16 => "int16_t".to_owned(), + FfiType::UInt32 => "uint32_t".to_owned(), + FfiType::Int32 => "int32_t".to_owned(), + FfiType::UInt64 => "uint64_t".to_owned(), + FfiType::Int64 => "int64_t".to_owned(), + FfiType::Float32 => "float".to_owned(), + FfiType::Float64 => "double".to_owned(), + FfiType::RustBuffer(_) => "RustBuffer".to_owned(), + FfiType::RustArcPtr { .. } => "void*".to_owned(), + FfiType::ForeignBytes => "ForeignBytes".to_owned(), + FfiType::Handle(_) => "uint64_t".to_owned(), + FfiType::RustCallStatus => "RustCallStatus".to_owned(), + FfiType::Function(name) => name.0.to_owned(), + FfiType::Struct(name) => name.0.to_owned(), + FfiType::VoidPointer => "void*".to_owned(), + FfiType::MutReference(inner) | FfiType::Reference(inner) => { + format!("{}*", ffi_type_name(inner.as_ref())) + } + } +} + +pub fn ffi_value_class(node: &FfiTypeNode) -> Result { + Ok(match &node.ty { + FfiType::RustArcPtr { + module_name, + object_name, + } => { + format!( + "FfiValueObjectHandle{}{}", + module_name.to_upper_camel_case(), + object_name.to_upper_camel_case(), + ) + } + FfiType::UInt8 + | FfiType::Int8 + | FfiType::UInt16 + | FfiType::Int16 + | FfiType::UInt32 + | FfiType::Int32 + | FfiType::UInt64 + | FfiType::Int64 => format!("FfiValueInt<{}>", node.type_name), + FfiType::Float32 | FfiType::Float64 => { + format!("FfiValueFloat<{}>", node.type_name) + } + FfiType::RustBuffer(_) => "FfiValueRustBuffer".to_owned(), + FfiType::Handle(HandleKind::CallbackInterface { .. }) => "FfiValueInt".to_owned(), + ty => bail!("No FfiValue class for: {ty:?}"), + }) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_names.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_names.rs new file mode 100644 index 000000000000..e9a5222d2d19 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_names.rs @@ -0,0 +1,14 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; +use heck::ToUpperCamelCase; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|arg: &mut FfiValueArgument| { + arg.field_name = format!("m{}", arg.name.to_upper_camel_case()); + arg.name = format!("a{}", arg.name.to_upper_camel_case()); + }); + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_scaffolding_calls.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_scaffolding_calls.rs new file mode 100644 index 000000000000..1697dcd5c90b --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/cpp_scaffolding_calls.rs @@ -0,0 +1,75 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use anyhow::anyhow; +use std::collections::HashMap; + +use super::*; +use heck::ToUpperCamelCase; + +pub fn pass(root: &mut Root) -> Result<()> { + // Generate `ScaffoldingCall` items + root.cpp_scaffolding.scaffolding_calls = CombinedItems::try_new(root, |module, ids, items| { + let module_name = module.name.clone(); + let mut ffi_func_map = HashMap::new(); + module.visit(|ffi_func: &FfiFunction| { + if ffi_func.kind == FfiFunctionKind::Scaffolding { + ffi_func_map.insert(ffi_func.name.0.clone(), ffi_func.clone()); + } + }); + module.try_visit_mut(|callable: &mut Callable| { + // Callback interface methods don't have scaffolding functions associated with them + if matches!(callable.kind, CallableKind::VTableMethod { .. }) { + return Ok(()); + } + let ffi_func = ffi_func_map + .remove(&callable.ffi_func.0) + .ok_or_else(|| anyhow!("FfiFunction lookup failed: {:?}", callable.ffi_func.0))?; + callable.id = ids.new_id(); + let mut arguments = match &callable.kind { + CallableKind::Method { interface_name, .. } => vec![FfiValueArgument { + name: "uniffi_ptr".to_string(), + ty: FfiTypeNode { + ty: FfiType::RustArcPtr { + module_name: module_name.clone(), + object_name: interface_name.clone(), + }, + ..FfiTypeNode::default() + }, + ..FfiValueArgument::default() + }], + _ => vec![], + }; + arguments.extend(callable.arguments.iter().map(|a| FfiValueArgument { + name: a.name.clone(), + ty: a.ty.ffi_type.clone(), + ..FfiValueArgument::default() + })); + + items.push(ScaffoldingCall { + id: callable.id, + arguments, + handler_class_name: format!( + "ScaffoldingCallHandler{}", + ffi_func.name.0.to_upper_camel_case(), + ), + return_ty: callable + .return_type + .ty + .as_ref() + .map(|ty| FfiValueReturnType { + ty: ty.ffi_type.clone(), + ..FfiValueReturnType::default() + }), + ffi_func, + }); + Ok(()) + }) + })?; + root.cpp_scaffolding + .scaffolding_calls + .sort_by_key(|call| call.id); + + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/docs.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/docs.rs new file mode 100644 index 000000000000..7588bce778ea --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/docs.rs @@ -0,0 +1,67 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; + +pub fn pass(root: &mut Root) -> Result<()> { + let mut module_docs = vec![]; + root.visit_mut(|module: &mut Module| { + if module.fixture { + return; + } + let mut docs = ApiModuleDocs { + filename: format!("{}.md", module.name), + jsdoc_module_name: format!("{}.sys", module.js_name), + module_name: format!("{}.sys.mjs", module.js_name), + classes: vec![], + functions: vec![], + }; + module.visit(|type_def: &TypeDefinition| { + match type_def { + TypeDefinition::Interface(Interface { + name, docstring, .. + }) + | TypeDefinition::Record(Record { + name, docstring, .. + }) + | TypeDefinition::Custom(CustomType { + name, docstring, .. + }) => { + if docstring.is_some() { + docs.classes.push(name.clone()); + } + } + TypeDefinition::Enum(Enum { + name, + docstring, + variants, + self_type, + .. + }) => { + if docstring.is_some() { + docs.classes.push(name.clone()); + } + if self_type.is_used_as_error { + for v in variants { + docs.classes.push(v.name.clone()); + } + } + } + // TODO: callback interfaces. + // + // To implement this, we probably should define a base class with for the interface. + _ => (), + } + }); + module.visit(|func: &Function| { + docs.functions.push(func.name.clone()); + }); + docs.classes.sort(); + docs.functions.sort(); + module_docs.push(docs); + }); + root.module_docs = module_docs; + + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/interfaces.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/interfaces.rs new file mode 100644 index 000000000000..29f80f519a7b --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/interfaces.rs @@ -0,0 +1,56 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +//! Generate the `ScaffoldingCall` lists + +use super::*; +use heck::ToUpperCamelCase; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|int: &mut Interface| { + let int_ffi_converter = format!("FfiConverter{}", int.self_type.canonical_name); + int.visit_mut(|callable_kind: &mut CallableKind| { + if let CallableKind::Method { ffi_converter, .. } = callable_kind { + *ffi_converter = int_ffi_converter.clone(); + }; + }); + // Rename the primary constructor to `init` + int.visit_mut(|cons: &mut Constructor| { + if cons.name == "new" { + cons.name = "init".to_string(); + cons.visit_mut(|callable: &mut Callable| { + callable.name = "init".to_string(); + }) + } + }); + }); + + // Generate [CppScaffolding::pointer_types] + root.cpp_scaffolding.pointer_types = CombinedItems::new(root, |module, ids, items| { + let module_name = module.name.clone(); + module.visit_mut(|int: &mut Interface| { + int.object_id = ids.new_id(); + items.push(PointerType { + id: int.object_id, + name: format!( + "k{}{}PointerType", + module_name.to_upper_camel_case(), + int.name.to_upper_camel_case() + ), + ffi_value_class: format!( + "FfiValueObjectHandle{}{}", + module_name.to_upper_camel_case(), + int.name.to_upper_camel_case(), + ), + label: format!("{}::{}", module_name, int.name), + ffi_func_clone: int.ffi_func_clone.clone(), + ffi_func_free: int.ffi_func_free.clone(), + }) + }); + }); + root.cpp_scaffolding + .pointer_types + .sort_by_key(|call| call.id); + Ok(()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_docstrings.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_docstrings.rs new file mode 100644 index 000000000000..4bf975424163 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_docstrings.rs @@ -0,0 +1,67 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|module: &mut Module| { + module.js_docstring = format_docstring(module.docstring.as_ref().unwrap_or(&module.name)); + }); + root.visit_mut(|func: &mut Function| { + func.js_docstring = format_docstring(func.docstring.as_ref().unwrap_or(&func.name)); + }); + root.visit_mut(|meth: &mut Method| { + meth.js_docstring = format_docstring(meth.docstring.as_ref().unwrap_or(&meth.name)); + }); + root.visit_mut(|cons: &mut Method| { + cons.js_docstring = format_docstring(cons.docstring.as_ref().unwrap_or(&cons.name)); + }); + root.visit_mut(|rec: &mut Record| { + rec.js_docstring = format_docstring(rec.docstring.as_ref().unwrap_or(&rec.name)); + }); + root.visit_mut(|en: &mut Enum| { + en.js_docstring = format_docstring(en.docstring.as_ref().unwrap_or(&en.name)); + }); + root.visit_mut(|variant: &mut Variant| { + variant.js_docstring = + format_docstring(variant.docstring.as_ref().unwrap_or(&variant.name)); + }); + root.visit_mut(|field: &mut Field| { + field.js_docstring = format_docstring(field.docstring.as_ref().unwrap_or(&field.name)); + }); + root.visit_mut(|int: &mut Interface| { + int.js_docstring = format_docstring(int.docstring.as_ref().unwrap_or(&int.name)); + }); + root.visit_mut(|cbi: &mut CallbackInterface| { + cbi.js_docstring = format_docstring(cbi.docstring.as_ref().unwrap_or(&cbi.name)); + }); + root.visit_mut(|custom: &mut CustomType| { + custom.js_docstring = format_docstring(custom.docstring.as_ref().unwrap_or(&custom.name)); + }); + root.visit_mut(|field: &mut Field| { + field.js_docstring = format_docstring(field.docstring.as_ref().unwrap_or(&field.name)); + }); + Ok(()) +} + +/// Format a docstring for the JS code +fn format_docstring(docstring: &str) -> String { + // Remove any existing indentation + let docstring = textwrap::dedent(docstring); + // "Escape" `*/` chars to avoid closing the comment + let docstring = docstring.replace("*/", "* /"); + // Format the docstring making sure to: + // - Start with `/**` and end with `*/` + // - Line up all the `*` chars correctly + // - Add trailing leading spaces, to make this work with the `{{ -}}` tag + let mut output = String::default(); + output.push_str("/**\n"); + for line in docstring.split('\n') { + output.push_str(" * "); + output.push_str(line); + output.push('\n'); + } + output.push_str(" */"); + output +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/build.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_filename.rs similarity index 52% rename from toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/build.rs rename to toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_filename.rs index 303ac22d8d98..4f3ef74ff532 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/arithmetic/build.rs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_filename.rs @@ -2,6 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -fn main() { - uniffi::generate_scaffolding("src/arithmetic.udl").unwrap(); +use super::*; +use heck::ToUpperCamelCase; + +pub fn pass(module: &mut Module) -> Result<()> { + module.js_filename = format!("Rust{}.sys.mjs", module.name.to_upper_camel_case()); + Ok(()) } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_names.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_names.rs new file mode 100644 index 000000000000..8d20850a8b34 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/js_names.rs @@ -0,0 +1,59 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; +use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase}; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|func: &mut Function| func.name = func.name.to_lower_camel_case()); + root.visit_mut(|meth: &mut Method| meth.name = meth.name.to_lower_camel_case()); + root.visit_mut(|cons: &mut Constructor| cons.name = cons.name.to_lower_camel_case()); + root.visit_mut(|callable: &mut Callable| callable.name = callable.name.to_lower_camel_case()); + + root.visit_mut(|rec: &mut Record| rec.name = rec.name.to_upper_camel_case()); + root.visit_mut(|en: &mut Enum| { + en.name = en.name.to_upper_camel_case(); + if en.is_flat && !en.self_type.is_used_as_error { + en.visit_mut(|v: &mut Variant| v.name = v.name.to_shouty_snake_case()); + } else { + en.visit_mut(|v: &mut Variant| v.name = v.name.to_upper_camel_case()); + } + }); + root.visit_mut(|int: &mut Interface| int.name = int.name.to_upper_camel_case()); + root.visit_mut(|cbi: &mut CustomType| cbi.name = cbi.name.to_upper_camel_case()); + root.visit_mut(|custom: &mut CustomType| custom.name = custom.name.to_upper_camel_case()); + root.visit_mut(|arg: &mut Argument| arg.name = arg.name.to_lower_camel_case()); + root.visit_mut(|field: &mut Field| field.name = field.name.to_lower_camel_case()); + root.visit_mut(|module: &mut Module| module.js_name = format_module_name(&module.name)); + root.visit_mut(|ty: &mut Type| match ty { + Type::Record { + module_name, name, .. + } + | Type::Enum { + module_name, name, .. + } + | Type::Interface { + module_name, name, .. + } + | Type::CallbackInterface { + module_name, name, .. + } + | Type::Custom { + module_name, name, .. + } => { + *module_name = format_module_name(module_name); + *name = name.to_upper_camel_case(); + } + _ => (), + }); + root.visit_mut(|ext: &mut ExternalType| { + ext.module_name = format_module_name(&ext.module_name); + ext.name = ext.name.to_upper_camel_case(); + }); + Ok(()) +} + +fn format_module_name(source_name: &str) -> String { + format!("Rust{}", source_name.to_upper_camel_case()) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/literals.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/literals.rs new file mode 100644 index 000000000000..bf1d01d14f51 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/literals.rs @@ -0,0 +1,49 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; +use heck::{ToShoutySnakeCase, ToUpperCamelCase}; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|node: &mut LiteralNode| node.js_lit = js_lit(&node.lit)); + Ok(()) +} + +fn js_lit(lit: &Literal) -> String { + match lit { + Literal::Boolean(inner) => inner.to_string(), + Literal::String(inner) => format!("\"{}\"", inner), + Literal::UInt(num, radix, _) => number_lit(radix, num).to_string(), + Literal::Int(num, radix, _) => number_lit(radix, num).to_string(), + Literal::Float(num, _) => num.clone(), + Literal::Enum(name, typ) => enum_lit(&typ.ty, name), + Literal::EmptyMap => "{}".to_string(), + Literal::EmptySequence => "[]".to_string(), + Literal::Some { inner } => js_lit(inner), + Literal::None => "null".to_string(), + } +} + +fn number_lit( + radix: &Radix, + num: impl std::fmt::Display + std::fmt::LowerHex + std::fmt::Octal, +) -> String { + match radix { + Radix::Decimal => format!("{}", num), + Radix::Hexadecimal => format!("{:#x}", num), + Radix::Octal => format!("{:#o}", num), + } +} + +fn enum_lit(typ: &Type, variant_name: &str) -> String { + if let Type::Enum { name, .. } = typ { + format!( + "{}.{}", + name.to_upper_camel_case(), + variant_name.to_shouty_snake_case() + ) + } else { + panic!("Rendering an enum literal on a type that is not an enum") + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/mod.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/mod.rs new file mode 100644 index 000000000000..216818371a87 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/mod.rs @@ -0,0 +1,50 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#[macro_use] +mod nodes; +mod callables; +mod callback_interfaces; +mod cpp_callback_interfaces; +mod cpp_ffi_definitions; +mod cpp_ffi_types; +mod cpp_names; +mod cpp_scaffolding_calls; +mod docs; +mod interfaces; +mod js_docstrings; +mod js_filename; +mod js_names; +mod literals; +mod modules; +mod types; + +use crate::Config; +use anyhow::Result; +pub use nodes::*; +use std::collections::HashMap; +use uniffi_bindgen::pipeline::{general, initial}; +use uniffi_pipeline::{Node, Pipeline}; + +pub type GeckoPipeline = Pipeline; + +pub fn gecko_js_pipeline(pipeline_map: HashMap) -> GeckoPipeline { + general::pipeline() + .convert_ir_pass::() + .pass(modules::pass(pipeline_map)) + .pass(callables::pass) + .pass(interfaces::pass) + .pass(callback_interfaces::pass) + .pass(js_filename::pass) + .pass(js_names::pass) + .pass(js_docstrings::pass) + .pass(cpp_ffi_definitions::pass) + .pass(cpp_scaffolding_calls::pass) + .pass(cpp_callback_interfaces::pass) + .pass(types::pass) + .pass(cpp_ffi_types::pass) + .pass(cpp_names::pass) + .pass(literals::pass) + .pass(docs::pass) +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/modules.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/modules.rs new file mode 100644 index 000000000000..a1c84a141d07 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/modules.rs @@ -0,0 +1,29 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use super::*; +use crate::Config; +use std::collections::HashMap; + +pub fn pass(mut config_map: HashMap) -> impl FnMut(&mut Module) -> Result<()> { + move |module: &mut Module| { + module.config = config_map.remove(&module.crate_name).unwrap_or_default(); + // Set the `fixture` flag for modules that belong to the text fixtures + // To do this in a general way, we would need to remember which `Metadata::Namespace` items + // came from the fixtures library and create a closure that captured that set. + // + // However, since we only have two fixture modules, we can do this very easily. + if module.name.starts_with("uniffi_bindings_tests") { + module.fixture = true; + } + + // Workaround for the fact that the UniFFI 0.29.2 doesn't set this correctly. + module.string_type_node = TypeNode { + ty: Type::String, + canonical_name: "String".to_string(), + ..TypeNode::default() + }; + Ok(()) + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/nodes.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/nodes.rs new file mode 100644 index 000000000000..2f66bde126c1 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/nodes.rs @@ -0,0 +1,805 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use indexmap::IndexMap; + +use anyhow::Result; +use askama::Template; +use uniffi_pipeline::{AsRef, Node}; + +use crate::Config; + +/// Initial IR, this stores the metadata and other data +#[derive(Debug, Clone, Node)] +pub struct Root { + /// In library mode, we get the name of the library file for free. + pub cdylib: Option, + pub modules: IndexMap, + pub cpp_scaffolding: CppScaffolding, + pub module_docs: Vec, +} + +#[derive(Debug, Clone, Node, Template)] +#[template(path = "cpp/UniFFIScaffolding.cpp", escape = "none")] +pub struct CppScaffolding { + pub ffi_definitions: CombinedItems, + pub scaffolding_calls: CombinedItems, + pub pointer_types: CombinedItems, + pub callback_interfaces: CombinedItems, +} + +// A Scaffolding call implemented in the C++ code +#[derive(Debug, Clone, Node)] +pub struct ScaffoldingCall { + pub id: u64, + pub ffi_func: FfiFunction, + pub handler_class_name: String, + pub arguments: Vec, + pub return_ty: Option, +} + +/// FFI argument that's handled by one of the `FfiValue*` classes in the C++ code +#[derive(Debug, Clone, Node)] +pub struct FfiValueArgument { + pub name: String, + /// C++ class field name + pub field_name: String, + pub ffi_value_class: String, + pub ty: FfiTypeNode, +} + +/// FFI return value that's handled by one of the `FfiValue*` classes in the C++ code +#[derive(Debug, Clone, Node)] +pub struct FfiValueReturnType { + pub ffi_value_class: String, + pub ty: FfiTypeNode, +} + +// A `PointerType` const to define in the C++ code +#[derive(Debug, Clone, Node)] +pub struct PointerType { + pub id: u64, + pub name: String, + pub label: String, + pub ffi_value_class: String, + pub ffi_func_clone: RustFfiFunctionName, + pub ffi_func_free: RustFfiFunctionName, +} + +// Used to generate the C++ callback interface code +#[derive(Debug, Clone, Node)] +pub struct CppCallbackInterface { + pub id: u64, + pub name: String, + /// Name of the C++ variable that stores the UniFFICallbackHandler instance + pub handler_var: String, + // Name of the C++ static variable for the VTable + pub vtable_var: String, + /// Rust scaffolding function to initialize the VTable + pub init_fn: RustFfiFunctionName, + /// Name of the function generated by uniffi-bindgen-gecko-js to free the vtable. + pub free_fn: String, + pub vtable_struct_type: FfiTypeNode, + pub methods: Vec, +} + +// Used to generate the C++ code to handle a callback method +#[derive(Debug, Clone, Node)] +pub struct CppCallbackInterfaceMethod { + /// Name of the handler function + pub fn_name: String, + /// Name of the UniffiCallbackMethodHandlerBase subclass + pub handler_class_name: String, + pub ffi_func: FfiFunctionType, + pub arguments: Vec, + pub return_ty: Option, + pub out_pointer_ty: FfiTypeNode, +} + +#[derive(Debug, Clone, Node, Template)] +#[template(path = "js/Module.sys.mjs", escape = "none")] +pub struct Module { + pub name: String, + pub config: Config, + pub js_name: String, + pub js_filename: String, + pub fixture: bool, + pub crate_name: String, + pub docstring: Option, + pub js_docstring: String, + pub functions: Vec, + pub type_definitions: Vec, + pub ffi_definitions: Vec, + pub checksums: Vec, + pub ffi_rustbuffer_alloc: RustFfiFunctionName, + pub ffi_rustbuffer_from_bytes: RustFfiFunctionName, + pub ffi_rustbuffer_free: RustFfiFunctionName, + pub ffi_rustbuffer_reserve: RustFfiFunctionName, + pub ffi_uniffi_contract_version: RustFfiFunctionName, + pub string_type_node: TypeNode, + pub has_callback_interface: bool, +} + +#[derive(Debug, Clone, Node)] +pub enum TypeDefinition { + Interface(Interface), + CallbackInterface(CallbackInterface), + Record(Record), + Enum(Enum), + Custom(CustomType), + Simple(TypeNode), + Optional(OptionalType), + Sequence(SequenceType), + Map(MapType), + External(ExternalType), +} + +#[derive(Debug, Clone, Node)] +pub struct NamespaceMetadata { + pub crate_name: String, + pub name: String, +} + +#[derive(Debug, Clone, Node)] +pub struct Function { + pub name: String, + pub callable: Callable, + pub docstring: Option, + pub js_docstring: String, +} + +#[derive(Debug, Clone, Node)] +pub struct Constructor { + pub name: String, + pub self_name: String, + pub callable: Callable, + pub docstring: Option, + pub js_docstring: String, +} + +#[derive(Debug, Clone, Node)] +pub struct Method { + pub name: String, + pub self_name: String, + pub callable: Callable, + pub docstring: Option, + pub js_docstring: String, +} + +/// Common data from Function/Method/Constructor +#[derive(Debug, Clone, Node)] +pub struct Callable { + pub name: String, + pub async_data: Option, + pub is_js_async: bool, + // UniFFIScaffolding method used to invoke this callable + pub uniffi_scaffolding_method: String, + pub kind: CallableKind, + pub arguments: Vec, + pub return_type: ReturnType, + pub throws_type: ThrowsType, + pub checksum: Option, + pub ffi_func: RustFfiFunctionName, + pub id: u64, +} + +#[derive(Debug, Clone, Node)] +pub enum CallableKind { + Function, + Method { + interface_name: String, + ffi_converter: String, + }, + Constructor { + interface_name: String, + primary: bool, + }, + VTableMethod { + trait_name: String, + }, +} + +#[derive(Debug, Clone, Node)] +pub struct ReturnType { + pub ty: Option, +} + +#[derive(Debug, Clone, Node)] +pub struct ThrowsType { + pub ty: Option, +} + +#[derive(Debug, Clone, Node)] +pub struct AsyncData { + pub ffi_rust_future_poll: RustFfiFunctionName, + pub ffi_rust_future_cancel: RustFfiFunctionName, + pub ffi_rust_future_free: RustFfiFunctionName, + pub ffi_rust_future_complete: RustFfiFunctionName, + pub ffi_foreign_future_complete: FfiFunctionTypeName, + pub ffi_foreign_future_result: FfiStructName, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct Argument { + pub name: String, + #[as_ref] + pub ty: TypeNode, + pub by_ref: bool, + pub optional: bool, + pub default: Option, +} + +#[derive(Debug, Clone, Node)] +pub struct LiteralNode { + pub js_lit: String, + pub lit: Literal, +} + +#[derive(Debug, Clone, Node)] +pub enum Literal { + Boolean(bool), + String(String), + // Integers are represented as the widest representation we can. + // Number formatting vary with language and radix, so we avoid a lot of parsing and + // formatting duplication by using only signed and unsigned variants. + UInt(u64, Radix, TypeNode), + Int(i64, Radix, TypeNode), + // Pass the string representation through as typed in the UDL. + // This avoids a lot of uncertainty around precision and accuracy, + // though bindings for languages less sophisticated number parsing than WebIDL + // will have to do extra work. + Float(String, TypeNode), + Enum(String, TypeNode), + EmptySequence, + EmptyMap, + None, + Some { inner: Box }, +} + +// Represent the radix of integer literal values. +// We preserve the radix into the generated bindings for readability reasons. +#[derive(Debug, Clone, Node)] +pub enum Radix { + Decimal = 10, + Octal = 8, + Hexadecimal = 16, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct Record { + pub name: String, + pub remote: bool, // only used when generating scaffolding from UDL + pub fields: Vec, + pub docstring: Option, + pub js_docstring: String, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct Field { + pub name: String, + #[as_ref] + pub ty: TypeNode, + pub default: Option, + pub docstring: Option, + pub js_docstring: String, +} + +#[derive(Debug, Clone, Node)] +pub enum EnumShape { + Enum, + Error { flat: bool }, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct Enum { + pub name: String, + pub is_flat: bool, + pub shape: EnumShape, + pub remote: bool, + pub variants: Vec, + pub discr_type: Option, + pub non_exhaustive: bool, + pub js_docstring: String, + pub docstring: Option, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node)] +pub struct Variant { + pub name: String, + pub discr: Option, + pub fields: Vec, + pub docstring: Option, + pub js_docstring: String, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct Interface { + pub name: String, + pub object_id: u64, + pub constructors: Vec, + pub methods: Vec, + pub uniffi_traits: Vec, + pub trait_impls: Vec, + pub remote: bool, // only used when generating scaffolding from UDL + pub imp: ObjectImpl, + pub docstring: Option, + pub js_docstring: String, + #[as_ref] + pub self_type: TypeNode, + pub vtable: Option, + pub ffi_func_clone: RustFfiFunctionName, + pub ffi_func_free: RustFfiFunctionName, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct CallbackInterface { + pub name: String, + pub id: u64, + /// Name of the JS variable that stores the UniFFICallbackHandler instance + pub js_handler_var: String, + pub vtable: VTable, + pub docstring: Option, + pub js_docstring: String, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node)] +pub struct VTable { + /// Vtable struct. This has field for each callback interface method that stores a function + /// pointer for that method. + pub struct_type: FfiTypeNode, + /// Rust FFI function to initialize the vtable. + /// + /// Foreign code should call this function, passing it a pointer to the VTable struct. + pub init_fn: RustFfiFunctionName, + pub methods: Vec, +} + +/// Single method in a vtable +#[derive(Debug, Clone, Node)] +pub struct VTableMethod { + pub callable: Callable, + pub ffi_type: FfiTypeNode, +} + +#[derive(Debug, Clone, Node)] +pub enum UniffiTrait { + Debug { fmt: Method }, + Display { fmt: Method }, + Eq { eq: Method, ne: Method }, + Hash { hash: Method }, +} + +#[derive(Debug, Clone, Node)] +pub struct ObjectTraitImpl { + pub ty: TypeNode, + pub trait_name: String, + pub tr_module_name: Option, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct CustomType { + pub name: String, + pub builtin: TypeNode, + pub docstring: Option, + pub js_docstring: String, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct OptionalType { + pub inner: TypeNode, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct SequenceType { + pub inner: TypeNode, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct MapType { + pub key: TypeNode, + pub value: TypeNode, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node, AsRef)] +pub struct ExternalType { + pub module_name: String, + pub name: String, + #[as_ref] + pub self_type: TypeNode, +} + +#[derive(Debug, Clone, Node, AsRef)] +#[as_ref] +pub struct TypeNode { + pub ty: Type, + pub canonical_name: String, + pub ffi_converter: String, + pub is_used_as_error: bool, + pub ffi_type: FfiTypeNode, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Node)] +pub enum Type { + // Primitive types. + UInt8, + Int8, + UInt16, + Int16, + UInt32, + Int32, + UInt64, + Int64, + Float32, + Float64, + Boolean, + String, + Bytes, + Timestamp, + Duration, + Interface { + // The module path to the object + module_name: String, + // The name in the "type universe" + name: String, + // How the object is implemented. + imp: ObjectImpl, + }, + // Types defined in the component API, each of which has a string name. + Record { + module_name: String, + name: String, + }, + Enum { + module_name: String, + name: String, + }, + CallbackInterface { + module_name: String, + name: String, + }, + // Structurally recursive types. + Optional { + inner_type: Box, + }, + Sequence { + inner_type: Box, + }, + Map { + key_type: Box, + value_type: Box, + }, + // Custom type on the scaffolding side + Custom { + module_name: String, + name: String, + builtin: Box, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Node)] +pub enum ObjectImpl { + // A single Rust type + Struct, + // A trait that's can be implemented by Rust types + Trait, + // A trait + a callback interface -- can be implemented by both Rust and foreign types. + CallbackTrait, +} + +#[derive(Debug, Clone, Node)] +pub enum FfiDefinition { + /// FFI Function exported in the Rust library + RustFunction(FfiFunction), + /// FFI Function definition used in the interface, language, for example a callback interface method. + FunctionType(FfiFunctionType), + /// Struct definition used in the interface, for example a callback interface Vtable. + Struct(FfiStruct), +} + +#[derive(Debug, Clone, Node, PartialEq, Eq)] +pub struct RustFfiFunctionName(pub String); + +#[derive(Debug, Clone, Node, PartialEq, Eq)] +pub struct FfiStructName(pub String); + +#[derive(Debug, Clone, Node, PartialEq, Eq)] +pub struct FfiFunctionTypeName(pub String); + +#[derive(Debug, Clone, Node)] +pub struct FfiFunction { + pub name: RustFfiFunctionName, + pub async_data: Option, + pub arguments: Vec, + pub return_type: FfiReturnType, + pub has_rust_call_status_arg: bool, + pub kind: FfiFunctionKind, +} + +#[derive(Debug, Clone, PartialEq, Eq, Node)] +pub enum FfiFunctionKind { + Scaffolding, + ObjectClone, + ObjectFree, + RustFuturePoll, + RustFutureComplete, + RustFutureCancel, + RustFutureFree, + RustBufferFromBytes, + RustBufferFree, + RustBufferAlloc, + RustBufferReserve, + RustVtableInit, + UniffiContractVersion, + Checksum, +} + +#[derive(Debug, Clone, Node)] +pub struct FfiFunctionType { + pub name: FfiFunctionTypeName, + pub arguments: Vec, + pub return_type: FfiReturnType, + pub has_rust_call_status_arg: bool, +} + +#[derive(Debug, Clone, Node)] +pub struct FfiReturnType { + pub ty: Option, + pub type_name: String, +} + +#[derive(Debug, Clone, Node)] +pub struct FfiStruct { + pub name: FfiStructName, + pub fields: Vec, +} + +#[derive(Debug, Clone, Node)] +pub struct FfiField { + pub name: String, + pub ty: FfiTypeNode, +} + +#[derive(Debug, Clone, Node)] +pub struct FfiArgument { + pub name: String, + pub ty: FfiTypeNode, +} + +#[derive(Debug, Clone, Node)] +pub struct FfiTypeNode { + #[node(wraps)] + pub ty: FfiType, + pub type_name: String, +} + +#[derive(Debug, Clone, Node)] +pub enum FfiType { + UInt8, + Int8, + UInt16, + Int16, + UInt32, + Int32, + UInt64, + Int64, + Float32, + Float64, + RustArcPtr { + module_name: String, + object_name: String, + }, + RustBuffer(Option), + ForeignBytes, + Function(FfiFunctionTypeName), + Struct(FfiStructName), + Handle(HandleKind), + RustCallStatus, + Reference(Box), + MutReference(Box), + VoidPointer, +} + +#[derive(Debug, Clone, Node, PartialEq, Eq, Hash)] +pub enum HandleKind { + RustFuture, + ForeignFuture, + ForeignFutureCallbackData, + CallbackInterface { + module_name: String, + interface_name: String, + }, +} + +#[derive(Debug, Clone, Node)] +pub struct Checksum { + pub fn_name: RustFfiFunctionName, + pub checksum: u16, +} + +#[derive(Debug, Clone, Node, Template)] +#[template(path = "api-doc.md", escape = "none")] +pub struct ApiModuleDocs { + pub filename: String, + pub jsdoc_module_name: String, + pub module_name: String, + pub classes: Vec, + pub functions: Vec, +} + +/// Combines fixture and non-fixture template items +#[derive(Debug, Clone, Node)] +pub struct CombinedItems { + items: Vec, + fixture_items: Vec, +} + +impl CombinedItems { + /// Create a new CombinedItems value + /// + /// F is a function that finds items in module and pushes them to a vec. + pub fn new(root: &mut Root, mut f: F) -> Self + where + F: FnMut(&mut Module, &mut CombinedItemsIdGenerator, &mut Vec), + { + Self::try_new(root, |module, id_generator, items| { + f(module, id_generator, items); + Ok(()) + }) + .unwrap() + } + + pub fn try_new(root: &mut Root, mut f: F) -> Result + where + F: FnMut(&mut Module, &mut CombinedItemsIdGenerator, &mut Vec) -> Result<()>, + { + // Use 2 separate counters for "real" Rust components vs fixtures. + let mut combined_items = Self { + items: vec![], + fixture_items: vec![], + }; + let mut id_generator = CombinedItemsIdGenerator::default(); + // Process non-fixture items first for a couple reasons: + // * It works better when a pass wants to de-dupe items, like we do for FFI definitions, + // and an item appears in both `items` and `fixture_items`. This way the de-duped item + // won't be disabled by the if guard and also it will appear on top of the item list, + // which avoids issues with dependent definitions. + // * It means the IDs get grouped together, which can make for a more efficient `switch` + // statement. + + root.try_visit_mut(|module: &mut Module| { + if !module.fixture { + f(module, &mut id_generator, &mut combined_items.items) + } else { + Ok(()) + } + })?; + root.try_visit_mut(|module: &mut Module| { + if module.fixture { + f(module, &mut id_generator, &mut combined_items.fixture_items) + } else { + Ok(()) + } + })?; + Ok(combined_items) + } + + pub fn sort_by_key(&mut self, f: F) + where + F: Fn(&T) -> K, + K: Ord, + { + self.items.sort_by_key(&f); + self.fixture_items.sort_by_key(&f); + } + + /// Iterate over child items + /// Each item is the tuple (preprocssor_condition, , preprocssor_condition_end), where + /// `preprocssor_condition` is the preprocessor preprocssor_condition that should control if + /// the items are included. + fn iter(&self) -> impl Iterator { + vec![ + ("".to_string(), &*self.items, "".to_string()), + ( + "#ifdef MOZ_UNIFFI_FIXTURES".to_string(), + &*self.fixture_items, + "#endif /* MOZ_UNIFFI_FIXTURES */".to_string(), + ), + ] + .into_iter() + } +} + +#[derive(Default)] +pub struct CombinedItemsIdGenerator { + counter: u64, +} + +impl CombinedItemsIdGenerator { + pub fn new_id(&mut self) -> u64 { + self.counter += 1; + self.counter + } +} + +impl ScaffoldingCall { + pub fn is_async(&self) -> bool { + self.ffi_func.async_data.is_some() + } +} + +impl FfiFunction { + pub fn arg_types(&self) -> Vec<&str> { + self.arguments + .iter() + .map(|a| a.ty.type_name.as_str()) + .chain(self.has_rust_call_status_arg.then_some("RustCallStatus*")) + .collect() + } +} + +impl FfiFunctionType { + pub fn arg_types(&self) -> Vec<&str> { + self.arguments + .iter() + .map(|a| a.ty.type_name.as_str()) + .chain(self.has_rust_call_status_arg.then_some("RustCallStatus*")) + .collect() + } +} + +pub mod filters { + use super::*; + use askama::Result; + + pub fn ffi_converter(ty: impl AsRef) -> Result { + Ok(ty.as_ref().ffi_converter.to_string()) + } + + pub fn lift_fn(ty: impl AsRef) -> Result { + Ok(format!("{}.lift", ty.as_ref().ffi_converter)) + } + + pub fn lower_fn(ty: impl AsRef) -> Result { + Ok(format!("{}.lower", ty.as_ref().ffi_converter)) + } + + pub fn read_fn(ty: impl AsRef) -> Result { + Ok(format!("{}.read", ty.as_ref().ffi_converter)) + } + + pub fn write_fn(ty: impl AsRef) -> Result { + Ok(format!("{}.write", ty.as_ref().ffi_converter)) + } + + pub fn compute_size_fn(ty: impl AsRef) -> Result { + Ok(format!("{}.computeSize", ty.as_ref().ffi_converter)) + } + + pub fn check_type_fn(ty: impl AsRef) -> Result { + Ok(format!("{}.checkType", ty.as_ref().ffi_converter)) + } + + // Render an expression to check if two instances of this type are equal + pub fn field_equals(field: &Field, first_obj: &str, second_obj: &str) -> Result { + let name = &field.name; + Ok(match &field.ty.ty { + Type::Record { .. } => format!("{first_obj}.{name}.equals({second_obj}.{name})"), + _ => format!("{first_obj}.{name} == {second_obj}.{name}"), + }) + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/build.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/types.rs similarity index 50% rename from toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/build.rs rename to toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/types.rs index 9ea03e12de13..d9df1c79496a 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/refcounts/build.rs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/pipeline/types.rs @@ -2,6 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -fn main() { - uniffi::generate_scaffolding("./src/refcounts.udl").unwrap(); +use super::*; + +pub fn pass(root: &mut Root) -> Result<()> { + root.visit_mut(|node: &mut TypeNode| { + node.ffi_converter = format!("FfiConverter{}", node.canonical_name); + }); + + Ok(()) } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/render/cpp.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/render/cpp.rs deleted file mode 100644 index 992fa48f5952..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/render/cpp.rs +++ /dev/null @@ -1,519 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public -License, v. 2.0. If a copy of the MPL was not distributed with this -* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! This module generates the UniFFI C++ code that sits between the Rust scaffolding code and the -//! generated JS code. The main responsibility of the generated C++ code is to implement the -//! UniFFI WebIDL interface. -//! -//! The general strategy is to take the generalized component interface and convert it into types -//! that can be easily rendered by the UniFFIScaffolding.cpp template -- an intermediate -//! representation of sorts. -//! -//! In many cases this means converting a type from `uniffi_bindgen::interface` into another type -//! that represents the same concept, but is easier for the templates to render. In this case, the -//! new type name has `Cpp` appended to it ([FfiFunction] is converted to [FfiFunctionCpp]). - -use std::collections::HashSet; - -use askama::Template; -use heck::{ToSnakeCase, ToUpperCamelCase}; -use uniffi_bindgen::interface::{ - AsType, Callable, CallbackInterface, ComponentInterface, FfiDefinition, FfiFunction, FfiType, -}; - -use super::shared::*; -use crate::{CallbackIds, Component, FunctionIds, ObjectIds}; - -#[derive(Template)] -#[template(path = "UniFFIScaffolding.cpp", escape = "none")] -pub struct CPPScaffoldingTemplate { - all_ffi_definitions: CombinedItems>, - all_pointer_types: CombinedItems>, - all_callback_interfaces: CombinedItems>, - all_scaffolding_calls: CombinedItems>, -} - -impl CPPScaffoldingTemplate { - pub fn new( - components: &[Component], - fixture_components: &[Component], - function_ids: &FunctionIds<'_>, - object_ids: &ObjectIds<'_>, - callback_ids: &CallbackIds<'_>, - ) -> Self { - Self { - all_ffi_definitions: Self::all_ffi_definitions(components, fixture_components), - all_pointer_types: CombinedItems::new( - Self::pointer_types(object_ids, components), - Self::pointer_types(object_ids, fixture_components), - ), - all_callback_interfaces: CombinedItems::new( - Self::callback_interfaces(callback_ids, components), - Self::callback_interfaces(callback_ids, fixture_components), - ), - all_scaffolding_calls: CombinedItems::new( - Self::scaffolding_calls(function_ids, components), - Self::scaffolding_calls(function_ids, fixture_components), - ), - } - } - - fn all_ffi_definitions( - components: &[Component], - fixture_components: &[Component], - ) -> CombinedItems> { - // Track which FFI definition's we've seen and don't add them twice. - // This avoids duplicate definitions for shared FFI types like `CallbackInterfaceFree`. - // - // The code below ordered so that duplicated definitions get added to the components side - // of `CombinedItems` rather than the fixtures side. This way if fixtures are disabled, we - // don't see missing definition errors. - let mut seen_names = HashSet::new(); - - CombinedItems::new( - Self::ffi_definitions(components) - .into_iter() - .filter(|ffi_def| seen_names.insert(ffi_def.name().to_owned())) - .collect(), - Self::ffi_definitions(fixture_components) - .into_iter() - .filter(|ffi_def| seen_names.insert(ffi_def.name().to_owned())) - .collect(), - ) - } - - fn ffi_definitions(components: &[Component]) -> Vec { - components - .iter() - .flat_map(|c| c.ci.ffi_definitions()) - .map(|ffi_definition| match ffi_definition { - FfiDefinition::Function(ffi_func) => FfiDefinitionCpp::Function(FfiFunctionCpp { - name: ffi_func.name().to_snake_case(), - arg_types: ffi_func - .arguments() - .iter() - .map(|a| ffi_type_name(&a.type_())) - .chain( - ffi_func - .has_rust_call_status_arg() - .then(|| "RustCallStatus*".to_owned()), - ) - .collect(), - return_type: return_type(ffi_func.return_type()), - }), - FfiDefinition::CallbackFunction(ffi_callback) => { - FfiDefinitionCpp::CallbackFunction(FfiCallbackFunctionCpp { - name: ffi_callback.name().to_upper_camel_case(), - arg_types: ffi_callback - .arguments() - .into_iter() - .map(|a| ffi_type_name(&a.type_())) - .chain( - ffi_callback - .has_rust_call_status_arg() - .then(|| "RustCallStatus*".to_owned()), - ) - .collect(), - return_type: return_type(ffi_callback.return_type()), - }) - } - FfiDefinition::Struct(ffi_struct) => FfiDefinitionCpp::Struct(FfiStructCpp { - name: ffi_struct.name().to_upper_camel_case(), - fields: ffi_struct - .fields() - .iter() - .map(|f| FfiFieldCpp { - name: f.name().to_snake_case(), - type_: ffi_type_name(&f.type_()), - }) - .collect(), - }), - }) - .collect() - } - - fn pointer_types(object_ids: &ObjectIds<'_>, components: &[Component]) -> Vec { - components - .iter() - .flat_map(|c| { - c.ci.object_definitions() - .iter() - .map(move |obj| PointerType { - object_id: object_ids.get(&c.ci, obj), - name: pointer_type(c.ci.namespace(), obj.name()), - ffi_value_class: pointer_ffi_value_class(c.ci.namespace(), obj.name()), - label: format!("{}::{}", c.ci.namespace(), obj.name()), - clone_fn: obj.ffi_object_clone().name().to_string(), - free_fn: obj.ffi_object_free().name().to_string(), - }) - }) - .collect() - } - - fn callback_interfaces( - callback_ids: &CallbackIds<'_>, - components: &[Component], - ) -> Vec { - components - .iter() - .flat_map(|c| { - c.ci.callback_interface_definitions() - .iter() - .map(move |cbi| { - let cbi_name = cbi.name().to_upper_camel_case(); - CallbackInterfaceCpp { - id: callback_ids.get(&c.ci, cbi), - name: format!("{}:{}", c.ci.namespace(), cbi.name()), - js_handler_var: format!("gCallbackInterfaceJsHandler{cbi_name}"), - vtable: Self::callback_interface_vtable(&c.ci, cbi), - free_fn: format!("callbackInterfaceFree{cbi_name}"), - init_fn: cbi.ffi_init_callback().name().to_owned(), - } - }) - }) - .collect() - } - - fn callback_interface_vtable( - ci: &ComponentInterface, - cbi: &CallbackInterface, - ) -> CallbackInterfaceVTable { - let cbi_name = cbi.name().to_upper_camel_case(); - let cbi_name_snake = cbi.name().to_snake_case(); - - CallbackInterfaceVTable { - type_: ffi_type_name(&cbi.vtable()), - var_name: format!("kCallbackInterfaceVtable{cbi_name}"), - method_handlers: cbi - .vtable_methods() - .iter() - .map(|(_, method)| { - let method_name = method.name().to_upper_camel_case(); - let method_name_snake = method.name().to_snake_case(); - CallbackMethodHandler { - fn_name: format!("callback_interface_{cbi_name_snake}_{method_name_snake}"), - class_name: format!("CallbackInterfaceMethod{cbi_name}{method_name}"), - arguments: method - .arguments() - .iter() - .map(|arg| { - let ffi_type = arg.as_type().into(); - CallbackMethodArgument { - name: arg.name().to_snake_case(), - ffi_type: ffi_type_name(&ffi_type), - ffi_value_class: ffi_value_class(ci, &ffi_type), - } - }) - .collect(), - } - }) - .collect(), - } - } - - fn scaffolding_calls( - function_ids: &FunctionIds<'_>, - components: &[Component], - ) -> Vec { - let mut calls: Vec = components - .iter() - .flat_map(|c| { - exposed_functions(&c.ci).map(move |(callable, ffi_func)| { - ScaffoldingCall::new(&c.ci, callable, ffi_func, function_ids) - }) - }) - .collect(); - calls.sort_by_key(|c| c.function_id); - calls - } -} - -/// Combines fixture and non-fixture template items -struct CombinedItems { - item: T, - fixture_item: T, -} - -impl CombinedItems { - fn new(item: T, fixture_item: T) -> Self { - Self { item, fixture_item } - } - - /// Iterate over child items - /// Each item is the tuple (preprocssor_condition, , preprocssor_condition_end), where - /// `preprocssor_condition` is the preprocessor preprocssor_condition that should control if - /// the items are included. - fn iter(&self) -> impl Iterator { - vec![ - ("".to_string(), &self.item, "".to_string()), - ( - "#ifdef MOZ_UNIFFI_FIXTURES".to_string(), - &self.fixture_item, - "#endif /* MOZ_UNIFFI_FIXTURES */".to_string(), - ), - ] - .into_iter() - } -} - -enum FfiDefinitionCpp { - Function(FfiFunctionCpp), - CallbackFunction(FfiCallbackFunctionCpp), - Struct(FfiStructCpp), -} - -impl FfiDefinitionCpp { - fn name(&self) -> &str { - match self { - Self::Function(f) => &f.name, - Self::CallbackFunction(c) => &c.name, - Self::Struct(s) => &s.name, - } - } -} - -struct FfiFunctionCpp { - name: String, - arg_types: Vec, - return_type: String, -} - -struct FfiCallbackFunctionCpp { - name: String, - arg_types: Vec, - return_type: String, -} - -struct FfiStructCpp { - name: String, - fields: Vec, -} - -struct FfiFieldCpp { - name: String, - type_: String, -} - -struct PointerType { - object_id: usize, - name: String, - ffi_value_class: String, - label: String, - clone_fn: String, - free_fn: String, -} - -struct CallbackInterfaceCpp { - id: usize, - name: String, - /// Static variable that stores a reference to the JS UniFFICallbackHandler object - js_handler_var: String, - vtable: CallbackInterfaceVTable, - free_fn: String, - init_fn: String, -} - -/// Represents the vtable for a callback interface -/// -/// "vtable" just means a struct whose fields are function pointers -- one for each method. -struct CallbackInterfaceVTable { - /// FFI struct name - type_: String, - /// Name of the static variable storing the vtable - var_name: String, - /// Functions to handle the callback interface methods - /// - /// These are then stored in the vtable fields - method_handlers: Vec, -} - -/// Code to handle a single callback interface method -struct CallbackMethodHandler { - /// C++ function to handle the method - fn_name: String, - /// UniffiCallbackMethodHandlerBase subclass for this method - class_name: String, - arguments: Vec, -} - -struct CallbackMethodArgument { - name: String, - ffi_type: String, - ffi_value_class: String, -} - -struct ScaffoldingCall { - handler_class_name: String, - function_id: usize, - ffi_func_name: String, - return_type: Option, - arguments: Vec, - async_info: Option, -} - -impl ScaffoldingCall { - fn new( - ci: &ComponentInterface, - callable: &dyn Callable, - ffi_func: &FfiFunction, - function_ids: &FunctionIds, - ) -> Self { - let handler_class_name = format!( - "ScaffoldingCallHandler{}", - ffi_func.name().to_upper_camel_case() - ); - let arguments = ffi_func - .arguments() - .into_iter() - .map(|a| ScaffoldingCallArgument { - var_name: format!("m{}", a.name().to_upper_camel_case()), - ffi_value_class: ffi_value_class(ci, &a.type_()), - }) - .collect::>(); - - let async_info = callable.is_async().then(|| ScaffoldingCallAsyncInfo { - poll_fn: callable.ffi_rust_future_poll(ci), - complete_fn: callable.ffi_rust_future_complete(ci), - free_fn: callable.ffi_rust_future_free(ci), - }); - - Self { - handler_class_name, - function_id: function_ids.get(ci, ffi_func), - ffi_func_name: ffi_func.name().to_owned(), - // Make sure to use the callable here, not the ffi_func. For async functions, the FFI - // function always returns a handle. - return_type: callable - .return_type() - .map(FfiType::from) - .map(|return_type| ScaffoldingCallReturnType { - ffi_value_class: ffi_value_class(ci, &return_type), - }), - arguments, - async_info, - } - } - - fn is_async(&self) -> bool { - self.async_info.is_some() - } -} - -struct ScaffoldingCallReturnType { - ffi_value_class: String, -} - -struct ScaffoldingCallArgument { - var_name: String, - ffi_value_class: String, -} - -struct ScaffoldingCallAsyncInfo { - poll_fn: String, - complete_fn: String, - free_fn: String, -} - -fn ffi_value_class(ci: &ComponentInterface, ffi_type: &FfiType) -> String { - match ffi_type { - FfiType::RustArcPtr(name) => { - // Check if this is an external type - for ty in ci.iter_external_types() { - let external_ty_name = ty.name().expect("External type without name"); - let crate_name = ty.module_path().expect("External type without module path"); - if external_ty_name == name { - return pointer_ffi_value_class(crate_name_to_namespace(crate_name), name); - } - } - pointer_ffi_value_class(ci.namespace(), name) - } - FfiType::UInt8 - | FfiType::Int8 - | FfiType::UInt16 - | FfiType::Int16 - | FfiType::UInt32 - | FfiType::Int32 - | FfiType::UInt64 - | FfiType::Int64 => format!("FfiValueInt<{}>", ffi_type_name(ffi_type)), - FfiType::Float32 | FfiType::Float64 => { - format!("FfiValueFloat<{}>", ffi_type_name(ffi_type)) - } - FfiType::RustBuffer(_) => "FfiValueRustBuffer".to_owned(), - _ => format!("FfiConverter<{}>", ffi_type_name(ffi_type)), - } -} - -fn pointer_type(namespace: &str, name: &str) -> String { - format!( - "k{}{}PointerType", - namespace.to_upper_camel_case(), - name.to_upper_camel_case() - ) -} - -fn pointer_ffi_value_class(namespace: &str, name: &str) -> String { - format!( - "FfiValueObjectHandle{}{}", - namespace.to_upper_camel_case(), - name.to_upper_camel_case() - ) -} - -// C++ type for an FFI value -fn ffi_type_name(ffi_type: &FfiType) -> String { - match ffi_type { - FfiType::UInt8 => "uint8_t".to_owned(), - FfiType::Int8 => "int8_t".to_owned(), - FfiType::UInt16 => "uint16_t".to_owned(), - FfiType::Int16 => "int16_t".to_owned(), - FfiType::UInt32 => "uint32_t".to_owned(), - FfiType::Int32 => "int32_t".to_owned(), - FfiType::UInt64 => "uint64_t".to_owned(), - FfiType::Int64 => "int64_t".to_owned(), - FfiType::Float32 => "float".to_owned(), - FfiType::Float64 => "double".to_owned(), - FfiType::RustBuffer(_) => "RustBuffer".to_owned(), - FfiType::RustArcPtr(_) => "void*".to_owned(), - FfiType::ForeignBytes => "ForeignBytes".to_owned(), - FfiType::Handle => "uint64_t".to_owned(), - FfiType::RustCallStatus => "RustCallStatus".to_owned(), - FfiType::Callback(name) | FfiType::Struct(name) => name.to_owned(), - FfiType::VoidPointer => "void*".to_owned(), - FfiType::MutReference(inner) | FfiType::Reference(inner) => { - format!("{}*", ffi_type_name(inner.as_ref())) - } - } -} - -fn return_type(ffi_type: Option<&FfiType>) -> String { - match ffi_type { - Some(t) => ffi_type_name(t), - None => "void".to_owned(), - } -} - -// Iterate over functions, methods, and constructors exposed to JS -// -// Generates `&dyn Callable` items, since of these is a different type, but they all implement -// `Callable`. -// -// Also generates `&FfiFunction` for each item. There should probably be a method on `Callable` -// that returns this and there's a PR to do so, but in the meantime we need to use this workaround. -pub fn exposed_functions( - ci: &ComponentInterface, -) -> impl Iterator { - ci.function_definitions() - .iter() - .map(|f| (f as &dyn Callable, f.ffi_func())) - .chain(ci.object_definitions().iter().flat_map(|o| { - o.methods() - .into_iter() - .map(|m| (m as &dyn Callable, m.ffi_func())) - .chain( - o.constructors() - .into_iter() - .map(|c| (c as &dyn Callable, c.ffi_func())), - ) - })) -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/render/js.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/render/js.rs deleted file mode 100644 index e24c30263d01..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/render/js.rs +++ /dev/null @@ -1,476 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public -License, v. 2.0. If a copy of the MPL was not distributed with this -* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use super::shared::*; -use crate::{CallbackIds, Config, FunctionIds, ObjectIds}; -use askama::Template; -use camino::Utf8PathBuf; -use extend::ext; -use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase}; -use uniffi_bindgen::interface::{ - Argument, AsType, Callable, CallbackInterface, ComponentInterface, Constructor, Enum, Field, - Function, Literal, Method, Object, Radix, Record, Type, Variant, -}; - -fn js_arg_names(args: &[&Argument]) -> String { - args.iter() - .map(|arg| { - if let Some(default_value) = arg.default_value() { - format!("{} = {}", arg.js_name(), default_value.render()) - } else { - arg.js_name() - } - }) - .collect::>() - .join(",") -} - -fn render_enum_literal(typ: &Type, variant_name: &str) -> String { - if let Type::Enum { name, .. } = typ { - // TODO: This does not support complex enum literals yet. - format!( - "{}.{}", - name.to_upper_camel_case(), - variant_name.to_shouty_snake_case() - ) - } else { - panic!("Rendering an enum literal on a type that is not an enum") - } -} - -#[derive(Template)] -#[template(path = "js/wrapper.sys.mjs", escape = "none")] -pub struct JSBindingsTemplate<'a> { - pub ci: &'a ComponentInterface, - pub config: &'a Config, - pub function_ids: &'a FunctionIds<'a>, - pub object_ids: &'a ObjectIds<'a>, - pub callback_ids: &'a CallbackIds<'a>, - pub js_dir: &'a Utf8PathBuf, -} - -impl JSBindingsTemplate<'_> { - pub fn js_module_name(&self) -> String { - js_module_name(self.ci.namespace()) - } - - fn external_type_module(&self, crate_name: &str) -> String { - format!( - "moz-src:///{}/{}", - self.js_dir, - self.js_module_name_for_crate_name(crate_name), - ) - } - - fn js_module_name_for_crate_name(&self, crate_name: &str) -> String { - js_module_name(crate_name_to_namespace(crate_name)) - } -} - -// Define extension traits with methods used in our template code - -#[ext(name=LiteralJSExt)] -pub impl Literal { - fn render(&self) -> String { - match self { - Literal::Boolean(inner) => inner.to_string(), - Literal::String(inner) => format!("\"{}\"", inner), - Literal::UInt(num, radix, _) => radix.render_num(num).to_string(), - Literal::Int(num, radix, _) => radix.render_num(num).to_string(), - Literal::Float(num, _) => num.clone(), - Literal::Enum(name, typ) => render_enum_literal(typ, name), - Literal::EmptyMap => "{}".to_string(), - Literal::EmptySequence => "[]".to_string(), - Literal::Some { inner } => inner.render(), - Literal::None => "null".to_string(), - } - } -} - -#[ext(name=RadixJSExt)] -pub impl Radix { - fn render_num( - &self, - num: impl std::fmt::Display + std::fmt::LowerHex + std::fmt::Octal, - ) -> String { - match self { - Radix::Decimal => format!("{}", num), - Radix::Hexadecimal => format!("{:#x}", num), - Radix::Octal => format!("{:#o}", num), - } - } -} - -#[ext(name=RecordJSExt)] -pub impl Record { - fn js_name(&self) -> String { - self.name().to_upper_camel_case() - } - - fn constructor_field_list(&self) -> String { - let o = self - .fields() - .iter() - .map(|field| { - if let Some(default_value) = field.default_value() { - format!("{} = {}", field.js_name(), default_value.render()) - } else { - field.js_name() - } - }) - .collect::>() - .join(", "); - format!("{{ {o} }}") - } - - fn js_docstring(&self, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_docstring(docstring, spaces), - None => format_docstring(&self.js_name(), spaces), - } - } -} - -#[ext(name=CallbackInterfaceJSExt)] -pub impl CallbackInterface { - fn js_name(&self) -> String { - self.name().to_upper_camel_case() - } - - fn handler(&self) -> String { - format!("callbackHandler{}", self.js_name()) - } -} - -#[ext(name=FieldJSExt)] -pub impl Field { - fn js_name(&self) -> String { - self.name().to_lower_camel_case() - } - - fn lower_fn(&self) -> String { - self.as_type().lower_fn() - } - - fn lift_fn(&self) -> String { - self.as_type().lift_fn() - } - - fn write_datastream_fn(&self) -> String { - self.as_type().write_datastream_fn() - } - - fn read_datastream_fn(&self) -> String { - self.as_type().read_datastream_fn() - } - - fn compute_size_fn(&self) -> String { - self.as_type().compute_size_fn() - } - - fn ffi_converter(&self) -> String { - self.as_type().ffi_converter() - } - - fn js_docstring(&self, spaces: usize) -> String { - let type_docstring = format!("@type {{{}}}", self.as_type().type_name()); - let full_docstring = match self.docstring() { - Some(docstring) => format!("{docstring}\n{type_docstring}"), - None => type_docstring.to_string(), - }; - format_docstring(&full_docstring, spaces) - } -} - -#[ext(name=ArgumentJSExt)] -pub impl Argument { - fn js_name(&self) -> String { - self.name().to_lower_camel_case() - } - - fn lower_fn(&self) -> String { - self.as_type().lower_fn() - } - - fn lift_fn(&self) -> String { - self.as_type().lift_fn() - } - - fn write_datastream_fn(&self) -> String { - self.as_type().write_datastream_fn() - } - - fn read_datastream_fn(&self) -> String { - self.as_type().read_datastream_fn() - } - - fn compute_size_fn(&self) -> String { - self.as_type().compute_size_fn() - } - - fn ffi_converter(&self) -> String { - self.as_type().ffi_converter() - } -} - -#[ext(name=TypeJSExt)] -pub impl Type { - // Render an expression to check if two instances of this type are equal - fn equals(&self, first: &str, second: &str) -> String { - match self { - Type::Record { .. } => format!("{}.equals({})", first, second), - _ => format!("{} == {}", first, second), - } - } - - fn lower_fn(&self) -> String { - format!("{}.lower", self.ffi_converter()) - } - - fn lift_fn(&self) -> String { - format!("{}.lift", self.ffi_converter()) - } - - fn write_datastream_fn(&self) -> String { - format!("{}.write", self.ffi_converter()) - } - - fn read_datastream_fn(&self) -> String { - format!("{}.read", self.ffi_converter()) - } - - fn compute_size_fn(&self) -> String { - format!("{}.computeSize", self.ffi_converter()) - } - - fn type_name(&self) -> String { - match self { - Type::Int8 - | Type::UInt8 - | Type::Int16 - | Type::UInt16 - | Type::Int32 - | Type::UInt32 - | Type::Int64 - | Type::UInt64 - | Type::Float32 - | Type::Float64 => "number".into(), - Type::String => "string".into(), - // TODO: should be Uint8Array - Type::Bytes => "string".into(), - Type::Boolean => "Boolean".into(), - Type::Object { name, .. } - | Type::Enum { name, .. } - | Type::Record { name, .. } - | Type::CallbackInterface { name, .. } - | Type::Custom { name, .. } => name.to_upper_camel_case(), - Type::Optional { inner_type } => format!("?{}", inner_type.type_name()), - Type::Sequence { inner_type } => format!("Array.<{}>", inner_type.type_name()), - Type::Map { .. } => "object".into(), - Type::Timestamp => unimplemented!("Timestamp"), - Type::Duration => unimplemented!("Duration"), - } - } - - fn canonical_name(&self) -> String { - match self { - Type::Int8 => "i8".into(), - Type::UInt8 => "u8".into(), - Type::Int16 => "i16".into(), - Type::UInt16 => "u16".into(), - Type::Int32 => "i32".into(), - Type::UInt32 => "u32".into(), - Type::Int64 => "i64".into(), - Type::UInt64 => "u64".into(), - Type::Float32 => "f32".into(), - Type::Float64 => "f64".into(), - Type::String => "string".into(), - Type::Bytes => "bytes".into(), - Type::Boolean => "bool".into(), - Type::Object { name, .. } - | Type::Enum { name, .. } - | Type::Record { name, .. } - | Type::CallbackInterface { name, .. } => format!("Type{name}"), - Type::Timestamp => "Timestamp".into(), - Type::Duration => "Duration".into(), - Type::Optional { inner_type } => format!("Optional{}", inner_type.canonical_name()), - Type::Sequence { inner_type } => format!("Sequence{}", inner_type.canonical_name()), - Type::Map { - key_type, - value_type, - } => format!( - "Map{}{}", - key_type.canonical_name().to_upper_camel_case(), - value_type.canonical_name().to_upper_camel_case() - ), - Type::Custom { name, .. } => format!("Type{name}"), - } - } - - fn ffi_converter(&self) -> String { - format!( - "FfiConverter{}", - self.canonical_name().to_upper_camel_case() - ) - } -} - -#[ext(name=EnumJSExt)] -pub impl Enum { - fn js_name(&self) -> String { - self.name().to_upper_camel_case() - } - - fn js_docstring(&self, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_docstring(docstring, spaces), - None => format_docstring(&self.js_name(), spaces), - } - } - - // Get the discriminant value for a variant at the given index - fn variant_discriminant(&self, idx: &usize) -> Result { - // We need to return the actual discriminant values from the Rust enum - match self.variant_discr(*idx) { - Ok(Literal::UInt(v, _, _)) => Ok(v), - Ok(Literal::Int(v, _, _)) if v >= 0 => Ok(v as u64), - Ok(other) => Err(format!( - "Unexpected literal type for enum discriminant: {:?}", - other - )), - Err(e) => Err(format!("Failed to get discriminant: {}", e)), - } - } -} - -#[ext(name=VariantJSExt)] -pub impl Variant { - fn js_name(&self, enum_is_flat: bool) -> String { - if enum_is_flat { - self.name().to_shouty_snake_case() - } else { - self.name().to_upper_camel_case() - } - } - - fn js_docstring(&self, enum_is_flat: bool, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_docstring(docstring, spaces), - None => format_docstring(&self.js_name(enum_is_flat), spaces), - } - } -} - -#[ext(name=FunctionJSExt)] -pub impl Function { - fn js_arg_names(&self) -> String { - js_arg_names(self.arguments().as_slice()) - } - - fn js_name(&self) -> String { - self.name().to_lower_camel_case() - } - - fn js_docstring(&self, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_callable_docstring(self, docstring, spaces), - None => format_callable_docstring(self, &self.js_name(), spaces), - } - } -} - -#[ext(name=ObjectJSExt)] -pub impl Object { - fn js_name(&self) -> String { - self.name().to_upper_camel_case() - } - - fn js_docstring(&self, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_docstring(docstring, spaces), - None => format_docstring(&self.js_name(), spaces), - } - } -} - -#[ext(name=ConstructorJSExt)] -pub impl Constructor { - fn js_name(&self) -> String { - if self.is_primary_constructor() { - "init".to_string() - } else { - self.name().to_lower_camel_case() - } - } - - fn js_arg_names(&self) -> String { - js_arg_names(self.arguments().as_slice()) - } - - fn js_docstring(&self, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_callable_docstring(self, docstring, spaces), - None => format_callable_docstring(self, &self.js_name(), spaces), - } - } -} - -#[ext(name=MethodJSExt)] -pub impl Method { - fn js_arg_names(&self) -> String { - js_arg_names(self.arguments().as_slice()) - } - - fn js_name(&self) -> String { - self.name().to_lower_camel_case() - } - - fn js_docstring(&self, spaces: usize) -> String { - match self.docstring() { - Some(docstring) => format_callable_docstring(self, docstring, spaces), - None => format_callable_docstring(self, &self.js_name(), spaces), - } - } -} - -pub fn js_module_name(namespace: &str) -> String { - // The plain namespace name is a bit too generic as a module name for m-c, so we - // prefix it with "Rust". Later we'll probably allow this to be customized. - format!("Rust{}.sys.mjs", namespace.to_upper_camel_case()) -} - -/// Format a docstring for the JS code -/// -/// Spaces in the number of leading spaces to insert. This helps format nested items correctly, -/// like methods. -fn format_docstring(docstring: &str, spaces: usize) -> String { - let leading_space = " ".repeat(spaces); - // Remove any existing indentation - let docstring = textwrap::dedent(docstring); - // "Escape" `*/` chars to avoid closing the comment - let docstring = docstring.replace("*/", "* /"); - // Format the docstring making sure to: - // - Start with `/**` and end with `*/` - // - Line up all the `*` chars correctly - // - Indent all lines based on `spaces`, except the first which is typically already indented - // in the template. - // - Add trailing leading spaces, to make this work with the `{{ -}}` tag - format!( - "/**\n{}\n{leading_space} */\n{leading_space}", - textwrap::indent(&docstring, &format!("{leading_space} * ")) - ) -} - -fn format_callable_docstring(callable: &impl Callable, docstring: &str, spaces: usize) -> String { - let mut parts = vec![docstring.to_string()]; - if let Some(return_type) = callable.return_type() { - let return_type_name = return_type.type_name(); - parts.push(if callable.is_async() { - format!("@returns {{Promise<{return_type_name}>}}}}") - } else { - format!("@returns {{{return_type_name}}}") - }); - }; - format_docstring(&parts.join("\n"), spaces) -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/render/mod.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/render/mod.rs deleted file mode 100644 index f9ceeb9872b9..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/render/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public -License, v. 2.0. If a copy of the MPL was not distributed with this -* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -pub mod cpp; -pub mod js; -pub mod shared; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/render/shared.rs b/toolkit/components/uniffi-bindgen-gecko-js/src/render/shared.rs deleted file mode 100644 index 23b1851666c8..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/render/shared.rs +++ /dev/null @@ -1,67 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public -License, v. 2.0. If a copy of the MPL was not distributed with this -* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/// Extension traits that are shared across multiple render targets -use crate::Config; -use extend::ext; -use uniffi_bindgen::interface::{Callable, Constructor, Function, Method, Object}; - -/// How should we call a Rust function from JS? -pub enum CallStyle { - /// Sync Rust function - Sync, - /// Async Rust function - Async, - /// Sync Rust function, wrapped to be async - AsyncWrapper, -} - -impl CallStyle { - /// Is the JS version of this function async? - pub fn is_js_async(&self) -> bool { - matches!(self, Self::Async | Self::AsyncWrapper) - } -} - -fn call_style(callable: impl Callable, config: &Config, spec: &str) -> CallStyle { - if callable.is_async() { - CallStyle::Async - } else if config.async_wrappers.enable && !config.async_wrappers.main_thread.contains(spec) { - CallStyle::AsyncWrapper - } else { - CallStyle::Sync - } -} - -/// Map Rust crate names to UniFFI namespaces. -pub fn crate_name_to_namespace(crate_name: &str) -> &str { - // TODO: remove this hack, we should be able to calculate this by walking the CI data. - match crate_name { - "uniffi_geometry" => "geometry", - "uniffi_sprites" => "sprites", - s => s, - } -} - -#[ext] -pub impl Function { - fn call_style(&self, config: &Config) -> CallStyle { - call_style(self, config, self.name()) - } -} - -#[ext] -pub impl Object { - fn call_style_for_constructor(&self, cons: &Constructor, config: &Config) -> CallStyle { - call_style(cons, config, &format!("{}.{}", self.name(), cons.name())) - } - - fn call_style_for_method(&self, method: &Method, config: &Config) -> CallStyle { - call_style( - method, - config, - &format!("{}.{}", self.name(), method.name()), - ) - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/UniFFIScaffolding.cpp b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/UniFFIScaffolding.cpp deleted file mode 100644 index cb01eb404e7b..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/UniFFIScaffolding.cpp +++ /dev/null @@ -1,487 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ - -// Generated by uniffi-bindgen-gecko-js. DO NOT EDIT. - -#include "nsString.h" -#include "nsPrintfCString.h" -#include "mozilla/Logging.h" -#include "mozilla/Maybe.h" -#include "mozilla/StaticPtr.h" -#include "mozilla/UniquePtr.h" -#include "mozilla/dom/Promise.h" -#include "mozilla/dom/UniFFIScaffolding.h" -#include "mozilla/uniffi/Call.h" -#include "mozilla/uniffi/Callbacks.h" -#include "mozilla/uniffi/FfiValue.h" -#include "mozilla/uniffi/PointerType.h" -#include "mozilla/uniffi/Rust.h" - -namespace mozilla::uniffi { - -using dom::ArrayBuffer; -using dom::AutoEntryScript; -using dom::GlobalObject; -using dom::RootedDictionary; -using dom::NullableRootedUnion; -using dom::Promise; -using dom::OwningUniFFIScaffoldingValue; -using dom::Sequence; -using dom::UniFFICallbackHandler; -using dom::UniFFIPointer; -using dom::UniFFIScaffoldingCallResult; - -// Define scaffolding functions from UniFFI -extern "C" { - {%- for (preprocessor_condition, ffi_definitions, preprocessor_condition_end) in all_ffi_definitions.iter() %} -{{ preprocessor_condition }} - {%- for def in ffi_definitions %} - {%- match def %} - {%- when FfiDefinitionCpp::Function(func) %} - {{ func.return_type }} {{ func.name }}({{ func.arg_types|join(", ") }}); - {%- when FfiDefinitionCpp::CallbackFunction(func) %} - typedef {{ func.return_type }} (*{{ func.name }})({{ func.arg_types|join(", ") }}); - {%- when FfiDefinitionCpp::Struct(ffi_struct) %} - struct {{ ffi_struct.name }} { - {%- for field in ffi_struct.fields %} - {{ field.type_ }} {{ field.name }}; - {%- endfor %} - }; - {%- endmatch %} - {%- endfor %} -{{ preprocessor_condition_end }} - {%- endfor %} -} - -// Define pointer types and FfiValueObjectHandle* classes -{%- for (preprocessor_condition, pointer_types, preprocessor_condition_end) in all_pointer_types.iter() %} -{{ preprocessor_condition }} -{%- for pointer_type in pointer_types %} -const static mozilla::uniffi::UniFFIPointerType {{ pointer_type.name }} { - "{{ pointer_type.label }}"_ns, - {{ pointer_type.clone_fn }}, - {{ pointer_type.free_fn }}, -}; - -class {{ pointer_type.ffi_value_class }} { - private: - void* mValue = nullptr; - - public: - {{ pointer_type.ffi_value_class }}() = default; - explicit {{ pointer_type.ffi_value_class }}(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - {{ pointer_type.ffi_value_class }}(const {{ pointer_type.ffi_value_class }}&) = delete; - {{ pointer_type.ffi_value_class }}& operator=(const {{ pointer_type.ffi_value_class }}&) = delete; - - {{ pointer_type.ffi_value_class }}& operator=({{ pointer_type.ffi_value_class }}&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&{{ pointer_type.name }})) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &{{ pointer_type.name }}); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static {{ pointer_type.ffi_value_class }} FromRust(void* aValue) { - return {{ pointer_type.ffi_value_class }}(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - ({{ pointer_type.free_fn }})(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~{{ pointer_type.ffi_value_class }}() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; - -{%- endfor %} -{{ preprocessor_condition_end }} -{%- endfor %} - -// Callback interface method handlers, vtables, etc. -{%- for (preprocessor_condition, callback_interfaces, preprocessor_condition_end) in all_callback_interfaces.iter() %} -{{ preprocessor_condition }} - -{%- for cbi in callback_interfaces %} -static StaticRefPtr {{ cbi.js_handler_var }}; - -{%- for handler in cbi.vtable.method_handlers %} -{%- let method_index = loop.index0 %} - -class {{ handler.class_name }} : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - {%- for a in handler.arguments %} - {{ a.ffi_value_class }} {{ a.name }}{}; - {%- endfor %} - -public: - {{ handler.class_name }}(size_t aObjectHandle{%- for a in handler.arguments %}, {{ a.ffi_type }} {{ a.name }}{%- endfor %}) - : UniffiCallbackMethodHandlerBase("{{ cbi.name }}", aObjectHandle) - {%- for a in handler.arguments %}, {{ a.name }}({{ a.ffi_value_class }}::FromRust({{ a.name }})){% endfor %} { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - - {%- if !handler.arguments.is_empty() %} - // Setup - if (!uniffiArgs.AppendElements({{ handler.arguments.len() }}, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; - } - - // Convert each argument - {%- for a in handler.arguments %} - {{ a.name }}.Lift( - aCx, - &uniffiArgs[{{ loop.index0 }}], - aError); - if (aError.Failed()) { - return; - } - {%- endfor %} - {%- endif %} - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, {{ method_index }}, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void {{ handler.fn_name }}( - uint64_t uniffiHandle, - {% for a in handler.arguments %}{{ a.ffi_type }} {{ a.name }}, {% endfor %} - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique<{{ handler.class_name }}>(uniffiHandle{% for a in handler.arguments %}, {{ a.name }}{%- endfor %}); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &{{ cbi.js_handler_var }}); -} - -{%- endfor %} - -extern "C" void {{ cbi.free_fn }}(uint64_t uniffiHandle) { - // Callback object handles are keys in a map stored in the JS handler. To - // handle the free call, make a call into JS which will remove the key. - // Fire-and-forget is perfect for this. - UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("{{ cbi.name }}", uniffiHandle), &{{ cbi.js_handler_var }}); -} - - -static {{ cbi.vtable.type_ }} {{ cbi.vtable.var_name }} { - {%- for handler in cbi.vtable.method_handlers %} - {{ handler.fn_name }}, - {%- endfor %} - {{ cbi.free_fn }} -}; - -{%- endfor %} -{{ preprocessor_condition_end }} -{%- endfor %} - -void RegisterCallbackHandler(uint64_t aInterfaceId, UniFFICallbackHandler& aCallbackHandler, ErrorResult& aError) { - switch (aInterfaceId) { - {%- for (preprocessor_condition, callback_interfaces, preprocessor_condition_end) in all_callback_interfaces.iter() %} - {{ preprocessor_condition }} - - {%- for cbi in callback_interfaces %} - case {{ cbi.id }}: { - if ({{ cbi.js_handler_var }}) { - aError.ThrowUnknownError("[UniFFI] Callback handler already registered for {{ cbi.name }}"_ns); - return; - } - - {{ cbi.js_handler_var }} = &aCallbackHandler; - {{ cbi.init_fn }}(&{{ cbi.vtable.var_name }}); - break; - } - - - {%- endfor %} - {{ preprocessor_condition_end }} - {%- endfor %} - - default: - aError.ThrowUnknownError(nsPrintfCString("Unknown interface id: %" PRIu64, aInterfaceId)); - return; - } -} - -void DeregisterCallbackHandler(uint64_t aInterfaceId, ErrorResult& aError) { - switch (aInterfaceId) { - {%- for (preprocessor_condition, callback_interfaces, preprocessor_condition_end) in all_callback_interfaces.iter() %} - {{ preprocessor_condition }} - - {%- for cbi in callback_interfaces %} - case {{ cbi.id }}: { - if (!{{ cbi.js_handler_var }}) { - aError.ThrowUnknownError("[UniFFI] Callback handler not registered for {{ cbi.name }}"_ns); - return; - } - - {{ cbi.js_handler_var }} = nullptr; - break; - } - - - {%- endfor %} - {{ preprocessor_condition_end }} - {%- endfor %} - - default: - aError.ThrowUnknownError(nsPrintfCString("Unknown interface id: %" PRIu64, aInterfaceId)); - return; - } -} - - -// Define scaffolding call classes for each combination of return/argument types -{%- for (preprocessor_condition, scaffolding_calls, preprocessor_condition_end) in all_scaffolding_calls.iter() %} -{{ preprocessor_condition }} -{%- for scaffolding_call in scaffolding_calls %} -{%- match scaffolding_call.async_info %} -{%- when None %} -class {{ scaffolding_call.handler_class_name }} : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - {%- for arg in scaffolding_call.arguments %} - {{ arg.ffi_value_class }} {{ arg.var_name }}{}; - {%- endfor %} - - // MakeRustCall stores the result of the call in these fields - {%- match scaffolding_call.return_type %} - {%- when Some(return_type) %} - {{ return_type.ffi_value_class }} mUniffiReturnValue{}; - {%- else %} - {%- endmatch %} - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - {%- for arg in scaffolding_call.arguments %} - {{ arg.var_name }}.Lower(aArgs[{{ loop.index0 }}], aError); - if (aError.Failed()) { - return; - } - {%- endfor %} - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - {%- match scaffolding_call.return_type %} - {%- when Some(return_type) %} - mUniffiReturnValue = {{ return_type.ffi_value_class }}::FromRust( - {{ scaffolding_call.ffi_func_name }}( - {%- for arg in scaffolding_call.arguments %} - {{ arg.var_name }}.IntoRust(), - {%- endfor %} - aOutStatus - ) - ); - {%- else %} - {{ scaffolding_call.ffi_func_name }}( - {%- for arg in scaffolding_call.arguments %} - {{ arg.var_name }}.IntoRust(), - {%- endfor %} - aOutStatus - ); - {%- endmatch %} - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - {%- match scaffolding_call.return_type %} - {%- when Some(return_type) %} - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - {%- else %} - {%- endmatch %} - } -}; -{%- when Some(async_info) %} -class {{ scaffolding_call.handler_class_name }} : public UniffiAsyncCallHandler { -public: - {{ scaffolding_call.handler_class_name }}() : UniffiAsyncCallHandler({{ async_info.poll_fn }}, {{ async_info.free_fn }}) { } - -private: - // Complete stores the result of the call in mUniffiReturnValue - {%- match scaffolding_call.return_type %} - {%- when Some(return_type) %} - {{ return_type.ffi_value_class }} mUniffiReturnValue{}; - {%- else %} - {%- endmatch %} - -protected: - // Convert a sequence of JS arguments and call the scaffolding function. - // Always called on the main thread since async Rust calls don't block, they - // return a future. - void LowerArgsAndMakeRustCall(const dom::Sequence& aArgs, ErrorResult& aError) override { - {%- for arg in scaffolding_call.arguments %} - {{ arg.ffi_value_class }} {{ arg.var_name }}{}; - {{ arg.var_name }}.Lower(aArgs[{{ loop.index0 }}], aError); - if (aError.Failed()) { - return; - } - {%- endfor %} - - mFutureHandle = {{ scaffolding_call.ffi_func_name }}( - {%- for arg in scaffolding_call.arguments %} - {{ arg.var_name }}.IntoRust(){% if !loop.last %},{% endif %} - {%- endfor %} - ); - } - - void CallCompleteFn(RustCallStatus* aOutStatus) override { - {%- match scaffolding_call.return_type %} - {%- when Some(return_type) %} - mUniffiReturnValue = {{ return_type.ffi_value_class }}::FromRust( - {{ async_info.complete_fn }}(mFutureHandle, aOutStatus)); - {%- else %} - {{ async_info.complete_fn }}(mFutureHandle, aOutStatus); - {%- endmatch %} - } - -public: - void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - {%- match scaffolding_call.return_type %} - {%- when Some(return_type) %} - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - {%- else %} - {%- endmatch %} - } -}; -{%- endmatch %} - -{%- endfor %} -{{ preprocessor_condition_end }} -{%- endfor %} - -UniquePtr GetSyncCallHandler(uint64_t aId) { - switch (aId) { - {%- for (preprocessor_condition, scaffolding_calls, preprocessor_condition_end) in all_scaffolding_calls.iter() %} -{{ preprocessor_condition }} - {%- for call in scaffolding_calls %} - {%- if !call.is_async() %} - case {{ call.function_id }}: { - return MakeUnique<{{ call.handler_class_name }}>(); - } - {%- endif %} - {%- endfor %} -{{ preprocessor_condition_end }} - {%- endfor %} - - default: - return nullptr; - } -} - -UniquePtr GetAsyncCallHandler(uint64_t aId) { - switch (aId) { - {%- for (preprocessor_condition, scaffolding_calls, preprocessor_condition_end) in all_scaffolding_calls.iter() %} -{{ preprocessor_condition }} - {%- for call in scaffolding_calls %} - {%- if call.is_async() %} - case {{ call.function_id }}: { - return MakeUnique<{{ call.handler_class_name }}>(); - } - {%- endif %} - {%- endfor %} -{{ preprocessor_condition_end }} - {%- endfor %} - - default: - return nullptr; - } -} - - -Maybe> ReadPointer(const GlobalObject& aGlobal, uint64_t aId, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { - const UniFFIPointerType* type; - switch (aId) { - {%- for (preprocessor_condition, pointer_types, preprocessor_condition_end) in all_pointer_types.iter() %} -{{ preprocessor_condition }} - {%- for pointer_type in pointer_types %} - case {{ pointer_type.object_id }}: { - type = &{{ pointer_type.name }}; - break; - } - {%- endfor %} -{{ preprocessor_condition_end }} - {%- endfor %} - default: - return Nothing(); - } - return Some(UniFFIPointer::Read(aArrayBuff, aPosition, type, aError)); -} - -bool WritePointer(const GlobalObject& aGlobal, uint64_t aId, const UniFFIPointer& aPtr, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { - const UniFFIPointerType* type; - switch (aId) { - {%- for (preprocessor_condition, pointer_types, preprocessor_condition_end) in all_pointer_types.iter() %} -{{ preprocessor_condition }} - {%- for pointer_type in pointer_types %} - case {{ pointer_type.object_id }}: { - type = &{{ pointer_type.name }}; - break; - } - {%- endfor %} -{{ preprocessor_condition_end }} - {%- endfor %} - default: - return false; - } - aPtr.Write(aArrayBuff, aPosition, type, aError); - return true; -} - -} // namespace mozilla::uniffi diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/api-doc.md b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/api-doc.md index 40440537c4ba..e6fd7cc8faa5 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/api-doc.md +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/api-doc.md @@ -1,12 +1,12 @@ # {{ module_name }} -{% for class in classes -%} +{%- for class in classes %} ```{js:autoclass} {{ jsdoc_module_name }}.{{ class }} :members: :exclude-members: {{ class }} ``` -{% endfor -%} -{% for function in functions -%} +{%- endfor %} +{%- for function in functions %} ```{js:autofunction} {{ jsdoc_module_name }}.{{ function }} ``` -{% endfor -%} +{%- endfor %} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/CallbackInterfaces.cpp b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/CallbackInterfaces.cpp new file mode 100644 index 000000000000..b74274bf0fdd --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/CallbackInterfaces.cpp @@ -0,0 +1,155 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +// Callback interface method handlers, vtables, etc. +{%- for (preprocessor_condition, callback_interfaces, preprocessor_condition_end) in callback_interfaces.iter() %} +{{ preprocessor_condition }} + +{%- for cbi in callback_interfaces %} +static StaticRefPtr {{ cbi.handler_var }}; + +{%- for meth in cbi.methods %} +{%- let method_index = loop.index0 %} +{%- let arguments = meth.arguments %} + +class {{ meth.handler_class_name }} : public UniffiCallbackMethodHandlerBase { +private: + // Rust arguments + {%- for a in arguments %} + {{ a.ffi_value_class }} {{ a.field_name }}{}; + {%- endfor %} + +public: + {{ meth.handler_class_name }}(uint64_t aUniffiHandle{%- for a in arguments %}, {{ a.ty.type_name }} {{ a.name }}{%- endfor %}) + : UniffiCallbackMethodHandlerBase("{{ cbi.name }}", aUniffiHandle) + {%- for a in arguments %}, {{ a.field_name }}({{ a.ffi_value_class }}::FromRust({{ a.name }})){% endfor %} { + } + + MOZ_CAN_RUN_SCRIPT + void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { + nsTArray uniffiArgs; + + // Setup + if (!uniffiArgs.AppendElements({{ arguments.len() + 1 }}, mozilla::fallible)) { + aError.Throw(NS_ERROR_OUT_OF_MEMORY); + return; + } + + // Convert each argument + mUniffiHandle.Lift( + aCx, + &uniffiArgs[0], + aError); + if (aError.Failed()) { + return; + } + {%- for a in arguments %} + {{ a.field_name }}.Lift( + aCx, + &uniffiArgs[{{ loop.index }}], + aError); + if (aError.Failed()) { + return; + } + {%- endfor %} + + // Stores the return value. For now, we currently don't do anything with it, since we only support + // fire-and-forget callbacks. + NullableRootedUnion returnValue(aCx); + // Make the call + aJsHandler->Call(mUniffiHandle.IntoRust(), {{ method_index }}, uniffiArgs, returnValue, aError); + } +}; + +extern "C" void {{ meth.fn_name }}( + uint64_t aUniffiHandle, + {%- for a in meth.arguments %} + {{ a.ty.type_name }} {{ a.name }}, + {%- endfor %} + {{ meth.out_pointer_ty.type_name }} aUniffiOutReturn, + RustCallStatus* uniffiOutStatus +) { + UniquePtr handler = MakeUnique<{{ meth.handler_class_name }}>(aUniffiHandle{% for a in arguments %}, {{ a.name }}{%- endfor %}); + // Note: currently we only support queueing fire-and-forget async callbacks + + // For fire-and-forget callbacks, we don't know if the method succeeds or not + // since it's called later. uniffiCallStatus is initialized to a successful + // state by the Rust code, so there's no need to modify it. + UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &{{ cbi.handler_var }}); +} + +{%- endfor %} + +extern "C" void {{ cbi.free_fn }}(uint64_t uniffiHandle) { + // Callback object handles are keys in a map stored in the JS handler. To + // handle the free call, make a call into JS which will remove the key. + // Fire-and-forget is perfect for this. + UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("{{ cbi.name }}", uniffiHandle), &{{ cbi.handler_var }}); +} + +static {{ cbi.vtable_struct_type.type_name }} {{ cbi.vtable_var }} { + {%- for meth in cbi.methods %} + {{ meth.fn_name }}, + {%- endfor %} + {{ cbi.free_fn }} +}; + +{%- endfor %} +{{ preprocessor_condition_end }} +{%- endfor %} + +void RegisterCallbackHandler(uint64_t aInterfaceId, UniFFICallbackHandler& aCallbackHandler, ErrorResult& aError) { + switch (aInterfaceId) { + {%- for (preprocessor_condition, callback_interfaces, preprocessor_condition_end) in callback_interfaces.iter() %} + {{ preprocessor_condition }} + + {%- for cbi in callback_interfaces %} + case {{ cbi.id }}: { + if ({{ cbi.handler_var }}) { + aError.ThrowUnknownError("[UniFFI] Callback handler already registered for {{ cbi.name }}"_ns); + return; + } + + {{ cbi.handler_var }} = &aCallbackHandler; + {{ cbi.init_fn.0 }}(&{{ cbi.vtable_var }}); + break; + } + + + {%- endfor %} + {{ preprocessor_condition_end }} + {%- endfor %} + + default: + aError.ThrowUnknownError(nsPrintfCString("RegisterCallbackHandler: Unknown callback interface id (%" PRIu64 ")", aInterfaceId)); + return; + } +} + +void DeregisterCallbackHandler(uint64_t aInterfaceId, ErrorResult& aError) { + switch (aInterfaceId) { + {%- for (preprocessor_condition, callback_interfaces, preprocessor_condition_end) in callback_interfaces.iter() %} + {{ preprocessor_condition }} + + {%- for cbi in callback_interfaces %} + case {{ cbi.id }}: { + if (!{{ cbi.handler_var }}) { + aError.ThrowUnknownError("[UniFFI] Callback handler not registered for {{ cbi.name }}"_ns); + return; + } + + {{ cbi.handler_var }} = nullptr; + break; + } + + + {%- endfor %} + {{ preprocessor_condition_end }} + {%- endfor %} + + default: + aError.ThrowUnknownError(nsPrintfCString("DeregisterCallbackHandler: Unknown callback interface id (%" PRIu64 ")", aInterfaceId)); + return; + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/FfiDefinitions.cpp b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/FfiDefinitions.cpp new file mode 100644 index 000000000000..159eae331d59 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/FfiDefinitions.cpp @@ -0,0 +1,24 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +extern "C" { + {%- for (preprocessor_condition, ffi_definitions, preprocessor_condition_end) in ffi_definitions.iter() %} +{{ preprocessor_condition }} + {%- for def in ffi_definitions %} + {%- match def %} + {%- when FfiDefinition::RustFunction(func) %} + {{ func.return_type.type_name }} {{ func.name.0 }}({{ func.arg_types()|join(", ") }}); + {%- when FfiDefinition::FunctionType(func) %} + typedef {{ func.return_type.type_name }} (*{{ func.name.0 }})({{ func.arg_types()|join(", ") }}); + {%- when FfiDefinition::Struct(ffi_struct) %} + struct {{ ffi_struct.name.0 }} { + {%- for field in ffi_struct.fields %} + {{ field.ty.type_name }} {{ field.name }}; + {%- endfor %} + }; + {%- endmatch %} + {%- endfor %} +{{ preprocessor_condition_end }} + {%- endfor %} +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/PointerTypes.cpp b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/PointerTypes.cpp new file mode 100644 index 000000000000..d65530d8f4f1 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/PointerTypes.cpp @@ -0,0 +1,124 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +// Define pointer types +{%- for (preprocessor_condition, pointer_types, preprocessor_condition_end) in pointer_types.iter() %} +{{ preprocessor_condition }} +{%- for pointer_type in pointer_types %} +const static mozilla::uniffi::UniFFIPointerType {{ pointer_type.name }} { + "{{ pointer_type.label }}"_ns, + {{ pointer_type.ffi_func_clone.0 }}, + {{ pointer_type.ffi_func_free.0 }}, +}; + +class {{ pointer_type.ffi_value_class }} { + private: + void* mValue = nullptr; + + public: + {{ pointer_type.ffi_value_class }}() = default; + explicit {{ pointer_type.ffi_value_class }}(void* aValue) : mValue(aValue) {} + + // Delete copy constructor and assignment as this type is non-copyable. + {{ pointer_type.ffi_value_class }}(const {{ pointer_type.ffi_value_class }}&) = delete; + {{ pointer_type.ffi_value_class }}& operator=(const {{ pointer_type.ffi_value_class }}&) = delete; + + {{ pointer_type.ffi_value_class }}& operator=({{ pointer_type.ffi_value_class }}&& aOther) { + FreeHandle(); + mValue = aOther.mValue; + aOther.mValue = nullptr; + return *this; + } + + void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, + ErrorResult& aError) { + if (!aValue.IsUniFFIPointer()) { + aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); + return; + } + dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); + if (!value.IsSamePtrType(&{{ pointer_type.name }})) { + aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); + return; + } + FreeHandle(); + mValue = value.ClonePtr(); + } + + void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, + ErrorResult& aError) { + aDest->SetAsUniFFIPointer() = + dom::UniFFIPointer::Create(mValue, &{{ pointer_type.name }}); + mValue = nullptr; + } + + void* IntoRust() { + auto temp = mValue; + mValue = nullptr; + return temp; + } + + static {{ pointer_type.ffi_value_class }} FromRust(void* aValue) { + return {{ pointer_type.ffi_value_class }}(aValue); + } + + void FreeHandle() { + if (mValue) { + RustCallStatus callStatus{}; + ({{ pointer_type.ffi_func_free.0 }})(mValue, &callStatus); + // No need to check `RustCallStatus`, it's only part of the API to match + // other FFI calls. The free function can never fail. + } + } + + ~{{ pointer_type.ffi_value_class }}() { + // If the pointer is non-null, this means Lift/IntoRust was never called + // because there was some failure along the way. Free the pointer to avoid a + // leak + FreeHandle(); + } +}; + +{%- endfor %} +{{ preprocessor_condition_end }} +{%- endfor %} + +Maybe> ReadPointer(const GlobalObject& aGlobal, uint64_t aId, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { + const UniFFIPointerType* type; + switch (aId) { + {%- for (preprocessor_condition, pointer_types, preprocessor_condition_end) in pointer_types.iter() %} +{{ preprocessor_condition }} + {%- for pointer_type in pointer_types %} + case {{ pointer_type.id }}: { + type = &{{ pointer_type.name }}; + break; + } + {%- endfor %} +{{ preprocessor_condition_end }} + {%- endfor %} + default: + return Nothing(); + } + return Some(UniFFIPointer::Read(aArrayBuff, aPosition, type, aError)); +} + +bool WritePointer(const GlobalObject& aGlobal, uint64_t aId, const UniFFIPointer& aPtr, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { + const UniFFIPointerType* type; + switch (aId) { + {%- for (preprocessor_condition, pointer_types, preprocessor_condition_end) in pointer_types.iter() %} +{{ preprocessor_condition }} + {%- for pointer_type in pointer_types %} + case {{ pointer_type.id }}: { + type = &{{ pointer_type.name }}; + break; + } + {%- endfor %} +{{ preprocessor_condition_end }} + {%- endfor %} + default: + return false; + } + aPtr.Write(aArrayBuff, aPosition, type, aError); + return true; +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/ScaffoldingCalls.cpp b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/ScaffoldingCalls.cpp new file mode 100644 index 000000000000..0ce2554a8752 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/ScaffoldingCalls.cpp @@ -0,0 +1,161 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +// Define scaffolding call classes for each combination of return/argument types +{%- for (preprocessor_condition, scaffolding_calls, preprocessor_condition_end) in scaffolding_calls.iter() %} +{{ preprocessor_condition }} +{%- for scaffolding_call in scaffolding_calls %} +{%- match scaffolding_call.ffi_func.async_data %} +{%- when None %} +class {{ scaffolding_call.handler_class_name }} : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + {%- for arg in scaffolding_call.arguments %} + {{ arg.ffi_value_class }} {{ arg.field_name }}{}; + {%- endfor %} + + // MakeRustCall stores the result of the call in these fields + {%- if let Some(return_ty) = scaffolding_call.return_ty %} + {{ return_ty.ffi_value_class }} mUniffiReturnValue{}; + {%- endif %} + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + {%- for arg in scaffolding_call.arguments %} + {{ arg.field_name }}.Lower(aArgs[{{ loop.index0 }}], aError); + if (aError.Failed()) { + return; + } + {%- endfor %} + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + {%- match scaffolding_call.return_ty %} + {%- when Some(return_ty) %} + mUniffiReturnValue = {{ return_ty.ffi_value_class }}::FromRust( + {{ scaffolding_call.ffi_func.name.0 }}( + {%- for arg in scaffolding_call.arguments %} + {{ arg.field_name }}.IntoRust(), + {%- endfor %} + aOutStatus + ) + ); + {%- else %} + {{ scaffolding_call.ffi_func.name.0 }}( + {%- for arg in scaffolding_call.arguments %} + {{ arg.field_name }}.IntoRust(), + {%- endfor %} + aOutStatus + ); + {%- endmatch %} + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + {%- if scaffolding_call.return_ty.is_some() %} + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + {%- endif %} + } +}; +{%- when Some(async_data) %} +class {{ scaffolding_call.handler_class_name }} : public UniffiAsyncCallHandler { +public: + {{ scaffolding_call.handler_class_name }}() : UniffiAsyncCallHandler( + {{ async_data.ffi_rust_future_poll.0 }}, + {{ async_data.ffi_rust_future_free.0 }} + ) { } + +private: + // Complete stores the result of the call in mUniffiReturnValue + {%- if let Some(return_ty) = scaffolding_call.return_ty %} + {{ return_ty.ffi_value_class }} mUniffiReturnValue{}; + {%- endif %} + +protected: + // Convert a sequence of JS arguments and call the scaffolding function. + // Always called on the main thread since async Rust calls don't block, they + // return a future. + void LowerArgsAndMakeRustCall(const dom::Sequence& aArgs, ErrorResult& aError) override { + {%- for arg in scaffolding_call.arguments %} + {{ arg.ffi_value_class }} {{ arg.field_name }}{}; + {{ arg.field_name }}.Lower(aArgs[{{ loop.index0 }}], aError); + if (aError.Failed()) { + return; + } + {%- endfor %} + + mFutureHandle = {{ scaffolding_call.ffi_func.name.0 }}( + {%- for arg in scaffolding_call.arguments %} + {{ arg.field_name }}.IntoRust(){% if !loop.last %},{% endif %} + {%- endfor %} + ); + } + + void CallCompleteFn(RustCallStatus* aOutStatus) override { + {%- match scaffolding_call.return_ty %} + {%- when Some(return_ty) %} + mUniffiReturnValue = {{ return_ty.ffi_value_class }}::FromRust( + {{ async_data.ffi_rust_future_complete.0 }}(mFutureHandle, aOutStatus)); + {%- else %} + {{ async_data.ffi_rust_future_complete.0 }}(mFutureHandle, aOutStatus); + {%- endmatch %} + } + +public: + void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + {%- if scaffolding_call.return_ty.is_some() %} + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + {%- endif %} + } +}; +{%- endmatch %} + +{%- endfor %} +{{ preprocessor_condition_end }} +{%- endfor %} + +UniquePtr GetSyncCallHandler(uint64_t aId) { + switch (aId) { + {%- for (preprocessor_condition, scaffolding_calls, preprocessor_condition_end) in scaffolding_calls.iter() %} +{{ preprocessor_condition }} + {%- for call in scaffolding_calls %} + {%- if !call.is_async() %} + case {{ call.id }}: { + return MakeUnique<{{ call.handler_class_name }}>(); + } + {%- endif %} + {%- endfor %} +{{ preprocessor_condition_end }} + {%- endfor %} + + default: + return nullptr; + } +} + +UniquePtr GetAsyncCallHandler(uint64_t aId) { + switch (aId) { + {%- for (preprocessor_condition, scaffolding_calls, preprocessor_condition_end) in scaffolding_calls.iter() %} +{{ preprocessor_condition }} + {%- for call in scaffolding_calls %} + {%- if call.is_async() %} + case {{ call.id }}: { + return MakeUnique<{{ call.handler_class_name }}>(); + } + {%- endif %} + {%- endfor %} +{{ preprocessor_condition_end }} + {%- endfor %} + + default: + return nullptr; + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/UniFFIScaffolding.cpp b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/UniFFIScaffolding.cpp new file mode 100644 index 000000000000..e3ad142921b3 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/cpp/UniFFIScaffolding.cpp @@ -0,0 +1,39 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ + +// Generated by uniffi-bindgen-gecko-js. DO NOT EDIT. + +#include "nsString.h" +#include "nsPrintfCString.h" +#include "mozilla/Logging.h" +#include "mozilla/Maybe.h" +#include "mozilla/StaticPtr.h" +#include "mozilla/UniquePtr.h" +#include "mozilla/dom/Promise.h" +#include "mozilla/dom/UniFFIScaffolding.h" +#include "mozilla/uniffi/Call.h" +#include "mozilla/uniffi/Callbacks.h" +#include "mozilla/uniffi/FfiValue.h" +#include "mozilla/uniffi/PointerType.h" +#include "mozilla/uniffi/Rust.h" + +namespace mozilla::uniffi { + +using dom::ArrayBuffer; +using dom::AutoEntryScript; +using dom::GlobalObject; +using dom::RootedDictionary; +using dom::NullableRootedUnion; +using dom::Promise; +using dom::Sequence; +using dom::UniFFICallbackHandler; +using dom::UniFFIPointer; +using dom::UniFFIScaffoldingCallResult; + + +{% include "cpp/FfiDefinitions.cpp" %} +{% include "cpp/PointerTypes.cpp" %} +{% include "cpp/ScaffoldingCalls.cpp" %} +{% include "cpp/CallbackInterfaces.cpp" %} + +} // namespace mozilla::uniffi diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallableArgs.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallableArgs.sys.mjs new file mode 100644 index 000000000000..21511df54132 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallableArgs.sys.mjs @@ -0,0 +1,4 @@ +{%- for arg in callable.arguments %} +{{ arg.name }}{% if let Some(lit) = arg.default %} = {{ lit.js_lit }}{% endif %} +{%- if !loop.last %}, {% endif %} +{%- endfor -%} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallableBody.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallableBody.sys.mjs new file mode 100644 index 000000000000..a18b4c908c11 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallableBody.sys.mjs @@ -0,0 +1,29 @@ +{%- for arg in callable.arguments %} +{{ arg|check_type_fn }}({{ arg.name }}); +{%- endfor %} +const result = {% if callable.is_js_async %}await {% endif %}{{ callable.uniffi_scaffolding_method }}( + {{ callable.id }}, // {{ callable.ffi_func.0 }} + {%- if let CallableKind::Method { ffi_converter, .. } = callable.kind %} + {{ ffi_converter }}.lower(this), + {%- endif %} + {%- for arg in callable.arguments %} + {{ arg|lower_fn }}({{ arg.name }}), + {%- endfor %} +) +return handleRustResult( + result, + + {%- match callable.return_type.ty %} + {%- when Some(return_type) %} + {{ return_type|lift_fn }}.bind({{ return_type|ffi_converter }}), + {%- when None %} + (result) => undefined, + {%- endmatch %} + + {%- match callable.throws_type.ty %} + {%- when Some(err_type) %} + {{ err_type|lift_fn }}.bind({{ err_type|ffi_converter }}), + {%- when None %} + null, + {%- endmatch %} +) diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterface.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterface.sys.mjs index 0b24cbbe0b5e..2edae039dc64 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterface.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterface.sys.mjs @@ -1,13 +1,11 @@ -{%- let cbi = ci.get_callback_interface_definition(name).unwrap() %} -{#- See CallbackInterfaceRuntime.sys.mjs and CallbackInterfaceHandler.sys.mjs for the callback interface handler definition, referenced here as `{{ cbi.handler() }}` #} // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverter { +export class {{ cbi|ffi_converter }} extends FfiConverter { static lower(callbackObj) { - return {{ cbi.handler() }}.storeCallbackObj(callbackObj) + return {{ cbi.js_handler_var }}.storeCallbackObj(callbackObj) } static lift(handleId) { - return {{ cbi.handler() }}.getCallbackObj(handleId) + return {{ cbi.js_handler_var }}.getCallbackObj(handleId) } static read(dataStream) { @@ -22,3 +20,23 @@ export class {{ ffi_converter }} extends FfiConverter { return 8; } } + +const {{ cbi.js_handler_var }} = new UniFFICallbackHandler( + "{{ cbi.name }}", + {{ cbi.id }}, + [ + {%- for vtable_method in cbi.vtable.methods %} + new UniFFICallbackMethodHandler( + "{{ vtable_method.callable.name }}", + [ + {%- for arg in vtable_method.callable.arguments %} + {{ arg|ffi_converter }}, + {%- endfor %} + ], + ), + {%- endfor %} + ] +); + +// Allow the shutdown-related functionality to be tested in the unit tests +UnitTestObjs.{{ cbi.js_handler_var }} = {{ cbi.js_handler_var }}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterfaceHandler.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterfaceHandler.sys.mjs deleted file mode 100644 index a7e7ac8e2a52..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CallbackInterfaceHandler.sys.mjs +++ /dev/null @@ -1,19 +0,0 @@ -const {{ cbi.handler() }} = new UniFFICallbackHandler( - "{{ callback_ids.name(ci, cbi) }}", - {{ callback_ids.get(ci, cbi) }}, - [ - {%- for method in cbi.methods() %} - new UniFFICallbackMethodHandler( - "{{ method.js_name() }}", - [ - {%- for arg in method.arguments() %} - {{ arg.ffi_converter() }}, - {%- endfor %} - ], - ), - {%- endfor %} - ] -); - -// Allow the shutdown-related functionality to be tested in the unit tests -UnitTestObjs.{{ cbi.handler() }} = {{ cbi.handler() }}; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CustomType.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CustomType.sys.mjs index 4ce4dc31af8c..81cd2a6a503e 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CustomType.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/CustomType.sys.mjs @@ -1,23 +1,24 @@ // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverter { +export class {{ custom|ffi_converter }} extends FfiConverter { static lift(buf) { - return {{ builtin.ffi_converter() }}.lift(buf); + return {{ custom.builtin|lift_fn }}(buf); } static lower(buf) { - return {{ builtin.ffi_converter() }}.lower(buf); + return {{ custom.builtin|lower_fn }}(buf); } static write(dataStream, value) { - {{ builtin.ffi_converter() }}.write(dataStream, value); + {{ custom.builtin|write_fn }}(dataStream, value); } static read(buf) { - return {{ builtin.ffi_converter() }}.read(buf); + return {{ custom.builtin|read_fn }}(buf); } static computeSize(value) { - return {{ builtin.ffi_converter() }}.computeSize(value); + return {{ custom.builtin|compute_size_fn }}(value); } } + // TODO: We should also allow JS to customize the type eventually. diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Enum.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Enum.sys.mjs index c1ad654c5a2c..cc82be7fb16f 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Enum.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Enum.sys.mjs @@ -1,38 +1,35 @@ -{%- if enum_.is_flat() -%} +{%- if enum_.is_flat -%} -{{ enum_.js_docstring(0) -}} -export const {{ enum_.js_name() }} = { - {%- for variant in enum_.variants() %} - {{ variant.js_docstring(true, 4) -}} - {{ variant.js_name(true) }}:{% match enum_.variant_discriminant(loop.index0) %}{% when Ok with (value) %}{{ value }}{% when Err with (err) %}{{ loop.index0 }}{% endmatch %}, +{{ enum_.js_docstring }} +export const {{ enum_.name }} = { + {%- for variant in enum_.variants %} + {{ variant.js_docstring|indent(4) }} + {{ variant.name }}: {{loop.index}}, {%- endfor %} }; +Object.freeze({{ enum_.name }}); -Object.freeze({{ enum_.js_name() }}); // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { - static #validValues = Object.values({{ enum_.js_name() }}); - +export class {{ enum_|ffi_converter }} extends FfiConverterArrayBuffer { static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { - {%- for variant in enum_.variants() %} + {%- for variant in enum_.variants %} case {{ loop.index }}: - return {{ enum_.js_name() }}.{{ variant.js_name(true) }} + return {{ enum_.name }}.{{ variant.name }} {%- endfor %} default: - throw new UniFFITypeError("Unknown {{ enum_.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ enum_.name }} variant"); } } static write(dataStream, value) { - {%- for variant in enum_.variants() %} - if (value === {{ enum_.js_name() }}.{{ variant.js_name(true) }}) { + {%- for variant in enum_.variants %} + if (value === {{ enum_.name }}.{{ variant.name }}) { dataStream.writeInt32({{ loop.index }}); return; } {%- endfor %} - throw new UniFFITypeError("Unknown {{ enum_.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ enum_.name }} variant"); } static computeSize(value) { @@ -40,82 +37,80 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { } static checkType(value) { - // Check that the value is a valid enum variant - if (!this.#validValues.includes(value)) { - throw new UniFFITypeError(`${value} is not a valid value for {{ enum_.js_name() }}`); + if (!Number.isInteger(value) || value < 1 || value > {{ enum_.variants.len() }}) { + throw new UniFFITypeError(`${value} is not a valid value for {{ enum_.name }}`); } } } {%- else -%} -{{ enum_.js_docstring(0) -}} -export class {{ enum_.js_name() }} {} +{{ enum_.js_docstring }} +export class {{ enum_.name }} {} -{%- for variant in enum_.variants() %} -{{ variant.js_docstring(false, 0) -}} -{{enum_.js_name()}}.{{ variant.js_name(false) }} = class extends {{ enum_.js_name() }}{ +{%- for variant in enum_.variants %} +{{ variant.js_docstring }} +{{enum_.name }}.{{ variant.name }} = class extends {{ enum_.name }}{ constructor( - {% for field in variant.fields() -%} - {{ field.js_name() }}{%- if loop.last %}{%- else %}, {%- endif %} + {% for field in variant.fields -%} + {{ field.name }}{%- if loop.last %}{%- else %}, {%- endif %} {% endfor -%} ) { super(); - {%- for field in variant.fields() %} - this.{{field.js_name()}} = {{ field.js_name() }}; + {%- for field in variant.fields %} + this.{{ field.name }} = {{ field.name }}; {%- endfor %} } } {%- endfor %} // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { +export class {{ enum_|ffi_converter }} extends FfiConverterArrayBuffer { static read(dataStream) { - // Use sequential indices (1-based) for the wire format to match Python bindings switch (dataStream.readInt32()) { - {%- for variant in enum_.variants() %} + {%- for variant in enum_.variants %} case {{ loop.index }}: - return new {{ enum_.js_name() }}.{{ variant.js_name(false) }}( - {%- for field in variant.fields() %} - {{ field.ffi_converter() }}.read(dataStream){%- if loop.last %}{% else %}, {%- endif %} + return new {{ enum_.name }}.{{ variant.name }}( + {%- for field in variant.fields %} + {{ field|read_fn }}(dataStream){%- if loop.last %}{% else %}, {%- endif %} {%- endfor %} ); {%- endfor %} default: - throw new UniFFITypeError("Unknown {{ enum_.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ enum_.name }} variant"); } } static write(dataStream, value) { - {%- for variant in enum_.variants() %} - if (value instanceof {{enum_.js_name()}}.{{ variant.js_name(false) }}) { + {%- for variant in enum_.variants %} + if (value instanceof {{ enum_.name }}.{{ variant.name }}) { dataStream.writeInt32({{ loop.index }}); - {%- for field in variant.fields() %} - {{ field.ffi_converter() }}.write(dataStream, value.{{ field.js_name() }}); + {%- for field in variant.fields %} + {{ field|write_fn }}(dataStream, value.{{ field.name }}); {%- endfor %} return; } {%- endfor %} - throw new UniFFITypeError("Unknown {{ enum_.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ enum_.name }} variant"); } static computeSize(value) { // Size of the Int indicating the variant let totalSize = 4; - {%- for variant in enum_.variants() %} - if (value instanceof {{enum_.js_name()}}.{{ variant.js_name(false) }}) { - {%- for field in variant.fields() %} - totalSize += {{ field.ffi_converter() }}.computeSize(value.{{ field.js_name() }}); + {%- for variant in enum_.variants %} + if (value instanceof {{ enum_.name }}.{{ variant.name }}) { + {%- for field in variant.fields %} + totalSize += {{ field|compute_size_fn }}(value.{{ field.name }}); {%- endfor %} return totalSize; } {%- endfor %} - throw new UniFFITypeError("Unknown {{ enum_.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ enum_.name }} variant"); } static checkType(value) { - if (value === undefined || value === null || !(value instanceof {{ enum_.js_name() }})) { - throw new UniFFITypeError(`${value} is not a subclass instance of {{ enum_.js_name() }}`); + if (!(value instanceof {{ enum_.name }})) { + throw new UniFFITypeError(`${value} is not a subclass instance of {{ enum_.name }}`); } } } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Error.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Error.sys.mjs index 7e0018b14609..9e87e444872c 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Error.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Error.sys.mjs @@ -1,86 +1,83 @@ -{%- let string_type = Type::String %} -{%- let string_ffi_converter = string_type.ffi_converter() %} +{{ error.js_docstring }} +export class {{ error.name }} extends Error {} +{% for variant in error.variants %} -{{ error.js_docstring(0) -}} -export class {{ error.js_name() }} extends Error {} -{% for variant in error.variants() %} - -{{ variant.js_docstring(error.is_flat(), 0) -}} -export class {{ variant.name().to_upper_camel_case() }} extends {{ error.js_name() }} { -{% if error.is_flat() %} +{{ variant.js_docstring }} +export class {{ variant.name }} extends {{ error.name }} { +{% if error.is_flat %} constructor(message, ...params) { super(...params); this.message = message; } {%- else %} constructor( - {% for field in variant.fields() -%} - {{field.js_name()}}, + {% for field in variant.fields -%} + {{ field.name }}, {% endfor -%} ...params ) { - {%- if !variant.fields().is_empty() %} - const message = `{% for field in variant.fields() %}{{ field.js_name() }}: ${ {{ field.js_name() }} }{% if !loop.last %}, {% endif %}{% endfor %}`; + {%- if !variant.fields.is_empty() %} + const message = `{% for field in variant.fields %}{{ field.name }}: ${ {{ field.name }} }{% if !loop.last %}, {% endif %}{% endfor %}`; super(message, ...params); {%- else %} super(...params); {%- endif %} - {%- for field in variant.fields() %} - this.{{field.js_name()}} = {{ field.js_name() }}; + {%- for field in variant.fields %} + this.{{field.name}} = {{ field.name }}; {%- endfor %} } {%- endif %} toString() { - return `{{ variant.name().to_upper_camel_case() }}: ${super.toString()}` + return `{{ variant.name }}: ${super.toString()}` } } {%- endfor %} // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { +export class {{ error|ffi_converter }} extends FfiConverterArrayBuffer { static read(dataStream) { switch (dataStream.readInt32()) { - {%- for variant in error.variants() %} + {%- for variant in error.variants %} case {{ loop.index }}: - {%- if error.is_flat() %} - return new {{ variant.name().to_upper_camel_case() }}({{ string_ffi_converter }}.read(dataStream)); + {%- if error.is_flat %} + return new {{ variant.name }}({{ string_type_node|read_fn }}(dataStream)); {%- else %} - return new {{ variant.name().to_upper_camel_case() }}( - {%- for field in variant.fields() %} - {{ field.ffi_converter() }}.read(dataStream){%- if loop.last %}{% else %}, {%- endif %} + return new {{ variant.name }}( + {%- for field in variant.fields %} + {{ field|read_fn }}(dataStream){%- if loop.last %}{% else %}, {%- endif %} {%- endfor %} ); {%- endif %} {%- endfor %} default: - throw new UniFFITypeError("Unknown {{ error.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ error.name }} variant"); } } static computeSize(value) { // Size of the Int indicating the variant let totalSize = 4; - {%- for variant in error.variants() %} - if (value instanceof {{ variant.name().to_upper_camel_case() }}) { - {%- for field in variant.fields() %} - totalSize += {{ field.ffi_converter() }}.computeSize(value.{{ field.js_name() }}); + {%- for variant in error.variants %} + if (value instanceof {{ variant.name }}) { + {%- for field in variant.fields %} + totalSize += {{ field|compute_size_fn }}(value.{{ field.name }}); {%- endfor %} return totalSize; } {%- endfor %} - throw new UniFFITypeError("Unknown {{ error.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ error.name }} variant"); } static write(dataStream, value) { - {%- for variant in error.variants() %} - if (value instanceof {{ variant.name().to_upper_camel_case() }}) { + {%- for variant in error.variants %} + if (value instanceof {{ variant.name }}) { dataStream.writeInt32({{ loop.index }}); - {%- for field in variant.fields() %} - {{ field.ffi_converter() }}.write(dataStream, value.{{ field.js_name() }}); + {%- for field in variant.fields %} + {{ field|write_fn }}(dataStream, value.{{ field.name }}); {%- endfor %} return; } {%- endfor %} - throw new UniFFITypeError("Unknown {{ error.js_name() }} variant"); + throw new UniFFITypeError("Unknown {{ error.name }} variant"); } - static errorClass = {{ error.js_name() }}; + static errorClass = {{ error.name }}; } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/ExternalType.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/ExternalType.sys.mjs index 4661b23bf649..9205ce0cc024 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/ExternalType.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/ExternalType.sys.mjs @@ -1,7 +1,6 @@ import { - {{ ffi_converter }}, - {{ name }}, -} from "{{ self.external_type_module(module_path) }}"; + {{ external|ffi_converter }}, +} from "./{{ external.module_name }}.sys.mjs"; // Export the FFIConverter object to make external types work. -export { {{ ffi_converter }}, {{ name }} }; +export { {{ external|ffi_converter }} }; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Helpers.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Helpers.sys.mjs index 5714d4abca36..562e9df1717b 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Helpers.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Helpers.sys.mjs @@ -161,27 +161,22 @@ class ArrayBufferDataStream { }) } - {%- for object in ci.object_definitions() %} - - // Reads a {{ object.js_name() }} pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointer{{ object.js_name() }}() { - const pointerId = {{ object_ids.get(ci, object) }}; // {{ object_ids.name(ci, object) }} + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a {{ object.js_name() }} pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointer{{ object.js_name() }}(value) { - const pointerId = {{ object_ids.get(ci, object) }}; // {{ object_ids.name(ci, object) }} + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - {% endfor %} } function handleRustResult(result, liftCallback, liftErrCallback) { diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Interface.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Interface.sys.mjs new file mode 100644 index 000000000000..3c76601dc25f --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Interface.sys.mjs @@ -0,0 +1,62 @@ +{{ int.js_docstring }} +export class {{ int.name }} { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + {%- for cons in int.constructors %} + {%- let callable = cons.callable %} + {{ cons.js_docstring|indent(4) }} + static {% if cons.callable.is_js_async %}async {% endif %}{{ cons.name }}({% filter indent(8) %}{% include "js/CallableArgs.sys.mjs" %}{% endfilter %}) { + {% filter indent(8) %}{% include "js/CallableBody.sys.mjs" %}{% endfilter %} + } + {%- endfor %} + + {%- for meth in int.methods %} + {%- let callable = meth.callable %} + + {{ meth.js_docstring|indent(4) }} + {% if meth.callable.is_js_async %}async {% endif %}{{ meth.name }}({% filter indent(8) %}{% include "js/CallableArgs.sys.mjs" %}{% endfilter %}) { + {% filter indent(8) %}{% include "js/CallableBody.sys.mjs" %}{% endfilter %} + } + {%- endfor %} + +} + +// Export the FFIConverter object to make external types work. +export class {{ int|ffi_converter }} extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new {{ int.name }}(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a '{{ int.name }}' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer({{ int.object_id }})); + } + + static write(dataStream, value) { + dataStream.writePointer({{ int.object_id }}, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Map.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Map.sys.mjs index 0f75df8a3b9c..9816924cf633 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Map.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Map.sys.mjs @@ -1,22 +1,22 @@ // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { +export class {{ map|ffi_converter }} extends FfiConverterArrayBuffer { static read(dataStream) { const len = dataStream.readInt32(); const map = new Map(); for (let i = 0; i < len; i++) { - const key = {{ key_type.ffi_converter() }}.read(dataStream); - const value = {{ value_type.ffi_converter() }}.read(dataStream); + const key = {{ map.key|read_fn }}(dataStream); + const value = {{ map.value|read_fn }}(dataStream); map.set(key, value); } return map; } - static write(dataStream, map) { + static write(dataStream, map) { dataStream.writeInt32(map.size); for (const [key, value] of map) { - {{ key_type.ffi_converter() }}.write(dataStream, key); - {{ value_type.ffi_converter() }}.write(dataStream, value); + {{ map.key|write_fn }}(dataStream, key); + {{ map.value|write_fn }}(dataStream, value); } } @@ -24,8 +24,8 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { // The size of the length let size = 4; for (const [key, value] of map) { - size += {{ key_type.ffi_converter() }}.computeSize(key); - size += {{ value_type.ffi_converter() }}.computeSize(value); + size += {{ map.key|compute_size_fn }}(key); + size += {{ map.value|compute_size_fn }}(value); } return size; } @@ -33,7 +33,7 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { static checkType(map) { for (const [key, value] of map) { try { - {{ key_type.ffi_converter() }}.checkType(key); + {{ map.key|check_type_fn }}(key); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart("(key)"); @@ -42,7 +42,7 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { } try { - {{ value_type.ffi_converter() }}.checkType(value); + {{ map.value|check_type_fn }}(value); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(`[${key}]`); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Module.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Module.sys.mjs new file mode 100644 index 000000000000..7179288af87a --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Module.sys.mjs @@ -0,0 +1,21 @@ +// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. +// Trust me, you don't want to mess with it! + +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; + +// Objects intended to be used in the unit tests +export var UnitTestObjs = {}; + +{%- if has_callback_interface %} +{%- include "CallbackInterfaceRuntime.sys.mjs" %} +{% endif %} + +{% include "Helpers.sys.mjs" %} +{%- for func in functions %} +{%- let callable=func.callable %} +{{ func.js_docstring }} +export {% if func.callable.is_js_async %}async {% endif %}function {{ func.name }}({%- filter indent(4) %}{% include "js/CallableArgs.sys.mjs" %}{% endfilter %}) { + {% include "js/CallableBody.sys.mjs" %} +} +{% endfor %} +{% include "Types.sys.mjs" %} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Object.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Object.sys.mjs deleted file mode 100644 index 6ea05fb8f095..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Object.sys.mjs +++ /dev/null @@ -1,61 +0,0 @@ -{%- let object = ci.get_object_definition(name).unwrap() -%} -{{ object.js_docstring(0) -}} -export class {{ object.js_name() }} { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - {%- for cons in object.constructors() %} - {{ cons.js_docstring(4) -}} - static {{ cons.js_name() }}({{cons.js_arg_names()}}) { - {%- call js::call_constructor(cons, type_, object.call_style_for_constructor(cons, config)) -%} - } - {%- endfor %} - - {%- for meth in object.methods() %} - - {{ meth.js_docstring(4) -}} - {{ meth.js_name() }}({{ meth.js_arg_names() }}) { - {%- call js::call_method(meth, type_, object.call_style_for_method(meth, config)) %} - } - {%- endfor %} - -} - -// Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new {{ object.js_name() }}(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a '{{ object.js_name() }}' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointer{{ object.js_name() }}()); - } - - static write(dataStream, value) { - dataStream.writePointer{{ object.js_name() }}(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Optional.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Optional.sys.mjs index 89d193ad1ab0..203c7d3edd0a 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Optional.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Optional.sys.mjs @@ -1,8 +1,8 @@ // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { +export class {{ optional|ffi_converter }} extends FfiConverterArrayBuffer { static checkType(value) { if (value !== undefined && value !== null) { - {{ inner_type.ffi_converter() }}.checkType(value) + {{ optional.inner|check_type_fn }}(value) } } @@ -12,7 +12,7 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { case 0: return null case 1: - return {{ inner_type.ffi_converter() }}.read(dataStream) + return {{ optional.inner|read_fn }}(dataStream) default: throw new UniFFIError(`Unexpected code: ${code}`); } @@ -24,13 +24,13 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { return; } dataStream.writeUint8(1); - {{ inner_type.ffi_converter() }}.write(dataStream, value) + {{ optional.inner|write_fn}}(dataStream, value) } static computeSize(value) { if (value === null || value === undefined) { return 1; } - return 1 + {{ inner_type.ffi_converter() }}.computeSize(value) + return 1 + {{ optional.inner|compute_size_fn}}(value) } } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Record.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Record.sys.mjs index df0c3044dcfb..0a6c12eada22 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Record.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Record.sys.mjs @@ -1,67 +1,78 @@ -{%- let record = ci.get_record_definition(name).unwrap() -%} -{{ record.js_docstring(0) -}} -export class {{ record.js_name() }} { - constructor({{ record.constructor_field_list() }} = { {% for f in record.fields() %}{{ f.js_name() }}: undefined{% if !loop.last %}, {% endif %}{% endfor %} }) { - {%- for field in record.fields() %} +{{ record.js_docstring }} +export class {{ record.name }} { + constructor( + { + {%- for field in record.fields %} + {{ field.name }}{% if let Some(lit) = field.default %}= {{ lit.js_lit }}{% endif %} + {%- if !loop.last %}, {% endif %} + {%- endfor %} + } = { + {%- for field in record.fields %} + {{ field.name }}: undefined + {%- if !loop.last %}, {% endif %} + {%- endfor %} + } + ) { + {%- for field in record.fields %} try { - {{ field.ffi_converter() }}.checkType({{ field.js_name() }}) + {{ field|check_type_fn }}({{ field.name }}) } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("{{ field.js_name() }}"); + e.addItemDescriptionPart("{{ field.name }}"); } throw e; } {%- endfor %} - {%- for field in record.fields() %} - {{ field.js_docstring(8) -}} - this.{{field.js_name()}} = {{ field.js_name() }}; + {%- for field in record.fields %} + {{ field.js_docstring|indent(8) }} + this.{{field.name}} = {{ field.name }}; {%- endfor %} } equals(other) { return ( - {%- for field in record.fields() %} - {{ field.as_type().equals(&("this.{}"|format(field.js_name())), &("other.{}"|format(field.js_name()))) }}{% if !loop.last %} &&{% endif %} + {%- for field in record.fields %} + {% if !loop.first %}&& {% endif %}{{ field|field_equals("this", "other") }} {%- endfor %} ) } } // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { +export class {{ record|ffi_converter }} extends FfiConverterArrayBuffer { static read(dataStream) { - return new {{record.js_name()}}({ - {%- for field in record.fields() %} - {{ field.js_name() }}: {{ field.read_datastream_fn() }}(dataStream), + return new {{record.name}}({ + {%- for field in record.fields %} + {{ field.name }}: {{ field|read_fn }}(dataStream), {%- endfor %} }); } static write(dataStream, value) { - {%- for field in record.fields() %} - {{ field.write_datastream_fn() }}(dataStream, value.{{field.js_name()}}); + {%- for field in record.fields %} + {{ field|write_fn }}(dataStream, value.{{field.name}}); {%- endfor %} } static computeSize(value) { let totalSize = 0; - {%- for field in record.fields() %} - totalSize += {{ field.ffi_converter() }}.computeSize(value.{{ field.js_name() }}); + {%- for field in record.fields %} + totalSize += {{ field|compute_size_fn }}(value.{{ field.name }}); {%- endfor %} return totalSize } static checkType(value) { super.checkType(value); - if (!(value instanceof {{ record.js_name() }})) { - throw new UniFFITypeError(`Expected '{{ record.js_name() }}', found '${typeof value}'`); + if (!(value instanceof {{ record.name }})) { + throw new UniFFITypeError(`Expected '{{ record.name }}', found '${typeof value}'`); } - {%- for field in record.fields() %} + {%- for field in record.fields %} try { - {{ field.ffi_converter() }}.checkType(value.{{ field.js_name() }}); + {{ field|check_type_fn }}(value.{{ field.name }}); } catch (e) { if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart(".{{ field.js_name() }}"); + e.addItemDescriptionPart(".{{ field.name }}"); } throw e; } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Sequence.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Sequence.sys.mjs index 4c1034a18215..cad79f16f1a4 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Sequence.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Sequence.sys.mjs @@ -1,10 +1,10 @@ // Export the FFIConverter object to make external types work. -export class {{ ffi_converter }} extends FfiConverterArrayBuffer { +export class {{ sequence|ffi_converter }} extends FfiConverterArrayBuffer { static read(dataStream) { const len = dataStream.readInt32(); const arr = []; for (let i = 0; i < len; i++) { - arr.push({{ inner_type.ffi_converter() }}.read(dataStream)); + arr.push({{ sequence.inner|read_fn }}(dataStream)); } return arr; } @@ -12,7 +12,7 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { static write(dataStream, value) { dataStream.writeInt32(value.length); value.forEach((innerValue) => { - {{ inner_type.ffi_converter() }}.write(dataStream, innerValue); + {{ sequence.inner|write_fn }}(dataStream, innerValue); }) } @@ -20,7 +20,7 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { // The size of the length let size = 4; for (const innerValue of value) { - size += {{ inner_type.ffi_converter() }}.computeSize(innerValue); + size += {{ sequence.inner|compute_size_fn }}(innerValue); } return size; } @@ -31,7 +31,7 @@ export class {{ ffi_converter }} extends FfiConverterArrayBuffer { } value.forEach((innerValue, idx) => { try { - {{ inner_type.ffi_converter() }}.checkType(innerValue); + {{ sequence.inner|check_type_fn }}(innerValue); } catch (e) { if (e instanceof UniFFITypeError) { e.addItemDescriptionPart(`[${idx}]`); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/TopLevelFunctions.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/TopLevelFunctions.sys.mjs deleted file mode 100644 index 47db9eb1fb25..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/TopLevelFunctions.sys.mjs +++ /dev/null @@ -1,7 +0,0 @@ -{%- for func in ci.function_definitions() %} - -{{ func.js_docstring(0) -}} -export function {{ func.js_name() }}({{ func.js_arg_names() }}) { -{% call js::call_scaffolding_function(func) %} -} -{%- endfor %} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Types.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Types.sys.mjs index 1ab390e76974..53bd0c328332 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Types.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/Types.sys.mjs @@ -1,13 +1,11 @@ -{%- if !ci.callback_interface_definitions().is_empty() %} -{%- include "CallbackInterfaceRuntime.sys.mjs" %} - -{% endif %} -{%- for type_ in ci.iter_local_types() %} -{%- let ffi_converter = type_.ffi_converter() %} -{%- match type_ %} +{%- for type_def in type_definitions %} +{% match type_def %} +{%- when TypeDefinition::Simple(type_node) %} +{%- let ffi_converter = type_node.ffi_converter %} +{%- match type_node.ty %} {%- when Type::Boolean %} {%- include "Boolean.sys.mjs" %} @@ -41,63 +39,58 @@ {%- when Type::Float64 %} {%- include "Float64.sys.mjs" %} -{%- when Type::Record { name, module_path } %} -{%- include "Record.sys.mjs" %} - -{%- when Type::Optional { inner_type } %} -{%- include "Optional.sys.mjs" %} - {%- when Type::String %} {%- include "String.sys.mjs" %} {%- when Type::Bytes %} {%- include "Bytes.sys.mjs" %} -{%- when Type::Sequence { inner_type } %} +{%- else %} + +throw("Unexpected type in `TypeDefinition::Simple` {{ "{type_node:?}"|format }}") + +{%- endmatch %} + +{%- when TypeDefinition::Optional(optional) %} +{%- include "Optional.sys.mjs" %} + + +{%- when TypeDefinition::Sequence(sequence) %} {%- include "Sequence.sys.mjs" %} -{%- when Type::Map { key_type, value_type } %} +{%- when TypeDefinition::Map(map) %} {%- include "Map.sys.mjs" %} -{%- when Type::Enum { name, module_path } %} -{%- let e = ci.get_enum_definition(name).unwrap() %} + +{%- when TypeDefinition::Record(record) %} +{%- include "Record.sys.mjs" %} + +{%- when TypeDefinition::Enum(e) %} {# For enums, there are either an error *or* an enum, they can't be both. #} -{%- if ci.is_name_used_as_error(name) %} +{%- if e.self_type.is_used_as_error %} {%- let error = e %} {%- include "Error.sys.mjs" %} {%- else %} {%- let enum_ = e %} {%- include "Enum.sys.mjs" %} -{% endif %} +{%- endif %} -{%- when Type::Object { name, imp, module_path } %} -{%- include "Object.sys.mjs" %} -{%- when Type::Custom { name, builtin, module_path } %} +{%- when TypeDefinition::Interface(int) %} +{%- include "Interface.sys.mjs" %} + +{%- when TypeDefinition::Custom(custom) %} {%- include "CustomType.sys.mjs" %} -{%- when Type::CallbackInterface { name, module_path } %} +{%- when TypeDefinition::CallbackInterface(cbi) %} {%- include "CallbackInterface.sys.mjs" %} +{%- when TypeDefinition::External(external) %} +{%- include "ExternalType.sys.mjs" %} + {%- else %} {#- TODO implement the other types #} {%- endmatch %} -{% endfor %} - -{%- for type_ in ci.iter_external_types() %} -{%- let ffi_converter = type_.ffi_converter() %} -{%- let name = type_.name().expect("External type without name") %} -{%- let module_path = type_.module_path().expect("External type without module path") %} -{%- include "ExternalType.sys.mjs" %} {%- endfor %} - - -{%- if !ci.callback_interface_definitions().is_empty() %} -// Define callback interface handlers, this must come after the type loop since they reference the FfiConverters defined above. - -{% for cbi in ci.callback_interface_definitions() %} -{%- include "CallbackInterfaceHandler.sys.mjs" %} -{% endfor %} -{% endif %} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/macros.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/macros.sys.mjs index 4f1a685e3f51..e09e133aa708 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/macros.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/macros.sys.mjs @@ -11,55 +11,55 @@ {%- endmacro %} {%- macro _call_scaffolding_function(func, return_type, receiver_ffi_converter, call_style) %} - {%- match return_type %} - {%- when Some with (return_type) %} - const liftResult = (result) => {{ return_type.ffi_converter() }}.lift(result); - {%- else %} - const liftResult = (result) => undefined; - {%- endmatch %} - {%- match func.throws_type() %} - {%- when Some with (err_type) %} - const liftError = (data) => {{ err_type.ffi_converter() }}.lift(data); - {%- else %} - const liftError = null; - {%- endmatch %} - const functionCall = () => { - {%- for arg in func.arguments() %} - try { - {{ arg.ffi_converter() }}.checkType({{ arg.js_name() }}) - } catch (e) { - if (e instanceof UniFFITypeError) { - e.addItemDescriptionPart("{{ arg.js_name() }}"); - } - throw e; - } - {%- endfor %} - - {%- match call_style %} - {%- when CallStyle::AsyncWrapper %} - return UniFFIScaffolding.callAsyncWrapper( - {%- when CallStyle::Sync %} - return UniFFIScaffolding.callSync( - {%- when CallStyle::Async %} - return UniFFIScaffolding.callAsync( - {%- endmatch %} - {{ function_ids.get(ci, func.ffi_func()) }}, // {{ function_ids.name(ci, func.ffi_func()) }} - {%- if receiver_ffi_converter != "" %} - {{ receiver_ffi_converter }}.lower(this), - {%- endif %} - {%- for arg in func.arguments() %} - {{ arg.lower_fn() }}({{ arg.js_name() }}), - {%- endfor %} - ) +{%- match return_type %} +{%- when Some with (return_type) %} +const liftResult = (result) => {{ return_type.ffi_converter() }}.lift(result); +{%- else %} +const liftResult = (result) => undefined; +{%- endmatch %} +{%- match func.throws_type() %} +{%- when Some with (err_type) %} +const liftError = (data) => {{ err_type.ffi_converter() }}.lift(data); +{%- else %} +const liftError = null; +{%- endmatch %} +const functionCall = () => { + {%- for arg in func.arguments() %} + try { + {{ arg.ffi_converter() }}.checkType({{ arg.js_name() }}) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("{{ arg.js_name() }}"); } + throw e; + } + {%- endfor %} - {%- if call_style.is_js_async() %} - try { - return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); - } catch (error) { - return Promise.reject(error) - } - {%- else %} - return handleRustResult(functionCall(), liftResult, liftError); + {%- match call_style %} + {%- when CallStyle::AsyncWrapper %} + return UniFFIScaffolding.callAsyncWrapper( + {%- when CallStyle::Sync %} + return UniFFIScaffolding.callSync( + {%- when CallStyle::Async %} + return UniFFIScaffolding.callAsync( + {%- endmatch %} + {{ function_ids.get(ci, func.ffi_func()) }}, // {{ function_ids.name(ci, func.ffi_func()) }} + {%- if receiver_ffi_converter != "" %} + {{ receiver_ffi_converter }}.lower(this), {%- endif %} + {%- for arg in func.arguments() %} + {{ arg.lower_fn() }}({{ arg.js_name() }}), + {%- endfor %} + ) +} + +{%- if call_style.is_js_async() %} +try { + return functionCall().then((result) => handleRustResult(result, liftResult, liftError)); +} catch (error) { + return Promise.reject(error) +} +{%- else %} +return handleRustResult(functionCall(), liftResult, liftError); +{%- endif %} {%- endmacro %} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/wrapper.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/wrapper.sys.mjs deleted file mode 100644 index 0c33c05e4fde..000000000000 --- a/toolkit/components/uniffi-bindgen-gecko-js/src/templates/js/wrapper.sys.mjs +++ /dev/null @@ -1,15 +0,0 @@ -// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. -// Trust me, you don't want to mess with it! - -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - -{% import "macros.sys.mjs" as js %} - -// Objects intended to be used in the unit tests -export var UnitTestObjs = {}; - -{% include "Helpers.sys.mjs" %} - -{% include "Types.sys.mjs" %} - -{% include "TopLevelFunctions.sys.mjs" %} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/test-fixtures/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/test-fixtures/Cargo.toml new file mode 100644 index 000000000000..f157a571e498 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/test-fixtures/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "uniffi-bindgen-gecko-js-test-fixtures" +version = "0.29.0" +edition = "2021" + +[lib] +crate-type = ["lib", "staticlib"] + +[dependencies] +uniffi_bindings_tests = { path = "../uniffi_bindings_tests" } +uniffi_bindings_tests_external_types = { path = "../uniffi_bindings_tests_external_types" } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/test-fixtures/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/test-fixtures/src/lib.rs new file mode 100644 index 000000000000..2643dcd031bf --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/test-fixtures/src/lib.rs @@ -0,0 +1,2 @@ +uniffi_bindings_tests::uniffi_reexport_scaffolding!(); +uniffi_bindings_tests_external_types::uniffi_reexport_scaffolding!(); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs new file mode 100644 index 000000000000..16bdc82cced4 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs @@ -0,0 +1,3180 @@ +// This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. +// Trust me, you don't want to mess with it! + +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; + +// Objects intended to be used in the unit tests +export var UnitTestObjs = {}; +/** + * Handler for a single UniFFI CallbackInterface + * + * This class stores objects that implement a callback interface in a handle + * map, allowing them to be referenced by the Rust code using an integer + * handle. + * + * While the callback object is stored in the map, it allows the Rust code to + * call methods on the object using the callback object handle, a method id, + * and an ArrayBuffer packed with the method arguments. + * + * When the Rust code drops its reference, it sends a call with the methodId=0, + * which causes callback object to be removed from the map. + */ +class UniFFICallbackHandler { + #name; + #interfaceId; + #handleCounter; + #handleMap; + #methodHandlers; + #allowNewCallbacks + + /** + * Create a UniFFICallbackHandler + * @param {string} name - Human-friendly name for this callback interface + * @param {int} interfaceId - Interface ID for this CallbackInterface. + * @param {UniFFICallbackMethodHandler[]} methodHandlers -- UniFFICallbackHandler for each method, in the same order as the UDL file + */ + constructor(name, interfaceId, methodHandlers) { + this.#name = name; + this.#interfaceId = interfaceId; + this.#handleCounter = 0; + this.#handleMap = new Map(); + this.#methodHandlers = methodHandlers; + this.#allowNewCallbacks = true; + + UniFFIScaffolding.registerCallbackHandler(this.#interfaceId, this); + Services.obs.addObserver(this, "xpcom-shutdown"); + } + + /** + * Store a callback object in the handle map and return the handle + * + * @param {obj} callbackObj - Object that implements the callback interface + * @returns {int} - Handle for this callback object, this is what gets passed back to Rust. + */ + storeCallbackObj(callbackObj) { + if (!this.#allowNewCallbacks) { + throw new UniFFIError(`No new callbacks allowed for ${this.#name}`); + } + const handle = this.#handleCounter; + this.#handleCounter += 1; + this.#handleMap.set(handle, new UniFFICallbackHandleMapEntry(callbackObj, Components.stack.caller.formattedStack.trim())); + return handle; + } + + /** + * Get a previously stored callback object + * + * @param {int} handle - Callback object handle, returned from `storeCallbackObj()` + * @returns {obj} - Callback object + */ + getCallbackObj(handle) { + return this.#handleMap.get(handle).callbackObj; + } + + /** + * Set if new callbacks are allowed for this handler + * + * This is called with false during shutdown to ensure the callback maps don't + * prevent JS objects from being GCed. + */ + setAllowNewCallbacks(allow) { + this.#allowNewCallbacks = allow + } + + /** + * Check that no callbacks are currently registered + * + * If there are callbacks registered a UniFFIError will be thrown. This is + * called during shutdown to generate an alert if there are leaked callback + * interfaces. + */ + assertNoRegisteredCallbacks() { + if (this.#handleMap.size > 0) { + const entry = this.#handleMap.values().next().value; + throw new UniFFIError(`UniFFI interface ${this.#name} has ${this.#handleMap.size} registered callbacks at xpcom-shutdown. This likely indicates a UniFFI callback leak.\nStack trace for the first leaked callback:\n${entry.stackTrace}.`); + } + } + + /** + * Invoke a method on a stored callback object + * @param {int} handle - Object handle + * @param {int} methodId - Method index (0-based) + * @param {UniFFIScaffoldingValue[]} args - Arguments to pass to the method + */ + call(handle, methodId, ...args) { + try { + this.#invokeCallbackInner(handle, methodId, args); + } catch (e) { + console.error(`internal error invoking callback: ${e}`) + } + } + + /** + * Destroy a stored callback object + * @param {int} handle - Object handle + */ + destroy(handle) { + this.#handleMap.delete(handle); + } + + #invokeCallbackInner(handle, methodId, args) { + const callbackObj = this.getCallbackObj(handle); + if (callbackObj === undefined) { + throw new UniFFIError(`${this.#name}: invalid callback handle id: ${handle}`); + } + + // Get the method data, converting from 1-based indexing + const methodHandler = this.#methodHandlers[methodId]; + if (methodHandler === undefined) { + throw new UniFFIError(`${this.#name}: invalid method id: ${methodId}`) + } + + methodHandler.call(callbackObj, args); + } + + /** + * xpcom-shutdown observer method + * + * This handles: + * - Deregistering ourselves as the UniFFI callback handler + * - Checks for any leftover stored callbacks which indicate memory leaks + */ + observe(aSubject, aTopic, aData) { + if (aTopic == "xpcom-shutdown") { + try { + this.setAllowNewCallbacks(false); + this.assertNoRegisteredCallbacks(); + UniFFIScaffolding.deregisterCallbackHandler(this.#interfaceId); + } catch (ex) { + console.error(`UniFFI Callback interface error during xpcom-shutdown: ${ex}`); + Cc["@mozilla.org/xpcom/debug;1"] + .getService(Ci.nsIDebug2) + .abort(ex.filename, ex.lineNumber); + } + } + } +} + +/** + * Handles calling a single method for a callback interface + */ +class UniFFICallbackMethodHandler { + #name; + #argsConverters; + + /** + * Create a UniFFICallbackMethodHandler + + * @param {string} name -- Name of the method to call on the callback object + * @param {FfiConverter[]} argsConverters - FfiConverter for each argument type + */ + constructor(name, argsConverters) { + this.#name = name; + this.#argsConverters = argsConverters; + } + + /** + * Invoke the method + * + * @param {obj} callbackObj -- Object implementing the callback interface for this method + * @param {ArrayBuffer} argsArrayBuffer -- Arguments for the method, packed in an ArrayBuffer + */ + call(callbackObj, args) { + const convertedArgs = this.#argsConverters.map((converter, i) => converter.lift(args[i])); + return callbackObj[this.#name](...convertedArgs); + } +} + +/** + * UniFFICallbackHandler.handleMap entry + * + * @property callbackObj - Callback object, this must implement the callback interface. + * @property {string} stackTrace - Stack trace from when the callback object was registered. This is used to proved extra context when debugging leaked callback objects. + */ +class UniFFICallbackHandleMapEntry { + constructor(callbackObj, stackTrace) { + this.callbackObj = callbackObj; + this.stackTrace = stackTrace + } +} + + +let lazy = {}; + +ChromeUtils.defineLazyGetter(lazy, "decoder", () => new TextDecoder()); +ChromeUtils.defineLazyGetter(lazy, "encoder", () => new TextEncoder()); + +// Write/Read data to/from an ArrayBuffer +class ArrayBufferDataStream { + constructor(arrayBuffer) { + this.dataView = new DataView(arrayBuffer); + this.pos = 0; + } + + readUint8() { + let rv = this.dataView.getUint8(this.pos); + this.pos += 1; + return rv; + } + + writeUint8(value) { + this.dataView.setUint8(this.pos, value); + this.pos += 1; + } + + readUint16() { + let rv = this.dataView.getUint16(this.pos); + this.pos += 2; + return rv; + } + + writeUint16(value) { + this.dataView.setUint16(this.pos, value); + this.pos += 2; + } + + readUint32() { + let rv = this.dataView.getUint32(this.pos); + this.pos += 4; + return rv; + } + + writeUint32(value) { + this.dataView.setUint32(this.pos, value); + this.pos += 4; + } + + readUint64() { + let rv = this.dataView.getBigUint64(this.pos); + this.pos += 8; + return Number(rv); + } + + writeUint64(value) { + this.dataView.setBigUint64(this.pos, BigInt(value)); + this.pos += 8; + } + + + readInt8() { + let rv = this.dataView.getInt8(this.pos); + this.pos += 1; + return rv; + } + + writeInt8(value) { + this.dataView.setInt8(this.pos, value); + this.pos += 1; + } + + readInt16() { + let rv = this.dataView.getInt16(this.pos); + this.pos += 2; + return rv; + } + + writeInt16(value) { + this.dataView.setInt16(this.pos, value); + this.pos += 2; + } + + readInt32() { + let rv = this.dataView.getInt32(this.pos); + this.pos += 4; + return rv; + } + + writeInt32(value) { + this.dataView.setInt32(this.pos, value); + this.pos += 4; + } + + readInt64() { + let rv = this.dataView.getBigInt64(this.pos); + this.pos += 8; + return Number(rv); + } + + writeInt64(value) { + this.dataView.setBigInt64(this.pos, BigInt(value)); + this.pos += 8; + } + + readFloat32() { + let rv = this.dataView.getFloat32(this.pos); + this.pos += 4; + return rv; + } + + writeFloat32(value) { + this.dataView.setFloat32(this.pos, value); + this.pos += 4; + } + + readFloat64() { + let rv = this.dataView.getFloat64(this.pos); + this.pos += 8; + return rv; + } + + writeFloat64(value) { + this.dataView.setFloat64(this.pos, value); + this.pos += 8; + } + + + writeString(value) { + // Note: in order to efficiently write this data, we first write the + // string data, reserving 4 bytes for the size. + const dest = new Uint8Array(this.dataView.buffer, this.pos + 4); + const encodeResult = lazy.encoder.encodeInto(value, dest); + if (encodeResult.read != value.length) { + throw new UniFFIError( + "writeString: out of space when writing to ArrayBuffer. Did the computeSize() method returned the wrong result?" + ); + } + const size = encodeResult.written; + // Next, go back and write the size before the string data + this.dataView.setUint32(this.pos, size); + // Finally, advance our position past both the size and string data + this.pos += size + 4; + } + + readString() { + const size = this.readUint32(); + const source = new Uint8Array(this.dataView.buffer, this.pos, size) + const value = lazy.decoder.decode(source); + this.pos += size; + return value; + } + + readBytes() { + const size = this.readInt32(); + const bytes = new Uint8Array(this.dataView.buffer, this.pos, size); + this.pos += size; + return bytes + } + + writeBytes(value) { + this.writeUint32(value.length); + value.forEach((elt) => { + this.writeUint8(elt); + }) + } + + // Reads a pointer from the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + readPointer(pointerId) { + const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); + this.pos += 8; + return res; + } + + // Writes a pointer into the data stream + // UniFFI Pointers are **always** 8 bytes long. That is enforced + // by the C++ and Rust Scaffolding code. + writePointer(pointerId, value) { + UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); + this.pos += 8; + } +} + +function handleRustResult(result, liftCallback, liftErrCallback) { + switch (result.code) { + case "success": + return liftCallback(result.data); + + case "error": + throw liftErrCallback(result.data); + + case "internal-error": + if (result.data) { + throw new UniFFIInternalError(FfiConverterString.lift(result.data)); + } else { + throw new UniFFIInternalError("Unknown error"); + } + + default: + throw new UniFFIError(`Unexpected status code: ${result.code}`); + } +} + +class UniFFIError { + constructor(message) { + this.message = message; + } + + toString() { + return `UniFFIError: ${this.message}` + } +} + +class UniFFIInternalError extends UniFFIError {} + +// Base class for FFI converters +class FfiConverter { + // throw `UniFFITypeError` if a value to be converted has an invalid type + static checkType(value) { + if (value === undefined ) { + throw new UniFFITypeError(`undefined`); + } + if (value === null ) { + throw new UniFFITypeError(`null`); + } + } +} + +// Base class for FFI converters that lift/lower by reading/writing to an ArrayBuffer +class FfiConverterArrayBuffer extends FfiConverter { + static lift(buf) { + return this.read(new ArrayBufferDataStream(buf)); + } + + static lower(value) { + const buf = new ArrayBuffer(this.computeSize(value)); + const dataStream = new ArrayBufferDataStream(buf); + this.write(dataStream, value); + return buf; + } + + /** + * Computes the size of the value. + * + * @param {*} _value + * @return {number} + */ + static computeSize(_value) { + throw new UniFFIInternalError("computeSize() should be declared in the derived class"); + } + + /** + * Reads the type from a data stream. + * + * @param {ArrayBufferDataStream} _dataStream + * @returns {any} + */ + static read(_dataStream) { + throw new UniFFIInternalError("read() should be declared in the derived class"); + } + + /** + * Writes the type to a data stream. + * + * @param {ArrayBufferDataStream} _dataStream + * @param {any} _value + */ + static write(_dataStream, _value) { + throw new UniFFIInternalError("write() should be declared in the derived class"); + } + +} + +// Symbols that are used to ensure that Object constructors +// can only be used with a proper UniFFI pointer +const uniffiObjectPtr = Symbol("uniffiObjectPtr"); +const constructUniffiObject = Symbol("constructUniffiObject"); +UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; +/** + * asyncRoundtripF32 + */ +export async function asyncRoundtripF32( + v) { + +FfiConverterFloat32.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 110, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_f32 + FfiConverterFloat32.lower(v), +) +return handleRustResult( + result, + FfiConverterFloat32.lift.bind(FfiConverterFloat32), + null, +) +} + +/** + * asyncRoundtripF64 + */ +export async function asyncRoundtripF64( + v) { + +FfiConverterFloat64.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 111, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_f64 + FfiConverterFloat64.lower(v), +) +return handleRustResult( + result, + FfiConverterFloat64.lift.bind(FfiConverterFloat64), + null, +) +} + +/** + * asyncRoundtripI16 + */ +export async function asyncRoundtripI16( + v) { + +FfiConverterInt16.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 112, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i16 + FfiConverterInt16.lower(v), +) +return handleRustResult( + result, + FfiConverterInt16.lift.bind(FfiConverterInt16), + null, +) +} + +/** + * asyncRoundtripI32 + */ +export async function asyncRoundtripI32( + v) { + +FfiConverterInt32.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 113, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i32 + FfiConverterInt32.lower(v), +) +return handleRustResult( + result, + FfiConverterInt32.lift.bind(FfiConverterInt32), + null, +) +} + +/** + * asyncRoundtripI64 + */ +export async function asyncRoundtripI64( + v) { + +FfiConverterInt64.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 114, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i64 + FfiConverterInt64.lower(v), +) +return handleRustResult( + result, + FfiConverterInt64.lift.bind(FfiConverterInt64), + null, +) +} + +/** + * asyncRoundtripI8 + */ +export async function asyncRoundtripI8( + v) { + +FfiConverterInt8.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 115, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i8 + FfiConverterInt8.lower(v), +) +return handleRustResult( + result, + FfiConverterInt8.lift.bind(FfiConverterInt8), + null, +) +} + +/** + * asyncRoundtripMap + */ +export async function asyncRoundtripMap( + v) { + +FfiConverterMapStringString.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 116, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_map + FfiConverterMapStringString.lower(v), +) +return handleRustResult( + result, + FfiConverterMapStringString.lift.bind(FfiConverterMapStringString), + null, +) +} + +/** + * asyncRoundtripObj + */ +export async function asyncRoundtripObj( + v) { + +FfiConverterTypeAsyncInterface.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 117, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_obj + FfiConverterTypeAsyncInterface.lower(v), +) +return handleRustResult( + result, + FfiConverterTypeAsyncInterface.lift.bind(FfiConverterTypeAsyncInterface), + null, +) +} + +/** + * asyncRoundtripString + */ +export async function asyncRoundtripString( + v) { + +FfiConverterString.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 118, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_string + FfiConverterString.lower(v), +) +return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, +) +} + +/** + * asyncRoundtripU16 + */ +export async function asyncRoundtripU16( + v) { + +FfiConverterUInt16.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 119, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u16 + FfiConverterUInt16.lower(v), +) +return handleRustResult( + result, + FfiConverterUInt16.lift.bind(FfiConverterUInt16), + null, +) +} + +/** + * asyncRoundtripU32 + */ +export async function asyncRoundtripU32( + v) { + +FfiConverterUInt32.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 120, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u32 + FfiConverterUInt32.lower(v), +) +return handleRustResult( + result, + FfiConverterUInt32.lift.bind(FfiConverterUInt32), + null, +) +} + +/** + * asyncRoundtripU64 + */ +export async function asyncRoundtripU64( + v) { + +FfiConverterUInt64.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 121, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u64 + FfiConverterUInt64.lower(v), +) +return handleRustResult( + result, + FfiConverterUInt64.lift.bind(FfiConverterUInt64), + null, +) +} + +/** + * asyncRoundtripU8 + */ +export async function asyncRoundtripU8( + v) { + +FfiConverterUInt8.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 122, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u8 + FfiConverterUInt8.lower(v), +) +return handleRustResult( + result, + FfiConverterUInt8.lift.bind(FfiConverterUInt8), + null, +) +} + +/** + * asyncRoundtripVec + */ +export async function asyncRoundtripVec( + v) { + +FfiConverterSequenceUInt32.checkType(v); +const result = await UniFFIScaffolding.callAsync( + 123, // uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_vec + FfiConverterSequenceUInt32.lower(v), +) +return handleRustResult( + result, + FfiConverterSequenceUInt32.lift.bind(FfiConverterSequenceUInt32), + null, +) +} + +/** + * cloneInterface + */ +export function cloneInterface( + int) { + +FfiConverterTypeTestInterface.checkType(int); +const result = UniFFIScaffolding.callSync( + 124, // uniffi_uniffi_bindings_tests_fn_func_clone_interface + FfiConverterTypeTestInterface.lower(int), +) +return handleRustResult( + result, + FfiConverterTypeTestInterface.lift.bind(FfiConverterTypeTestInterface), + null, +) +} + +/** + * funcWithDefault + */ +export function funcWithDefault( + arg = "DEFAULT") { + +FfiConverterString.checkType(arg); +const result = UniFFIScaffolding.callSync( + 125, // uniffi_uniffi_bindings_tests_fn_func_func_with_default + FfiConverterString.lower(arg), +) +return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, +) +} + +/** + * funcWithError + */ +export function funcWithError( + input) { + +FfiConverterUInt32.checkType(input); +const result = UniFFIScaffolding.callSync( + 126, // uniffi_uniffi_bindings_tests_fn_func_func_with_error + FfiConverterUInt32.lower(input), +) +return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTestError.lift.bind(FfiConverterTypeTestError), +) +} + +/** + * funcWithFlatError + */ +export function funcWithFlatError( + input) { + +FfiConverterUInt32.checkType(input); +const result = UniFFIScaffolding.callSync( + 127, // uniffi_uniffi_bindings_tests_fn_func_func_with_flat_error + FfiConverterUInt32.lower(input), +) +return handleRustResult( + result, + (result) => undefined, + FfiConverterTypeTestFlatError.lift.bind(FfiConverterTypeTestFlatError), +) +} + +/** + * Test a multi-word argument. `the_argument` should be normalized to the naming style of the + * foreign language. + */ +export function funcWithMultiWordArg( + theArgument) { + +FfiConverterString.checkType(theArgument); +const result = UniFFIScaffolding.callSync( + 128, // uniffi_uniffi_bindings_tests_fn_func_func_with_multi_word_arg + FfiConverterString.lower(theArgument), +) +return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, +) +} + +/** + * invokeTestCallbackInterfaceMethod + */ +export function invokeTestCallbackInterfaceMethod( + cbi) { + +FfiConverterTypeTestCallbackInterface.checkType(cbi); +const result = UniFFIScaffolding.callSync( + 129, // uniffi_uniffi_bindings_tests_fn_func_invoke_test_callback_interface_method + FfiConverterTypeTestCallbackInterface.lower(cbi), +) +return handleRustResult( + result, + FfiConverterUInt32.lift.bind(FfiConverterUInt32), + null, +) +} + +/** + * roundtripBool + */ +export function roundtripBool( + a) { + +FfiConverterBoolean.checkType(a); +const result = UniFFIScaffolding.callSync( + 130, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_bool + FfiConverterBoolean.lower(a), +) +return handleRustResult( + result, + FfiConverterBoolean.lift.bind(FfiConverterBoolean), + null, +) +} + +/** + * roundtripComplexCompound + */ +export function roundtripComplexCompound( + a) { + +FfiConverterOptionalSequenceMapStringUInt32.checkType(a); +const result = UniFFIScaffolding.callSync( + 131, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_compound + FfiConverterOptionalSequenceMapStringUInt32.lower(a), +) +return handleRustResult( + result, + FfiConverterOptionalSequenceMapStringUInt32.lift.bind(FfiConverterOptionalSequenceMapStringUInt32), + null, +) +} + +/** + * roundtripComplexEnum + */ +export function roundtripComplexEnum( + en) { + +FfiConverterTypeComplexEnum.checkType(en); +const result = UniFFIScaffolding.callSync( + 132, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_enum + FfiConverterTypeComplexEnum.lower(en), +) +return handleRustResult( + result, + FfiConverterTypeComplexEnum.lift.bind(FfiConverterTypeComplexEnum), + null, +) +} + +/** + * roundtripComplexRec + */ +export function roundtripComplexRec( + rec) { + +FfiConverterTypeComplexRec.checkType(rec); +const result = UniFFIScaffolding.callSync( + 133, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_rec + FfiConverterTypeComplexRec.lower(rec), +) +return handleRustResult( + result, + FfiConverterTypeComplexRec.lift.bind(FfiConverterTypeComplexRec), + null, +) +} + +/** + * roundtripCustomType + */ +export function roundtripCustomType( + handle) { + +FfiConverterTypeHandle.checkType(handle); +const result = UniFFIScaffolding.callSync( + 134, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_custom_type + FfiConverterTypeHandle.lower(handle), +) +return handleRustResult( + result, + FfiConverterTypeHandle.lift.bind(FfiConverterTypeHandle), + null, +) +} + +/** + * roundtripEnumNoData + */ +export function roundtripEnumNoData( + en) { + +FfiConverterTypeEnumNoData.checkType(en); +const result = UniFFIScaffolding.callSync( + 135, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_enum_no_data + FfiConverterTypeEnumNoData.lower(en), +) +return handleRustResult( + result, + FfiConverterTypeEnumNoData.lift.bind(FfiConverterTypeEnumNoData), + null, +) +} + +/** + * roundtripEnumWithData + */ +export function roundtripEnumWithData( + en) { + +FfiConverterTypeEnumWithData.checkType(en); +const result = UniFFIScaffolding.callSync( + 136, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_enum_with_data + FfiConverterTypeEnumWithData.lower(en), +) +return handleRustResult( + result, + FfiConverterTypeEnumWithData.lift.bind(FfiConverterTypeEnumWithData), + null, +) +} + +/** + * roundtripF32 + */ +export function roundtripF32( + a) { + +FfiConverterFloat32.checkType(a); +const result = UniFFIScaffolding.callSync( + 137, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_f32 + FfiConverterFloat32.lower(a), +) +return handleRustResult( + result, + FfiConverterFloat32.lift.bind(FfiConverterFloat32), + null, +) +} + +/** + * roundtripF64 + */ +export function roundtripF64( + a) { + +FfiConverterFloat64.checkType(a); +const result = UniFFIScaffolding.callSync( + 138, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_f64 + FfiConverterFloat64.lower(a), +) +return handleRustResult( + result, + FfiConverterFloat64.lift.bind(FfiConverterFloat64), + null, +) +} + +/** + * roundtripHashMap + */ +export function roundtripHashMap( + a) { + +FfiConverterMapStringUInt32.checkType(a); +const result = UniFFIScaffolding.callSync( + 139, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_hash_map + FfiConverterMapStringUInt32.lower(a), +) +return handleRustResult( + result, + FfiConverterMapStringUInt32.lift.bind(FfiConverterMapStringUInt32), + null, +) +} + +/** + * roundtripI16 + */ +export function roundtripI16( + a) { + +FfiConverterInt16.checkType(a); +const result = UniFFIScaffolding.callSync( + 140, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_i16 + FfiConverterInt16.lower(a), +) +return handleRustResult( + result, + FfiConverterInt16.lift.bind(FfiConverterInt16), + null, +) +} + +/** + * roundtripI32 + */ +export function roundtripI32( + a) { + +FfiConverterInt32.checkType(a); +const result = UniFFIScaffolding.callSync( + 141, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_i32 + FfiConverterInt32.lower(a), +) +return handleRustResult( + result, + FfiConverterInt32.lift.bind(FfiConverterInt32), + null, +) +} + +/** + * roundtripI64 + */ +export function roundtripI64( + a) { + +FfiConverterInt64.checkType(a); +const result = UniFFIScaffolding.callSync( + 142, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_i64 + FfiConverterInt64.lower(a), +) +return handleRustResult( + result, + FfiConverterInt64.lift.bind(FfiConverterInt64), + null, +) +} + +/** + * roundtripI8 + */ +export function roundtripI8( + a) { + +FfiConverterInt8.checkType(a); +const result = UniFFIScaffolding.callSync( + 143, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_i8 + FfiConverterInt8.lower(a), +) +return handleRustResult( + result, + FfiConverterInt8.lift.bind(FfiConverterInt8), + null, +) +} + +/** + * roundtripOption + */ +export function roundtripOption( + a) { + +FfiConverterOptionalUInt32.checkType(a); +const result = UniFFIScaffolding.callSync( + 144, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_option + FfiConverterOptionalUInt32.lower(a), +) +return handleRustResult( + result, + FfiConverterOptionalUInt32.lift.bind(FfiConverterOptionalUInt32), + null, +) +} + +/** + * roundtripSimpleRec + */ +export async function roundtripSimpleRec( + rec) { + +FfiConverterTypeSimpleRec.checkType(rec); +const result = await UniFFIScaffolding.callAsyncWrapper( + 145, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_simple_rec + FfiConverterTypeSimpleRec.lower(rec), +) +return handleRustResult( + result, + FfiConverterTypeSimpleRec.lift.bind(FfiConverterTypeSimpleRec), + null, +) +} + +/** + * roundtripString + */ +export function roundtripString( + a) { + +FfiConverterString.checkType(a); +const result = UniFFIScaffolding.callSync( + 146, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_string + FfiConverterString.lower(a), +) +return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, +) +} + +/** + * roundtripU16 + */ +export function roundtripU16( + a) { + +FfiConverterUInt16.checkType(a); +const result = UniFFIScaffolding.callSync( + 147, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_u16 + FfiConverterUInt16.lower(a), +) +return handleRustResult( + result, + FfiConverterUInt16.lift.bind(FfiConverterUInt16), + null, +) +} + +/** + * roundtripU32 + */ +export function roundtripU32( + a) { + +FfiConverterUInt32.checkType(a); +const result = UniFFIScaffolding.callSync( + 148, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_u32 + FfiConverterUInt32.lower(a), +) +return handleRustResult( + result, + FfiConverterUInt32.lift.bind(FfiConverterUInt32), + null, +) +} + +/** + * roundtripU64 + */ +export function roundtripU64( + a) { + +FfiConverterUInt64.checkType(a); +const result = UniFFIScaffolding.callSync( + 149, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_u64 + FfiConverterUInt64.lower(a), +) +return handleRustResult( + result, + FfiConverterUInt64.lift.bind(FfiConverterUInt64), + null, +) +} + +/** + * roundtripU8 + */ +export function roundtripU8( + a) { + +FfiConverterUInt8.checkType(a); +const result = UniFFIScaffolding.callSync( + 150, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_u8 + FfiConverterUInt8.lower(a), +) +return handleRustResult( + result, + FfiConverterUInt8.lift.bind(FfiConverterUInt8), + null, +) +} + +/** + * roundtripVec + */ +export function roundtripVec( + a) { + +FfiConverterSequenceUInt32.checkType(a); +const result = UniFFIScaffolding.callSync( + 151, // uniffi_uniffi_bindings_tests_fn_func_roundtrip_vec + FfiConverterSequenceUInt32.lower(a), +) +return handleRustResult( + result, + FfiConverterSequenceUInt32.lift.bind(FfiConverterSequenceUInt32), + null, +) +} + +/** + * Complex test: input a bunch of different values and add them together + */ +export function sumWithManyTypes( + a, + b, + c, + d, + e, + f, + g, + h, + i, + j, + negate) { + +FfiConverterUInt8.checkType(a); +FfiConverterInt8.checkType(b); +FfiConverterUInt16.checkType(c); +FfiConverterInt16.checkType(d); +FfiConverterUInt32.checkType(e); +FfiConverterInt32.checkType(f); +FfiConverterUInt64.checkType(g); +FfiConverterInt64.checkType(h); +FfiConverterFloat32.checkType(i); +FfiConverterFloat64.checkType(j); +FfiConverterBoolean.checkType(negate); +const result = UniFFIScaffolding.callSync( + 152, // uniffi_uniffi_bindings_tests_fn_func_sum_with_many_types + FfiConverterUInt8.lower(a), + FfiConverterInt8.lower(b), + FfiConverterUInt16.lower(c), + FfiConverterInt16.lower(d), + FfiConverterUInt32.lower(e), + FfiConverterInt32.lower(f), + FfiConverterUInt64.lower(g), + FfiConverterInt64.lower(h), + FfiConverterFloat32.lower(i), + FfiConverterFloat64.lower(j), + FfiConverterBoolean.lower(negate), +) +return handleRustResult( + result, + FfiConverterFloat64.lift.bind(FfiConverterFloat64), + null, +) +} + +/** + * swapTestInterfaces + */ +export function swapTestInterfaces( + interfaces) { + +FfiConverterTypeTwoTestInterfaces.checkType(interfaces); +const result = UniFFIScaffolding.callSync( + 153, // uniffi_uniffi_bindings_tests_fn_func_swap_test_interfaces + FfiConverterTypeTwoTestInterfaces.lower(interfaces), +) +return handleRustResult( + result, + FfiConverterTypeTwoTestInterfaces.lift.bind(FfiConverterTypeTwoTestInterfaces), + null, +) +} + +/** + * testFunc + */ +export function testFunc() { + +const result = UniFFIScaffolding.callSync( + 154, // uniffi_uniffi_bindings_tests_fn_func_test_func +) +return handleRustResult( + result, + (result) => undefined, + null, +) +} + + +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint8(value) + } + static read(dataStream) { + return dataStream.readUint8() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterInt8 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < -128 || value > 127) { + throw new UniFFITypeError(`${value} exceeds the I8 bounds`); + } + } + static computeSize(_value) { + return 1; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt8(value) + } + static read(dataStream) { + return dataStream.readInt8() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt16 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 65535) { + throw new UniFFITypeError(`${value} exceeds the U16 bounds`); + } + } + static computeSize(_value) { + return 2; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint16(value) + } + static read(dataStream) { + return dataStream.readUint16() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterInt16 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < -32768 || value > 32767) { + throw new UniFFITypeError(`${value} exceeds the I16 bounds`); + } + } + static computeSize(_value) { + return 2; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt16(value) + } + static read(dataStream) { + return dataStream.readInt16() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt32 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < 0 || value > 4294967295) { + throw new UniFFITypeError(`${value} exceeds the U32 bounds`); + } + } + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint32(value) + } + static read(dataStream) { + return dataStream.readUint32() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterInt32 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isInteger(value)) { + throw new UniFFITypeError(`${value} is not an integer`); + } + if (value < -2147483648 || value > 2147483647) { + throw new UniFFITypeError(`${value} exceeds the I32 bounds`); + } + } + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt32(value) + } + static read(dataStream) { + return dataStream.readInt32() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); + } + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint64(value) + } + static read(dataStream) { + return dataStream.readUint64() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeInt64(value) + } + static read(dataStream) { + return dataStream.readInt64() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterFloat32 extends FfiConverter { + static computeSize(_value) { + return 4; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeFloat32(value) + } + static read(dataStream) { + return dataStream.readFloat32() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterFloat64 extends FfiConverter { + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeFloat64(value) + } + static read(dataStream) { + return dataStream.readFloat64() + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterString extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (typeof value !== "string") { + throw new UniFFITypeError(`${value} is not a string`); + } + } + + static lift(buf) { + const utf8Arr = new Uint8Array(buf); + return lazy.decoder.decode(utf8Arr); + } + static lower(value) { + return lazy.encoder.encode(value).buffer; + } + + static write(dataStream, value) { + dataStream.writeString(value); + } + + static read(dataStream) { + return dataStream.readString(); + } + + static computeSize(value) { + return 4 + lazy.encoder.encode(value).length + } +} +/** + * SimpleRec + */ +export class SimpleRec { + constructor( + { + a + } = { + a: undefined + } + ) { + try { + FfiConverterUInt8.checkType(a) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("a"); + } + throw e; + } + /** + * a + */ + this.a = a; + } + + equals(other) { + return ( + this.a == other.a + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeSimpleRec extends FfiConverterArrayBuffer { + static read(dataStream) { + return new SimpleRec({ + a: FfiConverterUInt8.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterUInt8.write(dataStream, value.a); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterUInt8.computeSize(value.a); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof SimpleRec)) { + throw new UniFFITypeError(`Expected 'SimpleRec', found '${typeof value}'`); + } + try { + FfiConverterUInt8.checkType(value.a); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".a"); + } + throw e; + } + } +} +/** + * ComplexRec + */ +export class ComplexRec { + constructor( + { + fieldU8, + fieldI8, + fieldU16, + fieldI16, + fieldU32, + fieldI32, + fieldU64, + fieldI64, + fieldF32, + fieldF64, + fieldString= "DefaultString", + fieldRec + } = { + fieldU8: undefined, + fieldI8: undefined, + fieldU16: undefined, + fieldI16: undefined, + fieldU32: undefined, + fieldI32: undefined, + fieldU64: undefined, + fieldI64: undefined, + fieldF32: undefined, + fieldF64: undefined, + fieldString: undefined, + fieldRec: undefined + } + ) { + try { + FfiConverterUInt8.checkType(fieldU8) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldU8"); + } + throw e; + } + try { + FfiConverterInt8.checkType(fieldI8) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldI8"); + } + throw e; + } + try { + FfiConverterUInt16.checkType(fieldU16) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldU16"); + } + throw e; + } + try { + FfiConverterInt16.checkType(fieldI16) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldI16"); + } + throw e; + } + try { + FfiConverterUInt32.checkType(fieldU32) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldU32"); + } + throw e; + } + try { + FfiConverterInt32.checkType(fieldI32) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldI32"); + } + throw e; + } + try { + FfiConverterUInt64.checkType(fieldU64) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldU64"); + } + throw e; + } + try { + FfiConverterInt64.checkType(fieldI64) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldI64"); + } + throw e; + } + try { + FfiConverterFloat32.checkType(fieldF32) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldF32"); + } + throw e; + } + try { + FfiConverterFloat64.checkType(fieldF64) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldF64"); + } + throw e; + } + try { + FfiConverterString.checkType(fieldString) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldString"); + } + throw e; + } + try { + FfiConverterTypeSimpleRec.checkType(fieldRec) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("fieldRec"); + } + throw e; + } + /** + * fieldU8 + */ + this.fieldU8 = fieldU8; + /** + * fieldI8 + */ + this.fieldI8 = fieldI8; + /** + * fieldU16 + */ + this.fieldU16 = fieldU16; + /** + * fieldI16 + */ + this.fieldI16 = fieldI16; + /** + * fieldU32 + */ + this.fieldU32 = fieldU32; + /** + * fieldI32 + */ + this.fieldI32 = fieldI32; + /** + * fieldU64 + */ + this.fieldU64 = fieldU64; + /** + * fieldI64 + */ + this.fieldI64 = fieldI64; + /** + * fieldF32 + */ + this.fieldF32 = fieldF32; + /** + * fieldF64 + */ + this.fieldF64 = fieldF64; + /** + * fieldString + */ + this.fieldString = fieldString; + /** + * fieldRec + */ + this.fieldRec = fieldRec; + } + + equals(other) { + return ( + this.fieldU8 == other.fieldU8 + && this.fieldI8 == other.fieldI8 + && this.fieldU16 == other.fieldU16 + && this.fieldI16 == other.fieldI16 + && this.fieldU32 == other.fieldU32 + && this.fieldI32 == other.fieldI32 + && this.fieldU64 == other.fieldU64 + && this.fieldI64 == other.fieldI64 + && this.fieldF32 == other.fieldF32 + && this.fieldF64 == other.fieldF64 + && this.fieldString == other.fieldString + && this.fieldRec.equals(other.fieldRec) + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeComplexRec extends FfiConverterArrayBuffer { + static read(dataStream) { + return new ComplexRec({ + fieldU8: FfiConverterUInt8.read(dataStream), + fieldI8: FfiConverterInt8.read(dataStream), + fieldU16: FfiConverterUInt16.read(dataStream), + fieldI16: FfiConverterInt16.read(dataStream), + fieldU32: FfiConverterUInt32.read(dataStream), + fieldI32: FfiConverterInt32.read(dataStream), + fieldU64: FfiConverterUInt64.read(dataStream), + fieldI64: FfiConverterInt64.read(dataStream), + fieldF32: FfiConverterFloat32.read(dataStream), + fieldF64: FfiConverterFloat64.read(dataStream), + fieldString: FfiConverterString.read(dataStream), + fieldRec: FfiConverterTypeSimpleRec.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterUInt8.write(dataStream, value.fieldU8); + FfiConverterInt8.write(dataStream, value.fieldI8); + FfiConverterUInt16.write(dataStream, value.fieldU16); + FfiConverterInt16.write(dataStream, value.fieldI16); + FfiConverterUInt32.write(dataStream, value.fieldU32); + FfiConverterInt32.write(dataStream, value.fieldI32); + FfiConverterUInt64.write(dataStream, value.fieldU64); + FfiConverterInt64.write(dataStream, value.fieldI64); + FfiConverterFloat32.write(dataStream, value.fieldF32); + FfiConverterFloat64.write(dataStream, value.fieldF64); + FfiConverterString.write(dataStream, value.fieldString); + FfiConverterTypeSimpleRec.write(dataStream, value.fieldRec); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterUInt8.computeSize(value.fieldU8); + totalSize += FfiConverterInt8.computeSize(value.fieldI8); + totalSize += FfiConverterUInt16.computeSize(value.fieldU16); + totalSize += FfiConverterInt16.computeSize(value.fieldI16); + totalSize += FfiConverterUInt32.computeSize(value.fieldU32); + totalSize += FfiConverterInt32.computeSize(value.fieldI32); + totalSize += FfiConverterUInt64.computeSize(value.fieldU64); + totalSize += FfiConverterInt64.computeSize(value.fieldI64); + totalSize += FfiConverterFloat32.computeSize(value.fieldF32); + totalSize += FfiConverterFloat64.computeSize(value.fieldF64); + totalSize += FfiConverterString.computeSize(value.fieldString); + totalSize += FfiConverterTypeSimpleRec.computeSize(value.fieldRec); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof ComplexRec)) { + throw new UniFFITypeError(`Expected 'ComplexRec', found '${typeof value}'`); + } + try { + FfiConverterUInt8.checkType(value.fieldU8); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldU8"); + } + throw e; + } + try { + FfiConverterInt8.checkType(value.fieldI8); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldI8"); + } + throw e; + } + try { + FfiConverterUInt16.checkType(value.fieldU16); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldU16"); + } + throw e; + } + try { + FfiConverterInt16.checkType(value.fieldI16); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldI16"); + } + throw e; + } + try { + FfiConverterUInt32.checkType(value.fieldU32); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldU32"); + } + throw e; + } + try { + FfiConverterInt32.checkType(value.fieldI32); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldI32"); + } + throw e; + } + try { + FfiConverterUInt64.checkType(value.fieldU64); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldU64"); + } + throw e; + } + try { + FfiConverterInt64.checkType(value.fieldI64); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldI64"); + } + throw e; + } + try { + FfiConverterFloat32.checkType(value.fieldF32); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldF32"); + } + throw e; + } + try { + FfiConverterFloat64.checkType(value.fieldF64); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldF64"); + } + throw e; + } + try { + FfiConverterString.checkType(value.fieldString); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldString"); + } + throw e; + } + try { + FfiConverterTypeSimpleRec.checkType(value.fieldRec); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".fieldRec"); + } + throw e; + } + } +} +/** + * RecWithDefault + */ +export class RecWithDefault { + constructor( + { + a= 42 + } = { + a: undefined + } + ) { + try { + FfiConverterUInt8.checkType(a) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("a"); + } + throw e; + } + /** + * a + */ + this.a = a; + } + + equals(other) { + return ( + this.a == other.a + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeRecWithDefault extends FfiConverterArrayBuffer { + static read(dataStream) { + return new RecWithDefault({ + a: FfiConverterUInt8.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterUInt8.write(dataStream, value.a); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterUInt8.computeSize(value.a); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof RecWithDefault)) { + throw new UniFFITypeError(`Expected 'RecWithDefault', found '${typeof value}'`); + } + try { + FfiConverterUInt8.checkType(value.a); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".a"); + } + throw e; + } + } +} +/** + * TestInterface + */ +export class TestInterface { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + value) { + + FfiConverterUInt32.checkType(value); + const result = UniFFIScaffolding.callSync( + 155, // uniffi_uniffi_bindings_tests_fn_constructor_testinterface_new + FfiConverterUInt32.lower(value), + ) + return handleRustResult( + result, + FfiConverterTypeTestInterface.lift.bind(FfiConverterTypeTestInterface), + null, + ) + } + + /** + * getValue + */ + getValue() { + + const result = UniFFIScaffolding.callSync( + 156, // uniffi_uniffi_bindings_tests_fn_method_testinterface_get_value + FfiConverterTypeTestInterface.lower(this), + ) + return handleRustResult( + result, + FfiConverterUInt32.lift.bind(FfiConverterUInt32), + null, + ) + } + + /** + * Get the current reference count for this object + * + * The count does not include the extra reference needed to call this method. + */ + refCount() { + + const result = UniFFIScaffolding.callSync( + 157, // uniffi_uniffi_bindings_tests_fn_method_testinterface_ref_count + FfiConverterTypeTestInterface.lower(this), + ) + return handleRustResult( + result, + FfiConverterUInt32.lift.bind(FfiConverterUInt32), + null, + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeTestInterface extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new TestInterface(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'TestInterface' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(14)); + } + + static write(dataStream, value) { + dataStream.writePointer(14, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +/** + * TwoTestInterfaces + */ +export class TwoTestInterfaces { + constructor( + { + first, + second + } = { + first: undefined, + second: undefined + } + ) { + try { + FfiConverterTypeTestInterface.checkType(first) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("first"); + } + throw e; + } + try { + FfiConverterTypeTestInterface.checkType(second) + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("second"); + } + throw e; + } + /** + * first + */ + this.first = first; + /** + * second + */ + this.second = second; + } + + equals(other) { + return ( + this.first == other.first + && this.second == other.second + ) + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeTwoTestInterfaces extends FfiConverterArrayBuffer { + static read(dataStream) { + return new TwoTestInterfaces({ + first: FfiConverterTypeTestInterface.read(dataStream), + second: FfiConverterTypeTestInterface.read(dataStream), + }); + } + static write(dataStream, value) { + FfiConverterTypeTestInterface.write(dataStream, value.first); + FfiConverterTypeTestInterface.write(dataStream, value.second); + } + + static computeSize(value) { + let totalSize = 0; + totalSize += FfiConverterTypeTestInterface.computeSize(value.first); + totalSize += FfiConverterTypeTestInterface.computeSize(value.second); + return totalSize + } + + static checkType(value) { + super.checkType(value); + if (!(value instanceof TwoTestInterfaces)) { + throw new UniFFITypeError(`Expected 'TwoTestInterfaces', found '${typeof value}'`); + } + try { + FfiConverterTypeTestInterface.checkType(value.first); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".first"); + } + throw e; + } + try { + FfiConverterTypeTestInterface.checkType(value.second); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(".second"); + } + throw e; + } + } +} + +/** + * EnumNoData + */ +export const EnumNoData = { + /** + * A + */ + A: 1, + /** + * B + */ + B: 2, + /** + * C + */ + C: 3, +}; +Object.freeze(EnumNoData); + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeEnumNoData extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return EnumNoData.A + case 2: + return EnumNoData.B + case 3: + return EnumNoData.C + default: + throw new UniFFITypeError("Unknown EnumNoData variant"); + } + } + + static write(dataStream, value) { + if (value === EnumNoData.A) { + dataStream.writeInt32(1); + return; + } + if (value === EnumNoData.B) { + dataStream.writeInt32(2); + return; + } + if (value === EnumNoData.C) { + dataStream.writeInt32(3); + return; + } + throw new UniFFITypeError("Unknown EnumNoData variant"); + } + + static computeSize(value) { + return 4; + } + + static checkType(value) { + if (!Number.isInteger(value) || value < 1 || value > 3) { + throw new UniFFITypeError(`${value} is not a valid value for EnumNoData`); + } + } +} + +/** + * EnumWithData + */ +export class EnumWithData {} +/** + * A + */ +EnumWithData.A = class extends EnumWithData{ + constructor( + value + ) { + super(); + this.value = value; + } +} +/** + * B + */ +EnumWithData.B = class extends EnumWithData{ + constructor( + value + ) { + super(); + this.value = value; + } +} +/** + * C + */ +EnumWithData.C = class extends EnumWithData{ + constructor( + ) { + super(); + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeEnumWithData extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new EnumWithData.A( + FfiConverterUInt8.read(dataStream) + ); + case 2: + return new EnumWithData.B( + FfiConverterString.read(dataStream) + ); + case 3: + return new EnumWithData.C( + ); + default: + throw new UniFFITypeError("Unknown EnumWithData variant"); + } + } + + static write(dataStream, value) { + if (value instanceof EnumWithData.A) { + dataStream.writeInt32(1); + FfiConverterUInt8.write(dataStream, value.value); + return; + } + if (value instanceof EnumWithData.B) { + dataStream.writeInt32(2); + FfiConverterString.write(dataStream, value.value); + return; + } + if (value instanceof EnumWithData.C) { + dataStream.writeInt32(3); + return; + } + throw new UniFFITypeError("Unknown EnumWithData variant"); + } + + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof EnumWithData.A) { + totalSize += FfiConverterUInt8.computeSize(value.value); + return totalSize; + } + if (value instanceof EnumWithData.B) { + totalSize += FfiConverterString.computeSize(value.value); + return totalSize; + } + if (value instanceof EnumWithData.C) { + return totalSize; + } + throw new UniFFITypeError("Unknown EnumWithData variant"); + } + + static checkType(value) { + if (!(value instanceof EnumWithData)) { + throw new UniFFITypeError(`${value} is not a subclass instance of EnumWithData`); + } + } +} + +/** + * ComplexEnum + */ +export class ComplexEnum {} +/** + * A + */ +ComplexEnum.A = class extends ComplexEnum{ + constructor( + value + ) { + super(); + this.value = value; + } +} +/** + * B + */ +ComplexEnum.B = class extends ComplexEnum{ + constructor( + value + ) { + super(); + this.value = value; + } +} +/** + * C + */ +ComplexEnum.C = class extends ComplexEnum{ + constructor( + value + ) { + super(); + this.value = value; + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeComplexEnum extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new ComplexEnum.A( + FfiConverterTypeEnumNoData.read(dataStream) + ); + case 2: + return new ComplexEnum.B( + FfiConverterTypeEnumWithData.read(dataStream) + ); + case 3: + return new ComplexEnum.C( + FfiConverterTypeSimpleRec.read(dataStream) + ); + default: + throw new UniFFITypeError("Unknown ComplexEnum variant"); + } + } + + static write(dataStream, value) { + if (value instanceof ComplexEnum.A) { + dataStream.writeInt32(1); + FfiConverterTypeEnumNoData.write(dataStream, value.value); + return; + } + if (value instanceof ComplexEnum.B) { + dataStream.writeInt32(2); + FfiConverterTypeEnumWithData.write(dataStream, value.value); + return; + } + if (value instanceof ComplexEnum.C) { + dataStream.writeInt32(3); + FfiConverterTypeSimpleRec.write(dataStream, value.value); + return; + } + throw new UniFFITypeError("Unknown ComplexEnum variant"); + } + + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof ComplexEnum.A) { + totalSize += FfiConverterTypeEnumNoData.computeSize(value.value); + return totalSize; + } + if (value instanceof ComplexEnum.B) { + totalSize += FfiConverterTypeEnumWithData.computeSize(value.value); + return totalSize; + } + if (value instanceof ComplexEnum.C) { + totalSize += FfiConverterTypeSimpleRec.computeSize(value.value); + return totalSize; + } + throw new UniFFITypeError("Unknown ComplexEnum variant"); + } + + static checkType(value) { + if (!(value instanceof ComplexEnum)) { + throw new UniFFITypeError(`${value} is not a subclass instance of ComplexEnum`); + } + } +} + +/** + * Error enum + */ +export class TestError extends Error {} + + +/** + * Failure1 + */ +export class Failure1 extends TestError { + + constructor( + ...params + ) { + super(...params); + } + toString() { + return `Failure1: ${super.toString()}` + } +} + +/** + * Failure2 + */ +export class Failure2 extends TestError { + + constructor( + data, + ...params + ) { + const message = `data: ${ data }`; + super(message, ...params); + this.data = data; + } + toString() { + return `Failure2: ${super.toString()}` + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeTestError extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new Failure1( + ); + case 2: + return new Failure2( + FfiConverterString.read(dataStream) + ); + default: + throw new UniFFITypeError("Unknown TestError variant"); + } + } + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof Failure1) { + return totalSize; + } + if (value instanceof Failure2) { + totalSize += FfiConverterString.computeSize(value.data); + return totalSize; + } + throw new UniFFITypeError("Unknown TestError variant"); + } + static write(dataStream, value) { + if (value instanceof Failure1) { + dataStream.writeInt32(1); + return; + } + if (value instanceof Failure2) { + dataStream.writeInt32(2); + FfiConverterString.write(dataStream, value.data); + return; + } + throw new UniFFITypeError("Unknown TestError variant"); + } + + static errorClass = TestError; +} + +/** + * Flat error enum + * + * The associated data for this won't be across the FFI. Flat errors are mostly just a historical + * artifact, but there are some use-cases for them -- for example variants that wrap errors from + * other crates. + */ +export class TestFlatError extends Error {} + + +/** + * Here's an example of a variant that only works with a flat error, `io::Error` is not + * UniFFI compatible and can't be passed across the FFI. + */ +export class IoError extends TestFlatError { + + constructor(message, ...params) { + super(...params); + this.message = message; + } + toString() { + return `IoError: ${super.toString()}` + } +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeTestFlatError extends FfiConverterArrayBuffer { + static read(dataStream) { + switch (dataStream.readInt32()) { + case 1: + return new IoError(FfiConverterString.read(dataStream)); + default: + throw new UniFFITypeError("Unknown TestFlatError variant"); + } + } + static computeSize(value) { + // Size of the Int indicating the variant + let totalSize = 4; + if (value instanceof IoError) { + return totalSize; + } + throw new UniFFITypeError("Unknown TestFlatError variant"); + } + static write(dataStream, value) { + if (value instanceof IoError) { + dataStream.writeInt32(1); + return; + } + throw new UniFFITypeError("Unknown TestFlatError variant"); + } + + static errorClass = TestFlatError; +} +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeHandle extends FfiConverter { + static lift(buf) { + return FfiConverterUInt64.lift(buf); + } + + static lower(buf) { + return FfiConverterUInt64.lower(buf); + } + + static write(dataStream, value) { + FfiConverterUInt64.write(dataStream, value); + } + + static read(buf) { + return FfiConverterUInt64.read(buf); + } + + static computeSize(value) { + return FfiConverterUInt64.computeSize(value); + } +} + +// TODO: We should also allow JS to customize the type eventually. +/** + * AsyncInterface + */ +export class AsyncInterface { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init( + name) { + + FfiConverterString.checkType(name); + const result = UniFFIScaffolding.callSync( + 158, // uniffi_uniffi_bindings_tests_fn_constructor_asyncinterface_new + FfiConverterString.lower(name), + ) + return handleRustResult( + result, + FfiConverterTypeAsyncInterface.lift.bind(FfiConverterTypeAsyncInterface), + null, + ) + } + + /** + * name + */ + async name() { + + const result = await UniFFIScaffolding.callAsync( + 159, // uniffi_uniffi_bindings_tests_fn_method_asyncinterface_name + FfiConverterTypeAsyncInterface.lower(this), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeAsyncInterface extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new AsyncInterface(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'AsyncInterface' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(15)); + } + + static write(dataStream, value) { + dataStream.writePointer(15, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +/** + * ComplexMethods + */ +export class ComplexMethods { + // Use `init` to instantiate this class. + // DO NOT USE THIS CONSTRUCTOR DIRECTLY + constructor(opts) { + if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { + throw new UniFFIError("Attempting to construct an int using the JavaScript constructor directly" + + "Please use a UDL defined constructor, or the init function for the primary constructor") + } + if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { + throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") + } + this[uniffiObjectPtr] = opts[constructUniffiObject]; + } + + static init() { + + const result = UniFFIScaffolding.callSync( + 160, // uniffi_uniffi_bindings_tests_fn_constructor_complexmethods_new + ) + return handleRustResult( + result, + FfiConverterTypeComplexMethods.lift.bind(FfiConverterTypeComplexMethods), + null, + ) + } + + /** + * methodWithDefault + */ + methodWithDefault( + arg = "DEFAULT") { + + FfiConverterString.checkType(arg); + const result = UniFFIScaffolding.callSync( + 161, // uniffi_uniffi_bindings_tests_fn_method_complexmethods_method_with_default + FfiConverterTypeComplexMethods.lower(this), + FfiConverterString.lower(arg), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, + ) + } + + /** + * methodWithMultiWordArg + */ + methodWithMultiWordArg( + theArgument) { + + FfiConverterString.checkType(theArgument); + const result = UniFFIScaffolding.callSync( + 162, // uniffi_uniffi_bindings_tests_fn_method_complexmethods_method_with_multi_word_arg + FfiConverterTypeComplexMethods.lower(this), + FfiConverterString.lower(theArgument), + ) + return handleRustResult( + result, + FfiConverterString.lift.bind(FfiConverterString), + null, + ) + } + +} + +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeComplexMethods extends FfiConverter { + static lift(value) { + const opts = {}; + opts[constructUniffiObject] = value; + return new ComplexMethods(opts); + } + + static lower(value) { + const ptr = value[uniffiObjectPtr]; + if (!(ptr instanceof UniFFIPointer)) { + throw new UniFFITypeError("Object is not a 'ComplexMethods' instance"); + } + return ptr; + } + + static read(dataStream) { + return this.lift(dataStream.readPointer(16)); + } + + static write(dataStream, value) { + dataStream.writePointer(16, this.lower(value)); + } + + static computeSize(value) { + return 8; + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterTypeTestCallbackInterface extends FfiConverter { + static lower(callbackObj) { + return uniffiCallbackHandlerTestCallbackInterface.storeCallbackObj(callbackObj) + } + + static lift(handleId) { + return uniffiCallbackHandlerTestCallbackInterface.getCallbackObj(handleId) + } + + static read(dataStream) { + return this.lift(dataStream.readInt64()) + } + + static write(dataStream, callbackObj) { + dataStream.writeInt64(this.lower(callbackObj)) + } + + static computeSize(callbackObj) { + return 8; + } +} + +const uniffiCallbackHandlerTestCallbackInterface = new UniFFICallbackHandler( + "TestCallbackInterface", + 3, + [ + new UniFFICallbackMethodHandler( + "getValue", + [ + ], + ), + ] +); + +// Allow the shutdown-related functionality to be tested in the unit tests +UnitTestObjs.uniffiCallbackHandlerTestCallbackInterface = uniffiCallbackHandlerTestCallbackInterface; +// Export the FFIConverter object to make external types work. +export class FfiConverterMapStringString extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const map = new Map(); + for (let i = 0; i < len; i++) { + const key = FfiConverterString.read(dataStream); + const value = FfiConverterString.read(dataStream); + map.set(key, value); + } + + return map; + } + + static write(dataStream, map) { + dataStream.writeInt32(map.size); + for (const [key, value] of map) { + FfiConverterString.write(dataStream, key); + FfiConverterString.write(dataStream, value); + } + } + + static computeSize(map) { + // The size of the length + let size = 4; + for (const [key, value] of map) { + size += FfiConverterString.computeSize(key); + size += FfiConverterString.computeSize(value); + } + return size; + } + + static checkType(map) { + for (const [key, value] of map) { + try { + FfiConverterString.checkType(key); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("(key)"); + } + throw e; + } + + try { + FfiConverterString.checkType(value); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${key}]`); + } + throw e; + } + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceUInt32 extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterUInt32.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterUInt32.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterUInt32.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterUInt32.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterBoolean extends FfiConverter { + static computeSize(_value) { + return 1; + } + static lift(value) { + return value == 1; + } + static lower(value) { + if (value) { + return 1; + } else { + return 0; + } + } + static write(dataStream, value) { + dataStream.writeUint8(this.lower(value)) + } + static read(dataStream) { + return this.lift(dataStream.readUint8()) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterMapStringUInt32 extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const map = new Map(); + for (let i = 0; i < len; i++) { + const key = FfiConverterString.read(dataStream); + const value = FfiConverterUInt32.read(dataStream); + map.set(key, value); + } + + return map; + } + + static write(dataStream, map) { + dataStream.writeInt32(map.size); + for (const [key, value] of map) { + FfiConverterString.write(dataStream, key); + FfiConverterUInt32.write(dataStream, value); + } + } + + static computeSize(map) { + // The size of the length + let size = 4; + for (const [key, value] of map) { + size += FfiConverterString.computeSize(key); + size += FfiConverterUInt32.computeSize(value); + } + return size; + } + + static checkType(map) { + for (const [key, value] of map) { + try { + FfiConverterString.checkType(key); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart("(key)"); + } + throw e; + } + + try { + FfiConverterUInt32.checkType(value); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${key}]`); + } + throw e; + } + } + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterSequenceMapStringUInt32 extends FfiConverterArrayBuffer { + static read(dataStream) { + const len = dataStream.readInt32(); + const arr = []; + for (let i = 0; i < len; i++) { + arr.push(FfiConverterMapStringUInt32.read(dataStream)); + } + return arr; + } + + static write(dataStream, value) { + dataStream.writeInt32(value.length); + value.forEach((innerValue) => { + FfiConverterMapStringUInt32.write(dataStream, innerValue); + }) + } + + static computeSize(value) { + // The size of the length + let size = 4; + for (const innerValue of value) { + size += FfiConverterMapStringUInt32.computeSize(innerValue); + } + return size; + } + + static checkType(value) { + if (!Array.isArray(value)) { + throw new UniFFITypeError(`${value} is not an array`); + } + value.forEach((innerValue, idx) => { + try { + FfiConverterMapStringUInt32.checkType(innerValue); + } catch (e) { + if (e instanceof UniFFITypeError) { + e.addItemDescriptionPart(`[${idx}]`); + } + throw e; + } + }) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalSequenceMapStringUInt32 extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterSequenceMapStringUInt32.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterSequenceMapStringUInt32.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterSequenceMapStringUInt32.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterSequenceMapStringUInt32.computeSize(value) + } +} +// Export the FFIConverter object to make external types work. +export class FfiConverterOptionalUInt32 extends FfiConverterArrayBuffer { + static checkType(value) { + if (value !== undefined && value !== null) { + FfiConverterUInt32.checkType(value) + } + } + + static read(dataStream) { + const code = dataStream.readUint8(0); + switch (code) { + case 0: + return null + case 1: + return FfiConverterUInt32.read(dataStream) + default: + throw new UniFFIError(`Unexpected code: ${code}`); + } + } + + static write(dataStream, value) { + if (value === null || value === undefined) { + dataStream.writeUint8(0); + return; + } + dataStream.writeUint8(1); + FfiConverterUInt32.write(dataStream, value) + } + + static computeSize(value) { + if (value === null || value === undefined) { + return 1; + } + return 1 + FfiConverterUInt32.computeSize(value) + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustRefcounts.sys.mjs b/toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTestsExternalTypes.sys.mjs similarity index 67% rename from toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustRefcounts.sys.mjs rename to toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTestsExternalTypes.sys.mjs index be05d7183ccf..9ee2bf61367c 100644 --- a/toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated/RustRefcounts.sys.mjs +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTestsExternalTypes.sys.mjs @@ -1,9 +1,7 @@ // This file was autogenerated by the `uniffi-bindgen-gecko-js` crate. // Trust me, you don't want to mess with it! -import { UniFFITypeError } from "resource://gre/modules/UniFFI.sys.mjs"; - - +import { UniFFITypeError } from "moz-src:///toolkit/components/uniffi-js/js/UniFFI.sys.mjs"; // Objects intended to be used in the unit tests export var UnitTestObjs = {}; @@ -171,25 +169,22 @@ class ArrayBufferDataStream { }) } - // Reads a SingletonObject pointer from the data stream + // Reads a pointer from the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - readPointerSingletonObject() { - const pointerId = 17; // refcounts:SingletonObject + readPointer(pointerId) { const res = UniFFIScaffolding.readPointer(pointerId, this.dataView.buffer, this.pos); this.pos += 8; return res; } - // Writes a SingletonObject pointer into the data stream + // Writes a pointer into the data stream // UniFFI Pointers are **always** 8 bytes long. That is enforced // by the C++ and Rust Scaffolding code. - writePointerSingletonObject(value) { - const pointerId = 17; // refcounts:SingletonObject + writePointer(pointerId, value) { UniFFIScaffolding.writePointer(pointerId, value, this.dataView.buffer, this.pos); this.pos += 8; } - } function handleRustResult(result, liftCallback, liftErrCallback) { @@ -287,20 +282,143 @@ class FfiConverterArrayBuffer extends FfiConverter { const uniffiObjectPtr = Symbol("uniffiObjectPtr"); const constructUniffiObject = Symbol("constructUniffiObject"); UnitTestObjs.uniffiObjectPtr = uniffiObjectPtr; +/** + * roundtripExtCustomType + */ +export function roundtripExtCustomType( + custom) { + +FfiConverterTypeHandle.checkType(custom); +const result = UniFFIScaffolding.callSync( + 163, // uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_custom_type + FfiConverterTypeHandle.lower(custom), +) +return handleRustResult( + result, + FfiConverterTypeHandle.lift.bind(FfiConverterTypeHandle), + null, +) +} + +/** + * roundtripExtEnum + */ +export function roundtripExtEnum( + en) { + +FfiConverterTypeEnumWithData.checkType(en); +const result = UniFFIScaffolding.callSync( + 164, // uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_enum + FfiConverterTypeEnumWithData.lower(en), +) +return handleRustResult( + result, + FfiConverterTypeEnumWithData.lift.bind(FfiConverterTypeEnumWithData), + null, +) +} + +/** + * roundtripExtInterface + */ +export function roundtripExtInterface( + int) { + +FfiConverterTypeTestInterface.checkType(int); +const result = UniFFIScaffolding.callSync( + 165, // uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_interface + FfiConverterTypeTestInterface.lower(int), +) +return handleRustResult( + result, + FfiConverterTypeTestInterface.lift.bind(FfiConverterTypeTestInterface), + null, +) +} + +/** + * roundtripExtRecord + */ +export function roundtripExtRecord( + rec) { + +FfiConverterTypeSimpleRec.checkType(rec); +const result = UniFFIScaffolding.callSync( + 166, // uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_record + FfiConverterTypeSimpleRec.lower(rec), +) +return handleRustResult( + result, + FfiConverterTypeSimpleRec.lift.bind(FfiConverterTypeSimpleRec), + null, +) +} + + +import { + FfiConverterTypeHandle, +} from "./RustUniffiBindingsTests.sys.mjs"; // Export the FFIConverter object to make external types work. -export class FfiConverterI32 extends FfiConverter { +export { FfiConverterTypeHandle }; +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt64 extends FfiConverter { + static checkType(value) { + super.checkType(value); + if (!Number.isSafeInteger(value)) { + throw new UniFFITypeError(`${value} exceeds the safe integer bounds`); + } + if (value < 0) { + throw new UniFFITypeError(`${value} exceeds the U64 bounds`); + } + } + static computeSize(_value) { + return 8; + } + static lift(value) { + return value; + } + static lower(value) { + return value; + } + static write(dataStream, value) { + dataStream.writeUint64(value) + } + static read(dataStream) { + return dataStream.readUint64() + } +} +import { + FfiConverterTypeEnumWithData, +} from "./RustUniffiBindingsTests.sys.mjs"; + +// Export the FFIConverter object to make external types work. +export { FfiConverterTypeEnumWithData }; +import { + FfiConverterTypeTestInterface, +} from "./RustUniffiBindingsTests.sys.mjs"; + +// Export the FFIConverter object to make external types work. +export { FfiConverterTypeTestInterface }; +import { + FfiConverterTypeSimpleRec, +} from "./RustUniffiBindingsTests.sys.mjs"; + +// Export the FFIConverter object to make external types work. +export { FfiConverterTypeSimpleRec }; +// Export the FFIConverter object to make external types work. +export class FfiConverterUInt8 extends FfiConverter { static checkType(value) { super.checkType(value); if (!Number.isInteger(value)) { throw new UniFFITypeError(`${value} is not an integer`); } - if (value < -2147483648 || value > 2147483647) { - throw new UniFFITypeError(`${value} exceeds the I32 bounds`); + if (value < 0 || value > 256) { + throw new UniFFITypeError(`${value} exceeds the U8 bounds`); } } static computeSize(_value) { - return 4; + return 1; } static lift(value) { return value; @@ -309,138 +427,9 @@ export class FfiConverterI32 extends FfiConverter { return value; } static write(dataStream, value) { - dataStream.writeInt32(value) + dataStream.writeUint8(value) } static read(dataStream) { - return dataStream.readInt32() + return dataStream.readUint8() } } - -// Export the FFIConverter object to make external types work. -export class FfiConverterString extends FfiConverter { - static checkType(value) { - super.checkType(value); - if (typeof value !== "string") { - throw new UniFFITypeError(`${value} is not a string`); - } - } - - static lift(buf) { - const utf8Arr = new Uint8Array(buf); - return lazy.decoder.decode(utf8Arr); - } - static lower(value) { - return lazy.encoder.encode(value).buffer; - } - - static write(dataStream, value) { - dataStream.writeString(value); - } - - static read(dataStream) { - return dataStream.readString(); - } - - static computeSize(value) { - return 4 + lazy.encoder.encode(value).length - } -} - -/** - * SingletonObject - */ -export class SingletonObject { - // Use `init` to instantiate this class. - // DO NOT USE THIS CONSTRUCTOR DIRECTLY - constructor(opts) { - if (!Object.prototype.hasOwnProperty.call(opts, constructUniffiObject)) { - throw new UniFFIError("Attempting to construct an object using the JavaScript constructor directly" + - "Please use a UDL defined constructor, or the init function for the primary constructor") - } - if (!(opts[constructUniffiObject] instanceof UniFFIPointer)) { - throw new UniFFIError("Attempting to create a UniFFI object with a pointer that is not an instance of UniFFIPointer") - } - this[uniffiObjectPtr] = opts[constructUniffiObject]; - } - - /** - * method - */ - method() { - const liftResult = (result) => undefined; - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 157, // refcounts:uniffi_uniffi_fixture_refcounts_fn_method_singletonobject_method - FfiConverterTypeSingletonObject.lower(this), - ) - } - return handleRustResult(functionCall(), liftResult, liftError); - } - -} - -// Export the FFIConverter object to make external types work. -export class FfiConverterTypeSingletonObject extends FfiConverter { - static lift(value) { - const opts = {}; - opts[constructUniffiObject] = value; - return new SingletonObject(opts); - } - - static lower(value) { - const ptr = value[uniffiObjectPtr]; - if (!(ptr instanceof UniFFIPointer)) { - throw new UniFFITypeError("Object is not a 'SingletonObject' instance"); - } - return ptr; - } - - static read(dataStream) { - return this.lift(dataStream.readPointerSingletonObject()); - } - - static write(dataStream, value) { - dataStream.writePointerSingletonObject(value[uniffiObjectPtr]); - } - - static computeSize(value) { - return 8; - } -} - - - - - -/** - * getJsRefcount - * @returns {number} - */ -export function getJsRefcount() { - - const liftResult = (result) => FfiConverterI32.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 155, // refcounts:uniffi_uniffi_fixture_refcounts_fn_func_get_js_refcount - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} - -/** - * getSingleton - * @returns {SingletonObject} - */ -export function getSingleton() { - - const liftResult = (result) => FfiConverterTypeSingletonObject.lift(result); - const liftError = null; - const functionCall = () => { - return UniFFIScaffolding.callSync( - 156, // refcounts:uniffi_uniffi_fixture_refcounts_fn_func_get_singleton - ) - } - return handleRustResult(functionCall(), liftResult, liftError); -} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/moz.build b/toolkit/components/uniffi-bindgen-gecko-js/tests/moz.build new file mode 100644 index 000000000000..bcb2fe98f4e6 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/moz.build @@ -0,0 +1,14 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +FINAL_LIBRARY = "xul" + +MOZ_SRC_FILES += [ + "generated/RustUniffiBindingsTests.sys.mjs", + "generated/RustUniffiBindingsTestsExternalTypes.sys.mjs", +] + +XPCSHELL_TESTS_MANIFESTS += ["xpcshell/xpcshell.toml"] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_callback_interfaces.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_callback_interfaces.js new file mode 100644 index 000000000000..6437ef2f5cde --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_callback_interfaces.js @@ -0,0 +1,35 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { invokeTestCallbackInterfaceMethod } = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +// Test fire-and-forget callbacks interfaces. This schedule a callack interface call, but don't +// wait for a return. This is all we can currently test + +add_task(async function testFireAndForgetCallbackInterfaces() { + /** + * + */ + class Callback { + constructor(value) { + this.value = value; + this.getValueCount = 0; + } + + getValue() { + this.getValueCount += 1; + return this.value; + } + } + + const cbi = new Callback(42); + Assert.equal(cbi.getValueCount, 0); + invokeTestCallbackInterfaceMethod(cbi); + do_test_pending(); + await do_timeout(100, () => { + Assert.equal(cbi.getValueCount, 1); + do_test_finished(); + }); +}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_complex_fns.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_complex_fns.js new file mode 100644 index 000000000000..012666f42c2e --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_complex_fns.js @@ -0,0 +1,22 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { funcWithDefault, funcWithMultiWordArg, ComplexMethods } = + ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" + ); + +const complexMethods = ComplexMethods.init(); +Assert.stringMatches( + complexMethods.methodWithMultiWordArg.toString(), + /theArgument/ +); + +Assert.equal(complexMethods.methodWithDefault(), "DEFAULT"); +Assert.equal(complexMethods.methodWithDefault("NON-DEFAULT"), "NON-DEFAULT"); + +Assert.equal(funcWithDefault(), "DEFAULT"); +Assert.equal(funcWithDefault("NON-DEFAULT"), "NON-DEFAULT"); + +// Test that argument names are in camelCase +Assert.stringMatches(funcWithMultiWordArg.toString(), /theArgument/); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_compound_types.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_compound_types.js new file mode 100644 index 000000000000..f63d5b76221e --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_compound_types.js @@ -0,0 +1,42 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { + roundtripOption, + roundtripVec, + roundtripHashMap, + roundtripComplexCompound, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +Assert.equal(roundtripOption(42), 42); +Assert.equal(roundtripOption(null), null); +Assert.deepEqual(roundtripVec([1, 2, 3]), [1, 2, 3]); +Assert.deepEqual( + roundtripHashMap( + new Map([ + ["a", 1], + ["b", 2], + ]) + ), + new Map([ + ["a", 1], + ["b", 2], + ]) +); +Assert.deepEqual( + roundtripComplexCompound([ + new Map([ + ["a", 1], + ["b", 2], + ]), + ]), + [ + new Map([ + ["a", 1], + ["b", 2], + ]), + ] +); +Assert.equal(roundtripComplexCompound(null), null); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_custom_types.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_custom_types.js new file mode 100644 index 000000000000..1c965ec0e05a --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_custom_types.js @@ -0,0 +1,12 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { roundtripCustomType } = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +// The custom type here is a Handle, that is converted to an int on the JS side +Assert.equal(roundtripCustomType(100), 100); + +// TODO: implement the other half of this -- allow the int to be wrapped into a Handle on the JS +// side. diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_enums.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_enums.js new file mode 100644 index 000000000000..104d275641df --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_enums.js @@ -0,0 +1,42 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { + roundtripEnumNoData, + roundtripEnumWithData, + roundtripComplexEnum, + EnumNoData, + EnumWithData, + ComplexEnum, + SimpleRec, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +Assert.deepEqual(roundtripEnumNoData(EnumNoData.B), EnumNoData.B); + +Assert.deepEqual( + roundtripEnumWithData(new EnumWithData.A(10)), + new EnumWithData.A(10) +); +Assert.deepEqual( + roundtripEnumWithData(new EnumWithData.B("Ten")), + new EnumWithData.B("Ten") +); +Assert.deepEqual( + roundtripEnumWithData(new EnumWithData.C()), + new EnumWithData.C() +); + +Assert.deepEqual( + roundtripComplexEnum(new ComplexEnum.A(EnumNoData.C)), + new ComplexEnum.A(EnumNoData.C) +); +Assert.deepEqual( + roundtripComplexEnum(new ComplexEnum.B(new EnumWithData.A(20))), + new ComplexEnum.B(new EnumWithData.A(20)) +); +Assert.deepEqual( + roundtripComplexEnum(new ComplexEnum.C(new SimpleRec({ a: 30 }))), + new ComplexEnum.C(new SimpleRec({ a: 30 })) +); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_errors.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_errors.js new file mode 100644 index 000000000000..9174732504e2 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_errors.js @@ -0,0 +1,46 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { + funcWithError, + funcWithFlatError, + Failure1, + Failure2, + IoError, + TestError, + TestFlatError, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +// Check the error hierarchies +Assert.ok(Failure1.prototype instanceof TestError); +Assert.ok(Failure2.prototype instanceof TestError); +Assert.ok(IoError.prototype instanceof TestFlatError); + +// `funcWithError` throws when 0 or 1 is passed to it +Assert.throws( + () => { + funcWithError(0); + }, + e => e instanceof Failure1 +); + +Assert.throws( + () => { + funcWithError(1); + }, + e => e instanceof Failure2 && e.data == "DATA" +); + +funcWithError(2); + +// `funcWithflatError` throws when 0 is passed to it +Assert.throws( + () => { + funcWithFlatError(0); + }, + e => e instanceof IoError +); + +funcWithFlatError(1); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_external_types.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_external_types.js new file mode 100644 index 000000000000..ba153d0307ad --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_external_types.js @@ -0,0 +1,27 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { EnumWithData, SimpleRec, TestInterface } = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +const { + roundtripExtCustomType, + roundtripExtEnum, + roundtripExtInterface, + roundtripExtRecord, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTestsExternalTypes.sys.mjs" +); + +Assert.deepEqual( + roundtripExtRecord(new SimpleRec({ a: 42 })), + new SimpleRec({ a: 42 }) +); +Assert.deepEqual( + roundtripExtEnum(new EnumWithData.A(10)), + new EnumWithData.A(10) +); +const interface = TestInterface.init(20); +Assert.equal(roundtripExtInterface(interface).getValue(), 20); +Assert.equal(roundtripExtCustomType(100), 100); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_futures.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_futures.js new file mode 100644 index 000000000000..9cedf10003ab --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_futures.js @@ -0,0 +1,52 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { + asyncRoundtripU8, + asyncRoundtripI8, + asyncRoundtripU16, + asyncRoundtripI16, + asyncRoundtripU32, + asyncRoundtripI32, + asyncRoundtripU64, + asyncRoundtripI64, + asyncRoundtripF32, + asyncRoundtripF64, + asyncRoundtripString, + asyncRoundtripVec, + asyncRoundtripMap, + asyncRoundtripObj, + AsyncInterface, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +add_task(async function roundtripPrimitives() { + Assert.equal(await asyncRoundtripU8(42), 42); + Assert.equal(await asyncRoundtripI8(-42), -42); + Assert.equal(await asyncRoundtripU16(42), 42); + Assert.equal(await asyncRoundtripI16(-42), -42); + Assert.equal(await asyncRoundtripU32(42), 42); + Assert.equal(await asyncRoundtripI32(-42), -42); + Assert.equal(await asyncRoundtripU64(42), 42); + Assert.equal(await asyncRoundtripI64(-42), -42); + Assert.equal(await asyncRoundtripF32(0.5), 0.5); + Assert.equal(await asyncRoundtripF64(-0.5), -0.5); + Assert.equal(await asyncRoundtripString("hi"), "hi"); +}); + +add_task(async function roundtripCompounds() { + Assert.equal(await asyncRoundtripString("hi"), "hi"); + Assert.deepEqual(await asyncRoundtripVec([42]), [42]); + Assert.deepEqual( + await asyncRoundtripMap(new Map([["hello", "world"]])), + new Map([["hello", "world"]]) + ); +}); + +add_task(async function asyncInterfaces() { + const obj = AsyncInterface.init("Alice"); + Assert.equal(await obj.name(), "Alice"); + const obj2 = await asyncRoundtripObj(obj); + Assert.equal(await obj2.name(), "Alice"); +}); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_interfaces.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_interfaces.js new file mode 100644 index 000000000000..95335e61ef49 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_interfaces.js @@ -0,0 +1,39 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { TestInterface, TwoTestInterfaces, cloneInterface, swapTestInterfaces } = + ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" + ); + +const interface = TestInterface.init(20); +Assert.equal(interface.getValue(), 20); +Assert.equal(cloneInterface(interface).getValue(), 20); + +// Test records that store interfaces +// +// The goal is to test if we can read/write interface handles to RustBuffers +const two = new TwoTestInterfaces({ + first: TestInterface.init(1), + second: TestInterface.init(2), +}); +const swapped = swapTestInterfaces(two); +Assert.equal(swapped.first.getValue(), 2); +Assert.equal(swapped.second.getValue(), 1); + +// Create 2 references to an interface using a bunch of intermediary objects: +// * The one passed to `funcThatClonesInterface` +// * The clones created for each method call + +// eslint-disable-next-line no-unused-vars +const interface2 = TestInterface.init(20); +function funcThatClonesInterface(interface) { + return cloneInterface(interface); +} +// eslint-disable-next-line no-unused-vars +const interface2Clone = funcThatClonesInterface(cloneInterface(interface)); +interface.getValue(); +// Run GC, then check that only the 2 actual references remain. +Cu.forceGC(); +Cu.forceCC(); +Assert.equal(interface.refCount(), 2); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_primitive_types.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_primitive_types.js new file mode 100644 index 000000000000..1c42d890de12 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_primitive_types.js @@ -0,0 +1,37 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { + roundtripU8, + roundtripI8, + roundtripU16, + roundtripI16, + roundtripU32, + roundtripI32, + roundtripU64, + roundtripI64, + roundtripF32, + roundtripF64, + roundtripBool, + roundtripString, + sumWithManyTypes, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +// Test calling and returning a single argument +Assert.equal(roundtripU8(42), 42); +Assert.equal(roundtripI8(-42), -42); +Assert.equal(roundtripU16(42), 42); +Assert.equal(roundtripI16(-42), -42); +Assert.equal(roundtripU32(42), 42); +Assert.equal(roundtripI32(-42), -42); +Assert.equal(roundtripU64(42), 42); +Assert.equal(roundtripI64(-42), -42); +Assert.equal(roundtripF32(0.5), 0.5); +Assert.equal(roundtripF64(-3.5), -3.5); +Assert.equal(roundtripBool(true), true); +Assert.equal(roundtripString("ABC"), "ABC"); +// Test calling a function with lots of args +// This function will sum up all the numbers, then negate the value since we passed in `true` +Assert.equal(sumWithManyTypes(1, -2, 3, -4, 5, -6, 7, -8, 9.5, -10.5, true), 5); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_records.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_records.js new file mode 100644 index 000000000000..d74f511d65d3 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_records.js @@ -0,0 +1,54 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { + SimpleRec, + ComplexRec, + RecWithDefault, + roundtripSimpleRec, + roundtripComplexRec, +} = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +// roundtripSimpleRec is configured to use the async wrapped call type +add_task(async function testRoundtripSimpleRec() { + Assert.deepEqual( + await roundtripSimpleRec(new SimpleRec({ a: 42 })), + new SimpleRec({ a: 42 }) + ); +}); +Assert.deepEqual(new RecWithDefault().a, 42); +Assert.deepEqual(new RecWithDefault({}).a, 42); +Assert.deepEqual(new RecWithDefault({ a: 10 }).a, 10); +Assert.deepEqual( + roundtripComplexRec( + new ComplexRec({ + fieldU8: 0, + fieldI8: -1, + fieldU16: 2, + fieldI16: -3, + fieldU32: 4, + fieldI32: -5, + fieldU64: 6, + fieldI64: -7, + fieldF32: 8.5, + fieldF64: 9.5, + fieldRec: new SimpleRec({ a: 42 }), + }) + ), + new ComplexRec({ + fieldU8: 0, + fieldI8: -1, + fieldU16: 2, + fieldI16: -3, + fieldU32: 4, + fieldI32: -5, + fieldU64: 6, + fieldI64: -7, + fieldF32: 8.5, + fieldF64: 9.5, + fieldString: "DefaultString", + fieldRec: new SimpleRec({ a: 42 }), + }) +); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_simple_fns.js b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_simple_fns.js new file mode 100644 index 000000000000..07a3c8d4e86f --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/test_simple_fns.js @@ -0,0 +1,9 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +const { testFunc } = ChromeUtils.importESModule( + "moz-src:///toolkit/components/uniffi-bindgen-gecko-js/tests/generated/RustUniffiBindingsTests.sys.mjs" +); + +// Can we call a Rust function without throwing? +testFunc(); diff --git a/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/xpcshell.toml b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/xpcshell.toml new file mode 100644 index 000000000000..6323391407dd --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/tests/xpcshell/xpcshell.toml @@ -0,0 +1,25 @@ +[DEFAULT] + +["test_callback_interfaces.js"] + +["test_complex_fns.js"] + +["test_compound_types.js"] + +["test_custom_types.js"] + +["test_enums.js"] + +["test_errors.js"] + +["test_external_types.js"] + +["test_futures.js"] + +["test_interfaces.js"] + +["test_primitive_types.js"] + +["test_records.js"] + +["test_simple_fns.js"] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/Cargo.toml new file mode 100644 index 000000000000..7a06058e53ec --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "uniffi_bindings_tests" +version = "0.29.0" +edition = "2021" + +[lib] +crate-type = ["lib", "staticlib"] + +[dependencies] +thiserror = "1" +uniffi = { workspace = true, features = ["ffi-trace"] } + +[features] +default = ["simple_fns", "primitive_types", "complex_fns", "compound_types", "records", "enums", + "interfaces", "custom_types", "errors", "callback_interfaces", "futures"] +simple_fns = [] +primitive_types = [] +complex_fns = [] +compound_types = [] +records = [] +enums = [] +interfaces = [] +custom_types = [] +errors = [] +callback_interfaces = [] +futures = [] diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/README b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/README new file mode 100644 index 000000000000..ddacceadf9da --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/README @@ -0,0 +1,4 @@ +Tests fixtures for bindings generators + +This is used to test the UniFFI builtin bindings and can also be used to test external bindings. +See `uniffi_bindgen/src/bindings/python/bindgen_tests.rs` for example usage. diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/callback_interfaces.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/callback_interfaces.rs new file mode 100644 index 000000000000..0949a4a2d746 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/callback_interfaces.rs @@ -0,0 +1,13 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#[uniffi::export(callback_interface)] +pub trait TestCallbackInterface { + fn get_value(&self) -> u32; +} + +#[uniffi::export] +fn invoke_test_callback_interface_method(cbi: Box) -> u32 { + cbi.get_value() +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/complex_fns.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/complex_fns.rs new file mode 100644 index 000000000000..583a41be9410 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/complex_fns.rs @@ -0,0 +1,37 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Test lifting/lowering primitive types + +#[uniffi::export(default(arg = "DEFAULT"))] +pub fn func_with_default(arg: String) -> String { + arg +} + +/// Test a multi-word argument. `the_argument` should be normalized to the naming style of the +/// foreign language. +#[uniffi::export] +pub fn func_with_multi_word_arg(the_argument: String) -> String { + the_argument +} + +#[derive(uniffi::Object)] +struct ComplexMethods; + +#[uniffi::export] +impl ComplexMethods { + #[uniffi::constructor()] + pub fn new() -> Self { + Self + } + + #[uniffi::method(default(arg = "DEFAULT"))] + pub fn method_with_default(&self, arg: String) -> String { + arg + } + + pub fn method_with_multi_word_arg(&self, the_argument: String) -> String { + the_argument + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/compound_types.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/compound_types.rs new file mode 100644 index 000000000000..265595157e3f --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/compound_types.rs @@ -0,0 +1,29 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +use std::collections::HashMap; + +// Simple tests for inputting and returning arguments + +#[uniffi::export] +pub fn roundtrip_option(a: Option) -> Option { + a +} + +#[uniffi::export] +pub fn roundtrip_vec(a: Vec) -> Vec { + a +} + +#[uniffi::export] +pub fn roundtrip_hash_map(a: HashMap) -> HashMap { + a +} + +#[uniffi::export] +pub fn roundtrip_complex_compound( + a: Option>>, +) -> Option>> { + a +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/custom_types.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/custom_types.rs new file mode 100644 index 000000000000..d54e01e0e8cd --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/custom_types.rs @@ -0,0 +1,15 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +pub struct Handle(u64); + +uniffi::custom_type!(Handle, u64, { + try_lift: |val| Ok(Handle(val)), + lower: |handle| handle.0, +}); + +#[uniffi::export] +pub fn roundtrip_custom_type(handle: Handle) -> Handle { + handle +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/enums.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/enums.rs new file mode 100644 index 000000000000..c244c1006c07 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/enums.rs @@ -0,0 +1,41 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use crate::records::SimpleRec; + +#[derive(uniffi::Enum)] +pub enum EnumNoData { + A, + B, + C, +} + +#[derive(uniffi::Enum)] +pub enum EnumWithData { + A { value: u8 }, + B { value: String }, + C, +} + +#[derive(uniffi::Enum)] +pub enum ComplexEnum { + A { value: EnumNoData }, + B { value: EnumWithData }, + C { value: SimpleRec }, +} + +#[uniffi::export] +pub fn roundtrip_enum_no_data(en: EnumNoData) -> EnumNoData { + en +} + +#[uniffi::export] +pub fn roundtrip_enum_with_data(en: EnumWithData) -> EnumWithData { + en +} + +#[uniffi::export] +pub fn roundtrip_complex_enum(en: ComplexEnum) -> ComplexEnum { + en +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/errors.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/errors.rs new file mode 100644 index 000000000000..6ff7602602b2 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/errors.rs @@ -0,0 +1,50 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use std::io; + +/// Error enum +#[derive(uniffi::Error, thiserror::Error, Debug)] +pub enum TestError { + #[error("Failure1")] + Failure1, + #[error("Failure2(data={data})")] + Failure2 { data: String }, +} + +/// Flat error enum +/// +/// The associated data for this won't be across the FFI. Flat errors are mostly just a historical +/// artifact, but there are some use-cases for them -- for example variants that wrap errors from +/// other crates. +#[derive(uniffi::Error, thiserror::Error, Debug)] +#[uniffi(flat_error)] +pub enum TestFlatError { + /// Here's an example of a variant that only works with a flat error, `io::Error` is not + /// UniFFI compatible and can't be passed across the FFI. + #[error("Failure1")] + IoError(io::Error), +} + +#[uniffi::export] +pub fn func_with_error(input: u32) -> Result<(), TestError> { + match input { + 0 => Err(TestError::Failure1), + 1 => Err(TestError::Failure2 { + data: "DATA".to_string(), + }), + _ => Ok(()), + } +} + +#[uniffi::export] +pub fn func_with_flat_error(input: u32) -> Result<(), TestFlatError> { + match input { + 0 => Err(TestFlatError::IoError(io::Error::new( + io::ErrorKind::NotFound, + "NotFound".to_string(), + ))), + _ => Ok(()), + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/futures.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/futures.rs new file mode 100644 index 000000000000..172c4c82e3ff --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/futures.rs @@ -0,0 +1,97 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + + +//! Async functions that round-trip data. +//! +//! The purpose of these is to test the lift/lower implementations in the async code. + +use std::{collections::HashMap, sync::Arc}; + +#[uniffi::export] +async fn async_roundtrip_u8(v: u8) -> u8 { + v +} + +#[uniffi::export] +async fn async_roundtrip_i8(v: i8) -> i8 { + v +} + +#[uniffi::export] +async fn async_roundtrip_u16(v: u16) -> u16 { + v +} + +#[uniffi::export] +async fn async_roundtrip_i16(v: i16) -> i16 { + v +} + +#[uniffi::export] +async fn async_roundtrip_u32(v: u32) -> u32 { + v +} + +#[uniffi::export] +async fn async_roundtrip_i32(v: i32) -> i32 { + v +} + +#[uniffi::export] +async fn async_roundtrip_u64(v: u64) -> u64 { + v +} + +#[uniffi::export] +async fn async_roundtrip_i64(v: i64) -> i64 { + v +} + +#[uniffi::export] +async fn async_roundtrip_f32(v: f32) -> f32 { + v +} + +#[uniffi::export] +async fn async_roundtrip_f64(v: f64) -> f64 { + v +} + +#[uniffi::export] +async fn async_roundtrip_string(v: String) -> String { + v +} + +#[uniffi::export] +async fn async_roundtrip_vec(v: Vec) -> Vec { + v +} + +#[uniffi::export] +async fn async_roundtrip_map(v: HashMap) -> HashMap { + v +} + +#[derive(uniffi::Object)] +struct AsyncInterface { + name: String, +} + +#[uniffi::export] +impl AsyncInterface { + #[uniffi::constructor] + pub fn new(name: String) -> Arc { + Arc::new(AsyncInterface { name }) + } + + pub async fn name(&self) -> String { + self.name.clone() + } +} + +#[uniffi::export] +async fn async_roundtrip_obj(v: Arc) -> Arc { + v +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/interfaces.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/interfaces.rs new file mode 100644 index 000000000000..d00f91781da6 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/interfaces.rs @@ -0,0 +1,49 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use std::sync::Arc; + +#[derive(uniffi::Object)] +pub struct TestInterface { + value: u32, +} + +#[uniffi::export] +impl TestInterface { + #[uniffi::constructor] + pub fn new(value: u32) -> Self { + Self { value } + } + + pub fn get_value(&self) -> u32 { + self.value + } + + /// Get the current reference count for this object + /// + /// The count does not include the extra reference needed to call this method. + pub fn ref_count(self: Arc) -> u32 { + (Arc::strong_count(&self) - 1) as u32 + } +} + +#[uniffi::export] +pub fn clone_interface(int: Arc) -> Arc { + int +} + +// Test interfaces in records +#[derive(uniffi::Record)] +pub struct TwoTestInterfaces { + first: Arc, + second: Arc, +} + +#[uniffi::export] +pub fn swap_test_interfaces(interfaces: TwoTestInterfaces) -> TwoTestInterfaces { + TwoTestInterfaces { + first: interfaces.second, + second: interfaces.first, + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/lib.rs new file mode 100644 index 000000000000..c71f7a0840da --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/lib.rs @@ -0,0 +1,38 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +uniffi::setup_scaffolding!("uniffi_bindings_tests"); + +#[cfg(feature = "callback_interfaces")] +pub mod callback_interfaces; + +#[cfg(feature = "complex_fns")] +pub mod complex_fns; + +#[cfg(feature = "compound_types")] +pub mod compound_types; + +#[cfg(feature = "custom_types")] +pub mod custom_types; + +#[cfg(feature = "enums")] +pub mod enums; + +#[cfg(feature = "errors")] +pub mod errors; + +#[cfg(feature = "futures")] +pub mod futures; + +#[cfg(feature = "interfaces")] +pub mod interfaces; + +#[cfg(feature = "primitive_types")] +pub mod primitive_types; + +#[cfg(feature = "records")] +pub mod records; + +#[cfg(feature = "simple_fns")] +pub mod simple_fns; diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/primitive_types.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/primitive_types.rs new file mode 100644 index 000000000000..f0fbdbde2bce --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/primitive_types.rs @@ -0,0 +1,94 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Test lifting/lowering primitive types + +// Simple tests for inputting and returning arguments + +#[uniffi::export] +pub fn roundtrip_u8(a: u8) -> u8 { + a +} + +#[uniffi::export] +pub fn roundtrip_i8(a: i8) -> i8 { + a +} + +#[uniffi::export] +pub fn roundtrip_u16(a: u16) -> u16 { + a +} + +#[uniffi::export] +pub fn roundtrip_i16(a: i16) -> i16 { + a +} + +#[uniffi::export] +pub fn roundtrip_u32(a: u32) -> u32 { + a +} + +#[uniffi::export] +pub fn roundtrip_i32(a: i32) -> i32 { + a +} + +#[uniffi::export] +pub fn roundtrip_u64(a: u64) -> u64 { + a +} + +#[uniffi::export] +pub fn roundtrip_i64(a: i64) -> i64 { + a +} + +#[uniffi::export] +pub fn roundtrip_f32(a: f32) -> f32 { + a +} + +#[uniffi::export] +pub fn roundtrip_f64(a: f64) -> f64 { + a +} + +#[uniffi::export] +pub fn roundtrip_bool(a: bool) -> bool { + a +} + +#[uniffi::export] +pub fn roundtrip_string(a: String) -> String { + a +} + +/// Complex test: input a bunch of different values and add them together +#[uniffi::export] +#[allow(clippy::too_many_arguments)] +pub fn sum_with_many_types( + a: u8, + b: i8, + c: u16, + d: i16, + e: u32, + f: i32, + g: u64, + h: i64, + i: f32, + j: f64, + negate: bool, +) -> f64 { + let all_values = [ + a as f64, b as f64, c as f64, d as f64, e as f64, f as f64, g as f64, h as f64, i as f64, j, + ]; + let sum: f64 = all_values.into_iter().sum(); + if negate { + -sum + } else { + sum + } +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/records.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/records.rs new file mode 100644 index 000000000000..512b980ab929 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/records.rs @@ -0,0 +1,41 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#[derive(uniffi::Record)] +pub struct SimpleRec { + a: u8, +} + +#[derive(uniffi::Record)] +pub struct RecWithDefault { + #[uniffi(default = 42)] + a: u8, +} + +#[derive(uniffi::Record)] +pub struct ComplexRec { + field_u8: u8, + field_i8: i8, + field_u16: u16, + field_i16: i16, + field_u32: u32, + field_i32: i32, + field_u64: u64, + field_i64: i64, + field_f32: f32, + field_f64: f64, + #[uniffi(default = "DefaultString")] + field_string: String, + field_rec: SimpleRec, +} + +#[uniffi::export] +pub fn roundtrip_simple_rec(rec: SimpleRec) -> SimpleRec { + rec +} + +#[uniffi::export] +pub fn roundtrip_complex_rec(rec: ComplexRec) -> ComplexRec { + rec +} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/simple_fns.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/simple_fns.rs new file mode 100644 index 000000000000..b47acc545ec6 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests/src/simple_fns.rs @@ -0,0 +1,11 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +//! Extremely simple fixture to test making scaffolding calls without any arguments or return types +//! +//! The test is if the bindings can make a call to `test_func`. If in doubt, run the tests with +//! `--features=ffi-trace` to check that the function is actually called. + +#[uniffi::export] +pub fn test_func() {} diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests_external_types/Cargo.toml b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests_external_types/Cargo.toml new file mode 100644 index 000000000000..2c39e3d31d36 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests_external_types/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "uniffi_bindings_tests_external_types" +version = "0.29.0" +edition = "2021" + +[lib] +crate-type = ["lib", "staticlib"] + +[dependencies] +thiserror = "1" +uniffi = { workspace = true } + +uniffi_bindings_tests = { path = "../uniffi_bindings_tests" } diff --git a/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests_external_types/src/lib.rs b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests_external_types/src/lib.rs new file mode 100644 index 000000000000..e96e22e89a89 --- /dev/null +++ b/toolkit/components/uniffi-bindgen-gecko-js/uniffi_bindings_tests_external_types/src/lib.rs @@ -0,0 +1,34 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/// External types test lib +/// +/// This imports types from the main test fixture crate, then defines functions that input/return +/// them. +use std::sync::Arc; +use uniffi_bindings_tests::{ + custom_types::Handle, enums::EnumWithData, interfaces::TestInterface, records::SimpleRec, +}; + +uniffi::setup_scaffolding!("uniffi_bindings_tests_external_types"); + +#[uniffi::export] +pub fn roundtrip_ext_record(rec: SimpleRec) -> SimpleRec { + rec +} + +#[uniffi::export] +pub fn roundtrip_ext_enum(en: EnumWithData) -> EnumWithData { + en +} + +#[uniffi::export] +pub fn roundtrip_ext_interface(int: Arc) -> Arc { + int +} + +#[uniffi::export] +pub fn roundtrip_ext_custom_type(custom: Handle) -> Handle { + custom +} diff --git a/toolkit/components/uniffi-js/Callbacks.cpp b/toolkit/components/uniffi-js/Callbacks.cpp index 0cc8c4935172..d4061dbfd4ad 100644 --- a/toolkit/components/uniffi-js/Callbacks.cpp +++ b/toolkit/components/uniffi-js/Callbacks.cpp @@ -31,7 +31,7 @@ void UniffiCallbackMethodHandlerBase::FireAndForget( if (!jsHandler) { MOZ_LOG(gUniffiLogger, LogLevel::Error, ("[UniFFI] %s called, but JS handler not registered", - handler->mInterfaceName)); + handler->mUniffiInterfaceName)); return; } @@ -39,11 +39,11 @@ void UniffiCallbackMethodHandlerBase::FireAndForget( if (!global) { MOZ_LOG(gUniffiLogger, LogLevel::Error, ("[UniFFI] JS handler for %s has null global", - handler->mInterfaceName)); + handler->mUniffiInterfaceName)); return; } - dom::AutoEntryScript aes(global, handler->mInterfaceName); + dom::AutoEntryScript aes(global, handler->mUniffiInterfaceName); IgnoredErrorResult error; handler->MakeCall(aes.cx(), jsHandler, error); @@ -51,7 +51,7 @@ void UniffiCallbackMethodHandlerBase::FireAndForget( if (error.Failed()) { MOZ_LOG(gUniffiLogger, LogLevel::Error, ("[UniFFI] Error invoking JS handler for %s", - handler->mInterfaceName)); + handler->mUniffiInterfaceName)); return; } })); @@ -65,7 +65,7 @@ void UniffiCallbackMethodHandlerBase::FireAndForget( void UniffiCallbackFreeHandler::MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) { - aJsHandler->Destroy(mObjectHandle, aError); + aJsHandler->Destroy(mUniffiHandle.IntoRust(), aError); } } // namespace mozilla::uniffi diff --git a/toolkit/components/uniffi-js/Callbacks.h b/toolkit/components/uniffi-js/Callbacks.h index 67f49786ce6b..c5fd30f60199 100644 --- a/toolkit/components/uniffi-js/Callbacks.h +++ b/toolkit/components/uniffi-js/Callbacks.h @@ -10,6 +10,7 @@ #include "mozilla/StaticPtr.h" #include "mozilla/UniquePtr.h" #include "mozilla/dom/UniFFIScaffolding.h" +#include "mozilla/uniffi/FfiValue.h" #include "mozilla/uniffi/Rust.h" namespace mozilla::uniffi { @@ -49,8 +50,8 @@ void DeregisterCallbackHandler(uint64_t aInterfaceId, ErrorResult& aError); class UniffiCallbackMethodHandlerBase { protected: // Name of the callback interface - const char* mInterfaceName; - uint64_t mObjectHandle; + const char* mUniffiInterfaceName; + FfiValueInt mUniffiHandle; // Invoke the callback method using a JS handler MOZ_CAN_RUN_SCRIPT @@ -59,8 +60,9 @@ class UniffiCallbackMethodHandlerBase { public: UniffiCallbackMethodHandlerBase(const char* aInterfaceName, - uint64_t aObjectHandle) - : mInterfaceName(aInterfaceName), mObjectHandle(aObjectHandle) {} + uint64_t aUniffiHandle) + : mUniffiInterfaceName(aInterfaceName), + mUniffiHandle(FfiValueInt::FromRust(aUniffiHandle)) {} virtual ~UniffiCallbackMethodHandlerBase() = default; diff --git a/toolkit/components/uniffi-js/GeneratedScaffolding.cpp b/toolkit/components/uniffi-js/GeneratedScaffolding.cpp index bb8c00f48f7b..c1b9093300ce 100644 --- a/toolkit/components/uniffi-js/GeneratedScaffolding.cpp +++ b/toolkit/components/uniffi-js/GeneratedScaffolding.cpp @@ -25,236 +25,231 @@ using dom::GlobalObject; using dom::RootedDictionary; using dom::NullableRootedUnion; using dom::Promise; -using dom::OwningUniFFIScaffoldingValue; using dom::Sequence; using dom::UniFFICallbackHandler; using dom::UniFFIPointer; using dom::UniFFIScaffoldingCallResult; -// Define scaffolding functions from UniFFI + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + extern "C" { - typedef void (*RustFutureContinuationCallback)(uint64_t, int8_t); - typedef void (*ForeignFutureFree)(uint64_t); - typedef void (*CallbackInterfaceFree)(uint64_t); - struct ForeignFuture { - uint64_t handle; - ForeignFutureFree free; - }; - struct ForeignFutureStructU8 { - uint8_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteU8)(uint64_t, ForeignFutureStructU8); - struct ForeignFutureStructI8 { - int8_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteI8)(uint64_t, ForeignFutureStructI8); - struct ForeignFutureStructU16 { - uint16_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteU16)(uint64_t, ForeignFutureStructU16); - struct ForeignFutureStructI16 { - int16_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteI16)(uint64_t, ForeignFutureStructI16); - struct ForeignFutureStructU32 { - uint32_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteU32)(uint64_t, ForeignFutureStructU32); - struct ForeignFutureStructI32 { - int32_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteI32)(uint64_t, ForeignFutureStructI32); - struct ForeignFutureStructU64 { - uint64_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteU64)(uint64_t, ForeignFutureStructU64); - struct ForeignFutureStructI64 { - int64_t return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteI64)(uint64_t, ForeignFutureStructI64); - struct ForeignFutureStructF32 { - float return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteF32)(uint64_t, ForeignFutureStructF32); - struct ForeignFutureStructF64 { - double return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteF64)(uint64_t, ForeignFutureStructF64); - struct ForeignFutureStructPointer { - void* return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompletePointer)(uint64_t, ForeignFutureStructPointer); - struct ForeignFutureStructRustBuffer { - RustBuffer return_value; - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteRustBuffer)(uint64_t, ForeignFutureStructRustBuffer); - struct ForeignFutureStructVoid { - RustCallStatus call_status; - }; - typedef void (*ForeignFutureCompleteVoid)(uint64_t, ForeignFutureStructVoid); - typedef void (*CallbackInterfaceContextIdCallbackMethod0)(uint64_t, RustBuffer, int64_t, void*, RustCallStatus*); - typedef void (*CallbackInterfaceContextIdCallbackMethod1)(uint64_t, RustBuffer, void*, RustCallStatus*); - struct VTableCallbackInterfaceContextIdCallback { - CallbackInterfaceContextIdCallbackMethod0 persist; - CallbackInterfaceContextIdCallbackMethod1 rotated; - CallbackInterfaceFree uniffi_free; - }; - void* uniffi_context_id_fn_clone_contextidcomponent(void*, RustCallStatus*); - void uniffi_context_id_fn_free_contextidcomponent(void*, RustCallStatus*); - void* uniffi_context_id_fn_constructor_contextidcomponent_new(RustBuffer, int64_t, int8_t, uint64_t, RustCallStatus*); - void uniffi_context_id_fn_method_contextidcomponent_force_rotation(void*, RustCallStatus*); - RustBuffer uniffi_context_id_fn_method_contextidcomponent_request(void*, uint8_t, RustCallStatus*); - void uniffi_context_id_fn_method_contextidcomponent_unset_callback(void*, RustCallStatus*); - void uniffi_context_id_fn_init_callback_vtable_contextidcallback(VTableCallbackInterfaceContextIdCallback*); RustBuffer ffi_context_id_rustbuffer_alloc(uint64_t, RustCallStatus*); RustBuffer ffi_context_id_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); void ffi_context_id_rustbuffer_free(RustBuffer, RustCallStatus*); RustBuffer ffi_context_id_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + typedef void (*RustFutureContinuationCallback)(uint64_t, int8_t); + typedef void (*ForeignFutureFree)(uint64_t); + struct ForeignFuture { + uint64_t handle; + ForeignFutureFree free; + }; void ffi_context_id_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_u8(uint64_t); - void ffi_context_id_rust_future_free_u8(uint64_t); uint8_t ffi_context_id_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_u8(uint64_t); void ffi_context_id_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_i8(uint64_t); - void ffi_context_id_rust_future_free_i8(uint64_t); int8_t ffi_context_id_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_i8(uint64_t); void ffi_context_id_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_u16(uint64_t); - void ffi_context_id_rust_future_free_u16(uint64_t); uint16_t ffi_context_id_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_u16(uint64_t); void ffi_context_id_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_i16(uint64_t); - void ffi_context_id_rust_future_free_i16(uint64_t); int16_t ffi_context_id_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_i16(uint64_t); void ffi_context_id_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_u32(uint64_t); - void ffi_context_id_rust_future_free_u32(uint64_t); uint32_t ffi_context_id_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_u32(uint64_t); void ffi_context_id_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_i32(uint64_t); - void ffi_context_id_rust_future_free_i32(uint64_t); int32_t ffi_context_id_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_i32(uint64_t); void ffi_context_id_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_u64(uint64_t); - void ffi_context_id_rust_future_free_u64(uint64_t); uint64_t ffi_context_id_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_u64(uint64_t); void ffi_context_id_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_i64(uint64_t); - void ffi_context_id_rust_future_free_i64(uint64_t); int64_t ffi_context_id_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_i64(uint64_t); void ffi_context_id_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_f32(uint64_t); - void ffi_context_id_rust_future_free_f32(uint64_t); float ffi_context_id_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_f32(uint64_t); void ffi_context_id_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_f64(uint64_t); - void ffi_context_id_rust_future_free_f64(uint64_t); double ffi_context_id_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_f64(uint64_t); void ffi_context_id_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_pointer(uint64_t); - void ffi_context_id_rust_future_free_pointer(uint64_t); void* ffi_context_id_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_pointer(uint64_t); void ffi_context_id_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_rust_buffer(uint64_t); - void ffi_context_id_rust_future_free_rust_buffer(uint64_t); RustBuffer ffi_context_id_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_rust_buffer(uint64_t); void ffi_context_id_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_context_id_rust_future_cancel_void(uint64_t); - void ffi_context_id_rust_future_free_void(uint64_t); void ffi_context_id_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_context_id_rust_future_free_void(uint64_t); + void* uniffi_context_id_fn_clone_contextidcomponent(void*, RustCallStatus*); + void uniffi_context_id_fn_free_contextidcomponent(void*, RustCallStatus*); + typedef void (*CallbackInterfaceContextIdCallbackMethod0)(uint64_t, RustBuffer, int64_t, void*, RustCallStatus*); + typedef void (*CallbackInterfaceContextIdCallbackMethod1)(uint64_t, RustBuffer, void*, RustCallStatus*); + typedef void (*CallbackInterfaceFreecontext_id_ContextIdCallback)(uint64_t); + struct VTableCallbackInterfaceContextIdCallback { + CallbackInterfaceContextIdCallbackMethod0 persist; + CallbackInterfaceContextIdCallbackMethod1 rotated; + CallbackInterfaceFreecontext_id_ContextIdCallback uniffi_free; + }; + void uniffi_context_id_fn_init_callback_vtable_contextidcallback(VTableCallbackInterfaceContextIdCallback*); + void* uniffi_context_id_fn_constructor_contextidcomponent_new(RustBuffer, int64_t, int8_t, uint64_t, RustCallStatus*); + void uniffi_context_id_fn_method_contextidcomponent_force_rotation(void*, RustCallStatus*); + RustBuffer uniffi_context_id_fn_method_contextidcomponent_request(void*, uint8_t, RustCallStatus*); + void uniffi_context_id_fn_method_contextidcomponent_unset_callback(void*, RustCallStatus*); + uint32_t ffi_context_id_uniffi_contract_version(); + uint16_t uniffi_context_id_checksum_constructor_contextidcomponent_new(); uint16_t uniffi_context_id_checksum_method_contextidcomponent_force_rotation(); uint16_t uniffi_context_id_checksum_method_contextidcomponent_request(); uint16_t uniffi_context_id_checksum_method_contextidcomponent_unset_callback(); - uint16_t uniffi_context_id_checksum_constructor_contextidcomponent_new(); uint16_t uniffi_context_id_checksum_method_contextidcallback_persist(); uint16_t uniffi_context_id_checksum_method_contextidcallback_rotated(); - uint32_t ffi_context_id_uniffi_contract_version(); - typedef void (*CallbackInterfaceApplicationErrorReporterMethod0)(uint64_t, RustBuffer, RustBuffer, void*, RustCallStatus*); - typedef void (*CallbackInterfaceApplicationErrorReporterMethod1)(uint64_t, RustBuffer, RustBuffer, uint32_t, uint32_t, void*, RustCallStatus*); - struct VTableCallbackInterfaceApplicationErrorReporter { - CallbackInterfaceApplicationErrorReporterMethod0 report_error; - CallbackInterfaceApplicationErrorReporterMethod1 report_breadcrumb; - CallbackInterfaceFree uniffi_free; - }; - void uniffi_error_support_fn_init_callback_vtable_applicationerrorreporter(VTableCallbackInterfaceApplicationErrorReporter*); - void uniffi_error_support_fn_func_set_application_error_reporter(uint64_t, RustCallStatus*); - void uniffi_error_support_fn_func_unset_application_error_reporter(RustCallStatus*); RustBuffer ffi_error_support_rustbuffer_alloc(uint64_t, RustCallStatus*); RustBuffer ffi_error_support_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); void ffi_error_support_rustbuffer_free(RustBuffer, RustCallStatus*); RustBuffer ffi_error_support_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); void ffi_error_support_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_u8(uint64_t); - void ffi_error_support_rust_future_free_u8(uint64_t); uint8_t ffi_error_support_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_u8(uint64_t); void ffi_error_support_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_i8(uint64_t); - void ffi_error_support_rust_future_free_i8(uint64_t); int8_t ffi_error_support_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_i8(uint64_t); void ffi_error_support_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_u16(uint64_t); - void ffi_error_support_rust_future_free_u16(uint64_t); uint16_t ffi_error_support_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_u16(uint64_t); void ffi_error_support_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_i16(uint64_t); - void ffi_error_support_rust_future_free_i16(uint64_t); int16_t ffi_error_support_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_i16(uint64_t); void ffi_error_support_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_u32(uint64_t); - void ffi_error_support_rust_future_free_u32(uint64_t); uint32_t ffi_error_support_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_u32(uint64_t); void ffi_error_support_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_i32(uint64_t); - void ffi_error_support_rust_future_free_i32(uint64_t); int32_t ffi_error_support_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_i32(uint64_t); void ffi_error_support_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_u64(uint64_t); - void ffi_error_support_rust_future_free_u64(uint64_t); uint64_t ffi_error_support_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_u64(uint64_t); void ffi_error_support_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_i64(uint64_t); - void ffi_error_support_rust_future_free_i64(uint64_t); int64_t ffi_error_support_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_i64(uint64_t); void ffi_error_support_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_f32(uint64_t); - void ffi_error_support_rust_future_free_f32(uint64_t); float ffi_error_support_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_f32(uint64_t); void ffi_error_support_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_f64(uint64_t); - void ffi_error_support_rust_future_free_f64(uint64_t); double ffi_error_support_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_f64(uint64_t); void ffi_error_support_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_pointer(uint64_t); - void ffi_error_support_rust_future_free_pointer(uint64_t); void* ffi_error_support_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_pointer(uint64_t); void ffi_error_support_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_rust_buffer(uint64_t); - void ffi_error_support_rust_future_free_rust_buffer(uint64_t); RustBuffer ffi_error_support_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_rust_buffer(uint64_t); void ffi_error_support_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_error_support_rust_future_cancel_void(uint64_t); - void ffi_error_support_rust_future_free_void(uint64_t); void ffi_error_support_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_error_support_rust_future_free_void(uint64_t); + typedef void (*CallbackInterfaceApplicationErrorReporterMethod0)(uint64_t, RustBuffer, RustBuffer, void*, RustCallStatus*); + typedef void (*CallbackInterfaceApplicationErrorReporterMethod1)(uint64_t, RustBuffer, RustBuffer, uint32_t, uint32_t, void*, RustCallStatus*); + typedef void (*CallbackInterfaceFreeerrorsupport_ApplicationErrorReporter)(uint64_t); + struct VTableCallbackInterfaceApplicationErrorReporter { + CallbackInterfaceApplicationErrorReporterMethod0 report_error; + CallbackInterfaceApplicationErrorReporterMethod1 report_breadcrumb; + CallbackInterfaceFreeerrorsupport_ApplicationErrorReporter uniffi_free; + }; + void uniffi_error_support_fn_init_callback_vtable_applicationerrorreporter(VTableCallbackInterfaceApplicationErrorReporter*); + void uniffi_error_support_fn_func_set_application_error_reporter(uint64_t, RustCallStatus*); + void uniffi_error_support_fn_func_unset_application_error_reporter(RustCallStatus*); + uint32_t ffi_error_support_uniffi_contract_version(); uint16_t uniffi_error_support_checksum_func_set_application_error_reporter(); uint16_t uniffi_error_support_checksum_func_unset_application_error_reporter(); - uint16_t uniffi_error_support_checksum_method_applicationerrorreporter_report_error(); - uint16_t uniffi_error_support_checksum_method_applicationerrorreporter_report_breadcrumb(); - uint32_t ffi_error_support_uniffi_contract_version(); + RustBuffer ffi_relevancy_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_relevancy_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_relevancy_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_relevancy_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_u8(uint64_t); + uint8_t ffi_relevancy_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_u8(uint64_t); + void ffi_relevancy_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_i8(uint64_t); + int8_t ffi_relevancy_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_i8(uint64_t); + void ffi_relevancy_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_u16(uint64_t); + uint16_t ffi_relevancy_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_u16(uint64_t); + void ffi_relevancy_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_i16(uint64_t); + int16_t ffi_relevancy_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_i16(uint64_t); + void ffi_relevancy_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_u32(uint64_t); + uint32_t ffi_relevancy_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_u32(uint64_t); + void ffi_relevancy_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_i32(uint64_t); + int32_t ffi_relevancy_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_i32(uint64_t); + void ffi_relevancy_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_u64(uint64_t); + uint64_t ffi_relevancy_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_u64(uint64_t); + void ffi_relevancy_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_i64(uint64_t); + int64_t ffi_relevancy_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_i64(uint64_t); + void ffi_relevancy_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_f32(uint64_t); + float ffi_relevancy_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_f32(uint64_t); + void ffi_relevancy_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_f64(uint64_t); + double ffi_relevancy_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_f64(uint64_t); + void ffi_relevancy_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_pointer(uint64_t); + void* ffi_relevancy_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_pointer(uint64_t); + void ffi_relevancy_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_relevancy_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_rust_buffer(uint64_t); + void ffi_relevancy_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_relevancy_rust_future_cancel_void(uint64_t); + void ffi_relevancy_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_relevancy_rust_future_free_void(uint64_t); void* uniffi_relevancy_fn_clone_relevancystore(void*, RustCallStatus*); void uniffi_relevancy_fn_free_relevancystore(void*, RustCallStatus*); + double uniffi_relevancy_fn_func_score(RustBuffer, RustBuffer, RustCallStatus*); void* uniffi_relevancy_fn_constructor_relevancystore_new(RustBuffer, void*, RustCallStatus*); void uniffi_relevancy_fn_method_relevancystore_bandit_init(void*, RustBuffer, RustBuffer, RustCallStatus*); RustBuffer uniffi_relevancy_fn_method_relevancystore_bandit_select(void*, RustBuffer, RustBuffer, RustCallStatus*); @@ -265,64 +260,9 @@ extern "C" { RustBuffer uniffi_relevancy_fn_method_relevancystore_ingest(void*, RustBuffer, RustCallStatus*); void uniffi_relevancy_fn_method_relevancystore_interrupt(void*, RustCallStatus*); RustBuffer uniffi_relevancy_fn_method_relevancystore_user_interest_vector(void*, RustCallStatus*); - double uniffi_relevancy_fn_func_score(RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer ffi_relevancy_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_relevancy_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_relevancy_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_relevancy_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_u8(uint64_t); - void ffi_relevancy_rust_future_free_u8(uint64_t); - uint8_t ffi_relevancy_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_i8(uint64_t); - void ffi_relevancy_rust_future_free_i8(uint64_t); - int8_t ffi_relevancy_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_u16(uint64_t); - void ffi_relevancy_rust_future_free_u16(uint64_t); - uint16_t ffi_relevancy_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_i16(uint64_t); - void ffi_relevancy_rust_future_free_i16(uint64_t); - int16_t ffi_relevancy_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_u32(uint64_t); - void ffi_relevancy_rust_future_free_u32(uint64_t); - uint32_t ffi_relevancy_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_i32(uint64_t); - void ffi_relevancy_rust_future_free_i32(uint64_t); - int32_t ffi_relevancy_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_u64(uint64_t); - void ffi_relevancy_rust_future_free_u64(uint64_t); - uint64_t ffi_relevancy_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_i64(uint64_t); - void ffi_relevancy_rust_future_free_i64(uint64_t); - int64_t ffi_relevancy_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_f32(uint64_t); - void ffi_relevancy_rust_future_free_f32(uint64_t); - float ffi_relevancy_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_f64(uint64_t); - void ffi_relevancy_rust_future_free_f64(uint64_t); - double ffi_relevancy_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_pointer(uint64_t); - void ffi_relevancy_rust_future_free_pointer(uint64_t); - void* ffi_relevancy_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_rust_buffer(uint64_t); - void ffi_relevancy_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_relevancy_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_relevancy_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_relevancy_rust_future_cancel_void(uint64_t); - void ffi_relevancy_rust_future_free_void(uint64_t); - void ffi_relevancy_rust_future_complete_void(uint64_t, RustCallStatus*); + uint32_t ffi_relevancy_uniffi_contract_version(); uint16_t uniffi_relevancy_checksum_func_score(); + uint16_t uniffi_relevancy_checksum_constructor_relevancystore_new(); uint16_t uniffi_relevancy_checksum_method_relevancystore_bandit_init(); uint16_t uniffi_relevancy_checksum_method_relevancystore_bandit_select(); uint16_t uniffi_relevancy_checksum_method_relevancystore_bandit_update(); @@ -332,84 +272,84 @@ extern "C" { uint16_t uniffi_relevancy_checksum_method_relevancystore_ingest(); uint16_t uniffi_relevancy_checksum_method_relevancystore_interrupt(); uint16_t uniffi_relevancy_checksum_method_relevancystore_user_interest_vector(); - uint16_t uniffi_relevancy_checksum_constructor_relevancystore_new(); - uint32_t ffi_relevancy_uniffi_contract_version(); - void* uniffi_remote_settings_fn_clone_remotesettings(void*, RustCallStatus*); - void uniffi_remote_settings_fn_free_remotesettings(void*, RustCallStatus*); - void* uniffi_remote_settings_fn_constructor_remotesettings_new(RustBuffer, RustCallStatus*); - void uniffi_remote_settings_fn_method_remotesettings_download_attachment_to_path(void*, RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettings_get_records(void*, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettings_get_records_since(void*, uint64_t, RustCallStatus*); - void* uniffi_remote_settings_fn_clone_remotesettingsclient(void*, RustCallStatus*); - void uniffi_remote_settings_fn_free_remotesettingsclient(void*, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_collection_name(void*, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_get_attachment(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_get_records(void*, int8_t, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_get_records_map(void*, int8_t, RustCallStatus*); - void uniffi_remote_settings_fn_method_remotesettingsclient_shutdown(void*, RustCallStatus*); - void uniffi_remote_settings_fn_method_remotesettingsclient_sync(void*, RustCallStatus*); - void* uniffi_remote_settings_fn_clone_remotesettingsservice(void*, RustCallStatus*); - void uniffi_remote_settings_fn_free_remotesettingsservice(void*, RustCallStatus*); - void* uniffi_remote_settings_fn_constructor_remotesettingsservice_new(RustBuffer, RustBuffer, RustCallStatus*); - void* uniffi_remote_settings_fn_method_remotesettingsservice_make_client(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_remote_settings_fn_method_remotesettingsservice_sync(void*, RustCallStatus*); - void uniffi_remote_settings_fn_method_remotesettingsservice_update_config(void*, RustBuffer, RustCallStatus*); RustBuffer ffi_remote_settings_rustbuffer_alloc(uint64_t, RustCallStatus*); RustBuffer ffi_remote_settings_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); void ffi_remote_settings_rustbuffer_free(RustBuffer, RustCallStatus*); RustBuffer ffi_remote_settings_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); void ffi_remote_settings_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_u8(uint64_t); - void ffi_remote_settings_rust_future_free_u8(uint64_t); uint8_t ffi_remote_settings_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_u8(uint64_t); void ffi_remote_settings_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_i8(uint64_t); - void ffi_remote_settings_rust_future_free_i8(uint64_t); int8_t ffi_remote_settings_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_i8(uint64_t); void ffi_remote_settings_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_u16(uint64_t); - void ffi_remote_settings_rust_future_free_u16(uint64_t); uint16_t ffi_remote_settings_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_u16(uint64_t); void ffi_remote_settings_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_i16(uint64_t); - void ffi_remote_settings_rust_future_free_i16(uint64_t); int16_t ffi_remote_settings_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_i16(uint64_t); void ffi_remote_settings_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_u32(uint64_t); - void ffi_remote_settings_rust_future_free_u32(uint64_t); uint32_t ffi_remote_settings_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_u32(uint64_t); void ffi_remote_settings_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_i32(uint64_t); - void ffi_remote_settings_rust_future_free_i32(uint64_t); int32_t ffi_remote_settings_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_i32(uint64_t); void ffi_remote_settings_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_u64(uint64_t); - void ffi_remote_settings_rust_future_free_u64(uint64_t); uint64_t ffi_remote_settings_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_u64(uint64_t); void ffi_remote_settings_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_i64(uint64_t); - void ffi_remote_settings_rust_future_free_i64(uint64_t); int64_t ffi_remote_settings_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_i64(uint64_t); void ffi_remote_settings_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_f32(uint64_t); - void ffi_remote_settings_rust_future_free_f32(uint64_t); float ffi_remote_settings_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_f32(uint64_t); void ffi_remote_settings_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_f64(uint64_t); - void ffi_remote_settings_rust_future_free_f64(uint64_t); double ffi_remote_settings_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_f64(uint64_t); void ffi_remote_settings_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_pointer(uint64_t); - void ffi_remote_settings_rust_future_free_pointer(uint64_t); void* ffi_remote_settings_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_pointer(uint64_t); void ffi_remote_settings_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_rust_buffer(uint64_t); - void ffi_remote_settings_rust_future_free_rust_buffer(uint64_t); RustBuffer ffi_remote_settings_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_rust_buffer(uint64_t); void ffi_remote_settings_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_remote_settings_rust_future_cancel_void(uint64_t); - void ffi_remote_settings_rust_future_free_void(uint64_t); void ffi_remote_settings_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_remote_settings_rust_future_free_void(uint64_t); + void* uniffi_remote_settings_fn_clone_remotesettings(void*, RustCallStatus*); + void uniffi_remote_settings_fn_free_remotesettings(void*, RustCallStatus*); + void* uniffi_remote_settings_fn_clone_remotesettingsclient(void*, RustCallStatus*); + void uniffi_remote_settings_fn_free_remotesettingsclient(void*, RustCallStatus*); + void* uniffi_remote_settings_fn_clone_remotesettingsservice(void*, RustCallStatus*); + void uniffi_remote_settings_fn_free_remotesettingsservice(void*, RustCallStatus*); + void* uniffi_remote_settings_fn_constructor_remotesettings_new(RustBuffer, RustCallStatus*); + void uniffi_remote_settings_fn_method_remotesettings_download_attachment_to_path(void*, RustBuffer, RustBuffer, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettings_get_records(void*, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettings_get_records_since(void*, uint64_t, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_collection_name(void*, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_get_attachment(void*, RustBuffer, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_get_records(void*, int8_t, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettingsclient_get_records_map(void*, int8_t, RustCallStatus*); + void uniffi_remote_settings_fn_method_remotesettingsclient_shutdown(void*, RustCallStatus*); + void uniffi_remote_settings_fn_method_remotesettingsclient_sync(void*, RustCallStatus*); + void* uniffi_remote_settings_fn_constructor_remotesettingsservice_new(RustBuffer, RustBuffer, RustCallStatus*); + void* uniffi_remote_settings_fn_method_remotesettingsservice_make_client(void*, RustBuffer, RustCallStatus*); + RustBuffer uniffi_remote_settings_fn_method_remotesettingsservice_sync(void*, RustCallStatus*); + void uniffi_remote_settings_fn_method_remotesettingsservice_update_config(void*, RustBuffer, RustCallStatus*); + uint32_t ffi_remote_settings_uniffi_contract_version(); + uint16_t uniffi_remote_settings_checksum_constructor_remotesettings_new(); uint16_t uniffi_remote_settings_checksum_method_remotesettings_download_attachment_to_path(); uint16_t uniffi_remote_settings_checksum_method_remotesettings_get_records(); uint16_t uniffi_remote_settings_checksum_method_remotesettings_get_records_since(); @@ -419,12 +359,66 @@ extern "C" { uint16_t uniffi_remote_settings_checksum_method_remotesettingsclient_get_records_map(); uint16_t uniffi_remote_settings_checksum_method_remotesettingsclient_shutdown(); uint16_t uniffi_remote_settings_checksum_method_remotesettingsclient_sync(); + uint16_t uniffi_remote_settings_checksum_constructor_remotesettingsservice_new(); uint16_t uniffi_remote_settings_checksum_method_remotesettingsservice_make_client(); uint16_t uniffi_remote_settings_checksum_method_remotesettingsservice_sync(); uint16_t uniffi_remote_settings_checksum_method_remotesettingsservice_update_config(); - uint16_t uniffi_remote_settings_checksum_constructor_remotesettings_new(); - uint16_t uniffi_remote_settings_checksum_constructor_remotesettingsservice_new(); - uint32_t ffi_remote_settings_uniffi_contract_version(); + RustBuffer ffi_search_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_search_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_search_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_search_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_search_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_u8(uint64_t); + uint8_t ffi_search_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_u8(uint64_t); + void ffi_search_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_i8(uint64_t); + int8_t ffi_search_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_i8(uint64_t); + void ffi_search_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_u16(uint64_t); + uint16_t ffi_search_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_u16(uint64_t); + void ffi_search_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_i16(uint64_t); + int16_t ffi_search_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_i16(uint64_t); + void ffi_search_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_u32(uint64_t); + uint32_t ffi_search_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_u32(uint64_t); + void ffi_search_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_i32(uint64_t); + int32_t ffi_search_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_i32(uint64_t); + void ffi_search_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_u64(uint64_t); + uint64_t ffi_search_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_u64(uint64_t); + void ffi_search_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_i64(uint64_t); + int64_t ffi_search_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_i64(uint64_t); + void ffi_search_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_f32(uint64_t); + float ffi_search_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_f32(uint64_t); + void ffi_search_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_f64(uint64_t); + double ffi_search_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_f64(uint64_t); + void ffi_search_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_pointer(uint64_t); + void* ffi_search_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_pointer(uint64_t); + void ffi_search_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_search_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_rust_buffer(uint64_t); + void ffi_search_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_search_rust_future_cancel_void(uint64_t); + void ffi_search_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_search_rust_future_free_void(uint64_t); void* uniffi_search_fn_clone_searchengineselector(void*, RustCallStatus*); void uniffi_search_fn_free_searchengineselector(void*, RustCallStatus*); void* uniffi_search_fn_constructor_searchengineselector_new(RustCallStatus*); @@ -433,71 +427,74 @@ extern "C" { void uniffi_search_fn_method_searchengineselector_set_config_overrides(void*, RustBuffer, RustCallStatus*); void uniffi_search_fn_method_searchengineselector_set_search_config(void*, RustBuffer, RustCallStatus*); void uniffi_search_fn_method_searchengineselector_use_remote_settings_server(void*, void*, int8_t, RustCallStatus*); - RustBuffer ffi_search_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_search_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_search_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_search_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_u8(uint64_t); - void ffi_search_rust_future_free_u8(uint64_t); - uint8_t ffi_search_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_i8(uint64_t); - void ffi_search_rust_future_free_i8(uint64_t); - int8_t ffi_search_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_u16(uint64_t); - void ffi_search_rust_future_free_u16(uint64_t); - uint16_t ffi_search_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_i16(uint64_t); - void ffi_search_rust_future_free_i16(uint64_t); - int16_t ffi_search_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_u32(uint64_t); - void ffi_search_rust_future_free_u32(uint64_t); - uint32_t ffi_search_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_i32(uint64_t); - void ffi_search_rust_future_free_i32(uint64_t); - int32_t ffi_search_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_u64(uint64_t); - void ffi_search_rust_future_free_u64(uint64_t); - uint64_t ffi_search_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_i64(uint64_t); - void ffi_search_rust_future_free_i64(uint64_t); - int64_t ffi_search_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_f32(uint64_t); - void ffi_search_rust_future_free_f32(uint64_t); - float ffi_search_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_f64(uint64_t); - void ffi_search_rust_future_free_f64(uint64_t); - double ffi_search_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_pointer(uint64_t); - void ffi_search_rust_future_free_pointer(uint64_t); - void* ffi_search_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_rust_buffer(uint64_t); - void ffi_search_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_search_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_search_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_search_rust_future_cancel_void(uint64_t); - void ffi_search_rust_future_free_void(uint64_t); - void ffi_search_rust_future_complete_void(uint64_t, RustCallStatus*); + uint32_t ffi_search_uniffi_contract_version(); + uint16_t uniffi_search_checksum_constructor_searchengineselector_new(); uint16_t uniffi_search_checksum_method_searchengineselector_clear_search_config(); uint16_t uniffi_search_checksum_method_searchengineselector_filter_engine_configuration(); uint16_t uniffi_search_checksum_method_searchengineselector_set_config_overrides(); uint16_t uniffi_search_checksum_method_searchengineselector_set_search_config(); uint16_t uniffi_search_checksum_method_searchengineselector_use_remote_settings_server(); - uint16_t uniffi_search_checksum_constructor_searchengineselector_new(); - uint32_t ffi_search_uniffi_contract_version(); + RustBuffer ffi_suggest_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_suggest_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_suggest_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_suggest_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_u8(uint64_t); + uint8_t ffi_suggest_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_u8(uint64_t); + void ffi_suggest_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_i8(uint64_t); + int8_t ffi_suggest_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_i8(uint64_t); + void ffi_suggest_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_u16(uint64_t); + uint16_t ffi_suggest_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_u16(uint64_t); + void ffi_suggest_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_i16(uint64_t); + int16_t ffi_suggest_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_i16(uint64_t); + void ffi_suggest_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_u32(uint64_t); + uint32_t ffi_suggest_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_u32(uint64_t); + void ffi_suggest_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_i32(uint64_t); + int32_t ffi_suggest_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_i32(uint64_t); + void ffi_suggest_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_u64(uint64_t); + uint64_t ffi_suggest_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_u64(uint64_t); + void ffi_suggest_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_i64(uint64_t); + int64_t ffi_suggest_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_i64(uint64_t); + void ffi_suggest_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_f32(uint64_t); + float ffi_suggest_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_f32(uint64_t); + void ffi_suggest_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_f64(uint64_t); + double ffi_suggest_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_f64(uint64_t); + void ffi_suggest_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_pointer(uint64_t); + void* ffi_suggest_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_pointer(uint64_t); + void ffi_suggest_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_suggest_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_rust_buffer(uint64_t); + void ffi_suggest_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_suggest_rust_future_cancel_void(uint64_t); + void ffi_suggest_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_suggest_rust_future_free_void(uint64_t); void* uniffi_suggest_fn_clone_suggeststore(void*, RustCallStatus*); void uniffi_suggest_fn_free_suggeststore(void*, RustCallStatus*); + void* uniffi_suggest_fn_clone_suggeststorebuilder(void*, RustCallStatus*); + void uniffi_suggest_fn_free_suggeststorebuilder(void*, RustCallStatus*); + int8_t uniffi_suggest_fn_func_raw_suggestion_url_matches(RustBuffer, RustBuffer, RustCallStatus*); void* uniffi_suggest_fn_constructor_suggeststore_new(RustBuffer, void*, RustCallStatus*); int8_t uniffi_suggest_fn_method_suggeststore_any_dismissed_suggestions(void*, RustCallStatus*); void uniffi_suggest_fn_method_suggeststore_clear(void*, RustCallStatus*); @@ -514,8 +511,6 @@ extern "C" { int8_t uniffi_suggest_fn_method_suggeststore_is_dismissed_by_suggestion(void*, RustBuffer, RustCallStatus*); RustBuffer uniffi_suggest_fn_method_suggeststore_query(void*, RustBuffer, RustCallStatus*); RustBuffer uniffi_suggest_fn_method_suggeststore_query_with_metrics(void*, RustBuffer, RustCallStatus*); - void* uniffi_suggest_fn_clone_suggeststorebuilder(void*, RustCallStatus*); - void uniffi_suggest_fn_free_suggeststorebuilder(void*, RustCallStatus*); void* uniffi_suggest_fn_constructor_suggeststorebuilder_new(RustCallStatus*); void* uniffi_suggest_fn_method_suggeststorebuilder_build(void*, RustCallStatus*); void* uniffi_suggest_fn_method_suggeststorebuilder_cache_path(void*, RustBuffer, RustCallStatus*); @@ -524,64 +519,9 @@ extern "C" { void* uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_bucket_name(void*, RustBuffer, RustCallStatus*); void* uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_server(void*, RustBuffer, RustCallStatus*); void* uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_service(void*, void*, RustCallStatus*); - int8_t uniffi_suggest_fn_func_raw_suggestion_url_matches(RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer ffi_suggest_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_suggest_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_suggest_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_suggest_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_u8(uint64_t); - void ffi_suggest_rust_future_free_u8(uint64_t); - uint8_t ffi_suggest_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_i8(uint64_t); - void ffi_suggest_rust_future_free_i8(uint64_t); - int8_t ffi_suggest_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_u16(uint64_t); - void ffi_suggest_rust_future_free_u16(uint64_t); - uint16_t ffi_suggest_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_i16(uint64_t); - void ffi_suggest_rust_future_free_i16(uint64_t); - int16_t ffi_suggest_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_u32(uint64_t); - void ffi_suggest_rust_future_free_u32(uint64_t); - uint32_t ffi_suggest_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_i32(uint64_t); - void ffi_suggest_rust_future_free_i32(uint64_t); - int32_t ffi_suggest_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_u64(uint64_t); - void ffi_suggest_rust_future_free_u64(uint64_t); - uint64_t ffi_suggest_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_i64(uint64_t); - void ffi_suggest_rust_future_free_i64(uint64_t); - int64_t ffi_suggest_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_f32(uint64_t); - void ffi_suggest_rust_future_free_f32(uint64_t); - float ffi_suggest_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_f64(uint64_t); - void ffi_suggest_rust_future_free_f64(uint64_t); - double ffi_suggest_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_pointer(uint64_t); - void ffi_suggest_rust_future_free_pointer(uint64_t); - void* ffi_suggest_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_rust_buffer(uint64_t); - void ffi_suggest_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_suggest_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_suggest_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_suggest_rust_future_cancel_void(uint64_t); - void ffi_suggest_rust_future_free_void(uint64_t); - void ffi_suggest_rust_future_complete_void(uint64_t, RustCallStatus*); + uint32_t ffi_suggest_uniffi_contract_version(); uint16_t uniffi_suggest_checksum_func_raw_suggestion_url_matches(); + uint16_t uniffi_suggest_checksum_constructor_suggeststore_new(); uint16_t uniffi_suggest_checksum_method_suggeststore_any_dismissed_suggestions(); uint16_t uniffi_suggest_checksum_method_suggeststore_clear(); uint16_t uniffi_suggest_checksum_method_suggeststore_clear_dismissed_suggestions(); @@ -597,6 +537,7 @@ extern "C" { uint16_t uniffi_suggest_checksum_method_suggeststore_is_dismissed_by_suggestion(); uint16_t uniffi_suggest_checksum_method_suggeststore_query(); uint16_t uniffi_suggest_checksum_method_suggeststore_query_with_metrics(); + uint16_t uniffi_suggest_checksum_constructor_suggeststorebuilder_new(); uint16_t uniffi_suggest_checksum_method_suggeststorebuilder_build(); uint16_t uniffi_suggest_checksum_method_suggeststorebuilder_cache_path(); uint16_t uniffi_suggest_checksum_method_suggeststorebuilder_data_path(); @@ -604,75 +545,130 @@ extern "C" { uint16_t uniffi_suggest_checksum_method_suggeststorebuilder_remote_settings_bucket_name(); uint16_t uniffi_suggest_checksum_method_suggeststorebuilder_remote_settings_server(); uint16_t uniffi_suggest_checksum_method_suggeststorebuilder_remote_settings_service(); - uint16_t uniffi_suggest_checksum_constructor_suggeststore_new(); - uint16_t uniffi_suggest_checksum_constructor_suggeststorebuilder_new(); - uint32_t ffi_suggest_uniffi_contract_version(); RustBuffer ffi_sync15_rustbuffer_alloc(uint64_t, RustCallStatus*); RustBuffer ffi_sync15_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); void ffi_sync15_rustbuffer_free(RustBuffer, RustCallStatus*); RustBuffer ffi_sync15_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); void ffi_sync15_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_u8(uint64_t); - void ffi_sync15_rust_future_free_u8(uint64_t); uint8_t ffi_sync15_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_u8(uint64_t); void ffi_sync15_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_i8(uint64_t); - void ffi_sync15_rust_future_free_i8(uint64_t); int8_t ffi_sync15_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_i8(uint64_t); void ffi_sync15_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_u16(uint64_t); - void ffi_sync15_rust_future_free_u16(uint64_t); uint16_t ffi_sync15_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_u16(uint64_t); void ffi_sync15_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_i16(uint64_t); - void ffi_sync15_rust_future_free_i16(uint64_t); int16_t ffi_sync15_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_i16(uint64_t); void ffi_sync15_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_u32(uint64_t); - void ffi_sync15_rust_future_free_u32(uint64_t); uint32_t ffi_sync15_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_u32(uint64_t); void ffi_sync15_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_i32(uint64_t); - void ffi_sync15_rust_future_free_i32(uint64_t); int32_t ffi_sync15_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_i32(uint64_t); void ffi_sync15_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_u64(uint64_t); - void ffi_sync15_rust_future_free_u64(uint64_t); uint64_t ffi_sync15_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_u64(uint64_t); void ffi_sync15_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_i64(uint64_t); - void ffi_sync15_rust_future_free_i64(uint64_t); int64_t ffi_sync15_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_i64(uint64_t); void ffi_sync15_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_f32(uint64_t); - void ffi_sync15_rust_future_free_f32(uint64_t); float ffi_sync15_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_f32(uint64_t); void ffi_sync15_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_f64(uint64_t); - void ffi_sync15_rust_future_free_f64(uint64_t); double ffi_sync15_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_f64(uint64_t); void ffi_sync15_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_pointer(uint64_t); - void ffi_sync15_rust_future_free_pointer(uint64_t); void* ffi_sync15_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_pointer(uint64_t); void ffi_sync15_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_rust_buffer(uint64_t); - void ffi_sync15_rust_future_free_rust_buffer(uint64_t); RustBuffer ffi_sync15_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_rust_buffer(uint64_t); void ffi_sync15_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); void ffi_sync15_rust_future_cancel_void(uint64_t); - void ffi_sync15_rust_future_free_void(uint64_t); void ffi_sync15_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_sync15_rust_future_free_void(uint64_t); uint32_t ffi_sync15_uniffi_contract_version(); + RustBuffer ffi_tabs_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_tabs_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_tabs_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_tabs_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_u8(uint64_t); + uint8_t ffi_tabs_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_u8(uint64_t); + void ffi_tabs_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_i8(uint64_t); + int8_t ffi_tabs_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_i8(uint64_t); + void ffi_tabs_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_u16(uint64_t); + uint16_t ffi_tabs_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_u16(uint64_t); + void ffi_tabs_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_i16(uint64_t); + int16_t ffi_tabs_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_i16(uint64_t); + void ffi_tabs_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_u32(uint64_t); + uint32_t ffi_tabs_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_u32(uint64_t); + void ffi_tabs_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_i32(uint64_t); + int32_t ffi_tabs_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_i32(uint64_t); + void ffi_tabs_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_u64(uint64_t); + uint64_t ffi_tabs_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_u64(uint64_t); + void ffi_tabs_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_i64(uint64_t); + int64_t ffi_tabs_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_i64(uint64_t); + void ffi_tabs_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_f32(uint64_t); + float ffi_tabs_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_f32(uint64_t); + void ffi_tabs_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_f64(uint64_t); + double ffi_tabs_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_f64(uint64_t); + void ffi_tabs_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_pointer(uint64_t); + void* ffi_tabs_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_pointer(uint64_t); + void ffi_tabs_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_tabs_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_rust_buffer(uint64_t); + void ffi_tabs_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_tabs_rust_future_cancel_void(uint64_t); + void ffi_tabs_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_tabs_rust_future_free_void(uint64_t); void* uniffi_tabs_fn_clone_remotecommandstore(void*, RustCallStatus*); void uniffi_tabs_fn_free_remotecommandstore(void*, RustCallStatus*); + void* uniffi_tabs_fn_clone_tabsbridgedengine(void*, RustCallStatus*); + void uniffi_tabs_fn_free_tabsbridgedengine(void*, RustCallStatus*); + void* uniffi_tabs_fn_clone_tabsstore(void*, RustCallStatus*); + void uniffi_tabs_fn_free_tabsstore(void*, RustCallStatus*); int8_t uniffi_tabs_fn_method_remotecommandstore_add_remote_command(void*, RustBuffer, RustBuffer, RustCallStatus*); int8_t uniffi_tabs_fn_method_remotecommandstore_add_remote_command_at(void*, RustBuffer, RustBuffer, int64_t, RustCallStatus*); RustBuffer uniffi_tabs_fn_method_remotecommandstore_get_unsent_commands(void*, RustCallStatus*); int8_t uniffi_tabs_fn_method_remotecommandstore_remove_remote_command(void*, RustBuffer, RustBuffer, RustCallStatus*); int8_t uniffi_tabs_fn_method_remotecommandstore_set_pending_command_sent(void*, RustBuffer, RustCallStatus*); - void* uniffi_tabs_fn_clone_tabsbridgedengine(void*, RustCallStatus*); - void uniffi_tabs_fn_free_tabsbridgedengine(void*, RustCallStatus*); RustBuffer uniffi_tabs_fn_method_tabsbridgedengine_apply(void*, RustCallStatus*); RustBuffer uniffi_tabs_fn_method_tabsbridgedengine_ensure_current_sync_id(void*, RustBuffer, RustCallStatus*); int64_t uniffi_tabs_fn_method_tabsbridgedengine_last_sync(void*, RustCallStatus*); @@ -686,8 +682,6 @@ extern "C" { RustBuffer uniffi_tabs_fn_method_tabsbridgedengine_sync_id(void*, RustCallStatus*); void uniffi_tabs_fn_method_tabsbridgedengine_sync_started(void*, RustCallStatus*); void uniffi_tabs_fn_method_tabsbridgedengine_wipe(void*, RustCallStatus*); - void* uniffi_tabs_fn_clone_tabsstore(void*, RustCallStatus*); - void uniffi_tabs_fn_free_tabsstore(void*, RustCallStatus*); void* uniffi_tabs_fn_constructor_tabsstore_new(RustBuffer, RustCallStatus*); void* uniffi_tabs_fn_method_tabsstore_bridged_engine(void*, RustCallStatus*); void uniffi_tabs_fn_method_tabsstore_close_connection(void*, RustCallStatus*); @@ -695,62 +689,7 @@ extern "C" { void* uniffi_tabs_fn_method_tabsstore_new_remote_command_store(void*, RustCallStatus*); void uniffi_tabs_fn_method_tabsstore_register_with_sync_manager(void*, RustCallStatus*); void uniffi_tabs_fn_method_tabsstore_set_local_tabs(void*, RustBuffer, RustCallStatus*); - RustBuffer ffi_tabs_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_tabs_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_tabs_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_tabs_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_u8(uint64_t); - void ffi_tabs_rust_future_free_u8(uint64_t); - uint8_t ffi_tabs_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_i8(uint64_t); - void ffi_tabs_rust_future_free_i8(uint64_t); - int8_t ffi_tabs_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_u16(uint64_t); - void ffi_tabs_rust_future_free_u16(uint64_t); - uint16_t ffi_tabs_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_i16(uint64_t); - void ffi_tabs_rust_future_free_i16(uint64_t); - int16_t ffi_tabs_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_u32(uint64_t); - void ffi_tabs_rust_future_free_u32(uint64_t); - uint32_t ffi_tabs_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_i32(uint64_t); - void ffi_tabs_rust_future_free_i32(uint64_t); - int32_t ffi_tabs_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_u64(uint64_t); - void ffi_tabs_rust_future_free_u64(uint64_t); - uint64_t ffi_tabs_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_i64(uint64_t); - void ffi_tabs_rust_future_free_i64(uint64_t); - int64_t ffi_tabs_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_f32(uint64_t); - void ffi_tabs_rust_future_free_f32(uint64_t); - float ffi_tabs_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_f64(uint64_t); - void ffi_tabs_rust_future_free_f64(uint64_t); - double ffi_tabs_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_pointer(uint64_t); - void ffi_tabs_rust_future_free_pointer(uint64_t); - void* ffi_tabs_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_rust_buffer(uint64_t); - void ffi_tabs_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_tabs_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_tabs_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_tabs_rust_future_cancel_void(uint64_t); - void ffi_tabs_rust_future_free_void(uint64_t); - void ffi_tabs_rust_future_complete_void(uint64_t, RustCallStatus*); + uint32_t ffi_tabs_uniffi_contract_version(); uint16_t uniffi_tabs_checksum_method_remotecommandstore_add_remote_command(); uint16_t uniffi_tabs_checksum_method_remotecommandstore_add_remote_command_at(); uint16_t uniffi_tabs_checksum_method_remotecommandstore_get_unsent_commands(); @@ -769,16 +708,73 @@ extern "C" { uint16_t uniffi_tabs_checksum_method_tabsbridgedengine_sync_id(); uint16_t uniffi_tabs_checksum_method_tabsbridgedengine_sync_started(); uint16_t uniffi_tabs_checksum_method_tabsbridgedengine_wipe(); + uint16_t uniffi_tabs_checksum_constructor_tabsstore_new(); uint16_t uniffi_tabs_checksum_method_tabsstore_bridged_engine(); uint16_t uniffi_tabs_checksum_method_tabsstore_close_connection(); uint16_t uniffi_tabs_checksum_method_tabsstore_get_all(); uint16_t uniffi_tabs_checksum_method_tabsstore_new_remote_command_store(); uint16_t uniffi_tabs_checksum_method_tabsstore_register_with_sync_manager(); uint16_t uniffi_tabs_checksum_method_tabsstore_set_local_tabs(); - uint16_t uniffi_tabs_checksum_constructor_tabsstore_new(); - uint32_t ffi_tabs_uniffi_contract_version(); + RustBuffer ffi_webext_storage_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_webext_storage_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_webext_storage_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_webext_storage_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_u8(uint64_t); + uint8_t ffi_webext_storage_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_u8(uint64_t); + void ffi_webext_storage_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_i8(uint64_t); + int8_t ffi_webext_storage_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_i8(uint64_t); + void ffi_webext_storage_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_u16(uint64_t); + uint16_t ffi_webext_storage_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_u16(uint64_t); + void ffi_webext_storage_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_i16(uint64_t); + int16_t ffi_webext_storage_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_i16(uint64_t); + void ffi_webext_storage_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_u32(uint64_t); + uint32_t ffi_webext_storage_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_u32(uint64_t); + void ffi_webext_storage_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_i32(uint64_t); + int32_t ffi_webext_storage_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_i32(uint64_t); + void ffi_webext_storage_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_u64(uint64_t); + uint64_t ffi_webext_storage_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_u64(uint64_t); + void ffi_webext_storage_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_i64(uint64_t); + int64_t ffi_webext_storage_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_i64(uint64_t); + void ffi_webext_storage_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_f32(uint64_t); + float ffi_webext_storage_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_f32(uint64_t); + void ffi_webext_storage_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_f64(uint64_t); + double ffi_webext_storage_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_f64(uint64_t); + void ffi_webext_storage_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_pointer(uint64_t); + void* ffi_webext_storage_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_pointer(uint64_t); + void ffi_webext_storage_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_webext_storage_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_rust_buffer(uint64_t); + void ffi_webext_storage_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_webext_storage_rust_future_cancel_void(uint64_t); + void ffi_webext_storage_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_webext_storage_rust_future_free_void(uint64_t); void* uniffi_webext_storage_fn_clone_webextstoragebridgedengine(void*, RustCallStatus*); void uniffi_webext_storage_fn_free_webextstoragebridgedengine(void*, RustCallStatus*); + void* uniffi_webext_storage_fn_clone_webextstoragestore(void*, RustCallStatus*); + void uniffi_webext_storage_fn_free_webextstoragestore(void*, RustCallStatus*); RustBuffer uniffi_webext_storage_fn_method_webextstoragebridgedengine_apply(void*, RustCallStatus*); RustBuffer uniffi_webext_storage_fn_method_webextstoragebridgedengine_ensure_current_sync_id(void*, RustBuffer, RustCallStatus*); int64_t uniffi_webext_storage_fn_method_webextstoragebridgedengine_last_sync(void*, RustCallStatus*); @@ -792,8 +788,6 @@ extern "C" { RustBuffer uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_id(void*, RustCallStatus*); void uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_started(void*, RustCallStatus*); void uniffi_webext_storage_fn_method_webextstoragebridgedengine_wipe(void*, RustCallStatus*); - void* uniffi_webext_storage_fn_clone_webextstoragestore(void*, RustCallStatus*); - void uniffi_webext_storage_fn_free_webextstoragestore(void*, RustCallStatus*); void* uniffi_webext_storage_fn_constructor_webextstoragestore_new(RustBuffer, RustCallStatus*); void* uniffi_webext_storage_fn_method_webextstoragestore_bridged_engine(void*, RustCallStatus*); RustBuffer uniffi_webext_storage_fn_method_webextstoragestore_clear(void*, RustBuffer, RustCallStatus*); @@ -803,62 +797,7 @@ extern "C" { RustBuffer uniffi_webext_storage_fn_method_webextstoragestore_get_synced_changes(void*, RustCallStatus*); RustBuffer uniffi_webext_storage_fn_method_webextstoragestore_remove(void*, RustBuffer, RustBuffer, RustCallStatus*); RustBuffer uniffi_webext_storage_fn_method_webextstoragestore_set(void*, RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer ffi_webext_storage_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_webext_storage_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_webext_storage_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_webext_storage_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_u8(uint64_t); - void ffi_webext_storage_rust_future_free_u8(uint64_t); - uint8_t ffi_webext_storage_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_i8(uint64_t); - void ffi_webext_storage_rust_future_free_i8(uint64_t); - int8_t ffi_webext_storage_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_u16(uint64_t); - void ffi_webext_storage_rust_future_free_u16(uint64_t); - uint16_t ffi_webext_storage_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_i16(uint64_t); - void ffi_webext_storage_rust_future_free_i16(uint64_t); - int16_t ffi_webext_storage_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_u32(uint64_t); - void ffi_webext_storage_rust_future_free_u32(uint64_t); - uint32_t ffi_webext_storage_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_i32(uint64_t); - void ffi_webext_storage_rust_future_free_i32(uint64_t); - int32_t ffi_webext_storage_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_u64(uint64_t); - void ffi_webext_storage_rust_future_free_u64(uint64_t); - uint64_t ffi_webext_storage_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_i64(uint64_t); - void ffi_webext_storage_rust_future_free_i64(uint64_t); - int64_t ffi_webext_storage_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_f32(uint64_t); - void ffi_webext_storage_rust_future_free_f32(uint64_t); - float ffi_webext_storage_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_f64(uint64_t); - void ffi_webext_storage_rust_future_free_f64(uint64_t); - double ffi_webext_storage_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_pointer(uint64_t); - void ffi_webext_storage_rust_future_free_pointer(uint64_t); - void* ffi_webext_storage_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_rust_buffer(uint64_t); - void ffi_webext_storage_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_webext_storage_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_webext_storage_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_webext_storage_rust_future_cancel_void(uint64_t); - void ffi_webext_storage_rust_future_free_void(uint64_t); - void ffi_webext_storage_rust_future_complete_void(uint64_t, RustCallStatus*); + uint32_t ffi_webext_storage_uniffi_contract_version(); uint16_t uniffi_webext_storage_checksum_method_webextstoragebridgedengine_apply(); uint16_t uniffi_webext_storage_checksum_method_webextstoragebridgedengine_ensure_current_sync_id(); uint16_t uniffi_webext_storage_checksum_method_webextstoragebridgedengine_last_sync(); @@ -872,6 +811,7 @@ extern "C" { uint16_t uniffi_webext_storage_checksum_method_webextstoragebridgedengine_sync_id(); uint16_t uniffi_webext_storage_checksum_method_webextstoragebridgedengine_sync_started(); uint16_t uniffi_webext_storage_checksum_method_webextstoragebridgedengine_wipe(); + uint16_t uniffi_webext_storage_checksum_constructor_webextstoragestore_new(); uint16_t uniffi_webext_storage_checksum_method_webextstoragestore_bridged_engine(); uint16_t uniffi_webext_storage_checksum_method_webextstoragestore_clear(); uint16_t uniffi_webext_storage_checksum_method_webextstoragestore_close(); @@ -880,957 +820,257 @@ extern "C" { uint16_t uniffi_webext_storage_checksum_method_webextstoragestore_get_synced_changes(); uint16_t uniffi_webext_storage_checksum_method_webextstoragestore_remove(); uint16_t uniffi_webext_storage_checksum_method_webextstoragestore_set(); - uint16_t uniffi_webext_storage_checksum_constructor_webextstoragestore_new(); - uint32_t ffi_webext_storage_uniffi_contract_version(); #ifdef MOZ_UNIFFI_FIXTURES - uint64_t uniffi_arithmetical_fn_func_add(uint64_t, uint64_t, RustCallStatus*); - uint64_t uniffi_arithmetical_fn_func_div(uint64_t, uint64_t, RustCallStatus*); - int8_t uniffi_arithmetical_fn_func_equal(uint64_t, uint64_t, RustCallStatus*); - uint64_t uniffi_arithmetical_fn_func_sub(uint64_t, uint64_t, RustCallStatus*); - RustBuffer ffi_arithmetical_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_arithmetical_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_arithmetical_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_arithmetical_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_u8(uint64_t); - void ffi_arithmetical_rust_future_free_u8(uint64_t); - uint8_t ffi_arithmetical_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_i8(uint64_t); - void ffi_arithmetical_rust_future_free_i8(uint64_t); - int8_t ffi_arithmetical_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_u16(uint64_t); - void ffi_arithmetical_rust_future_free_u16(uint64_t); - uint16_t ffi_arithmetical_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_i16(uint64_t); - void ffi_arithmetical_rust_future_free_i16(uint64_t); - int16_t ffi_arithmetical_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_u32(uint64_t); - void ffi_arithmetical_rust_future_free_u32(uint64_t); - uint32_t ffi_arithmetical_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_i32(uint64_t); - void ffi_arithmetical_rust_future_free_i32(uint64_t); - int32_t ffi_arithmetical_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_u64(uint64_t); - void ffi_arithmetical_rust_future_free_u64(uint64_t); - uint64_t ffi_arithmetical_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_i64(uint64_t); - void ffi_arithmetical_rust_future_free_i64(uint64_t); - int64_t ffi_arithmetical_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_f32(uint64_t); - void ffi_arithmetical_rust_future_free_f32(uint64_t); - float ffi_arithmetical_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_f64(uint64_t); - void ffi_arithmetical_rust_future_free_f64(uint64_t); - double ffi_arithmetical_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_pointer(uint64_t); - void ffi_arithmetical_rust_future_free_pointer(uint64_t); - void* ffi_arithmetical_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_rust_buffer(uint64_t); - void ffi_arithmetical_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_arithmetical_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_arithmetical_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_arithmetical_rust_future_cancel_void(uint64_t); - void ffi_arithmetical_rust_future_free_void(uint64_t); - void ffi_arithmetical_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_arithmetical_checksum_func_add(); - uint16_t uniffi_arithmetical_checksum_func_div(); - uint16_t uniffi_arithmetical_checksum_func_equal(); - uint16_t uniffi_arithmetical_checksum_func_sub(); - uint32_t ffi_arithmetical_uniffi_contract_version(); - RustBuffer uniffi_uniffi_custom_types_fn_func_echo_explicit_value(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_custom_types_fn_func_echo_gapped_value(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_custom_types_fn_func_echo_sequential_value(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_custom_types_fn_func_get_custom_types_demo(RustBuffer, RustCallStatus*); - uint8_t uniffi_uniffi_custom_types_fn_func_get_explicit_discriminant(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_custom_types_fn_func_get_explicit_enum_values(RustCallStatus*); - uint8_t uniffi_uniffi_custom_types_fn_func_get_gapped_discriminant(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_custom_types_fn_func_get_gapped_enum_values(RustCallStatus*); - uint8_t uniffi_uniffi_custom_types_fn_func_get_sequential_discriminant(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_custom_types_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_custom_types_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_custom_types_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_custom_types_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_custom_types_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_custom_types_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_custom_types_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_custom_types_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_custom_types_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_custom_types_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_custom_types_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_custom_types_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_f32(uint64_t); - float ffi_uniffi_custom_types_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_f64(uint64_t); - double ffi_uniffi_custom_types_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_custom_types_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_custom_types_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_custom_types_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_custom_types_rust_future_cancel_void(uint64_t); - void ffi_uniffi_custom_types_rust_future_free_void(uint64_t); - void ffi_uniffi_custom_types_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_custom_types_checksum_func_echo_explicit_value(); - uint16_t uniffi_uniffi_custom_types_checksum_func_echo_gapped_value(); - uint16_t uniffi_uniffi_custom_types_checksum_func_echo_sequential_value(); - uint16_t uniffi_uniffi_custom_types_checksum_func_get_custom_types_demo(); - uint16_t uniffi_uniffi_custom_types_checksum_func_get_explicit_discriminant(); - uint16_t uniffi_uniffi_custom_types_checksum_func_get_explicit_enum_values(); - uint16_t uniffi_uniffi_custom_types_checksum_func_get_gapped_discriminant(); - uint16_t uniffi_uniffi_custom_types_checksum_func_get_gapped_enum_values(); - uint16_t uniffi_uniffi_custom_types_checksum_func_get_sequential_discriminant(); - uint32_t ffi_uniffi_custom_types_uniffi_contract_version(); - double uniffi_uniffi_fixture_external_types_fn_func_gradient(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_fixture_external_types_fn_func_intersection(RustBuffer, RustBuffer, RustCallStatus*); - void uniffi_uniffi_fixture_external_types_fn_func_move_sprite_to_origin(void*, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_external_types_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_external_types_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_external_types_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_fixture_external_types_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_fixture_external_types_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_fixture_external_types_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_fixture_external_types_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_fixture_external_types_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_fixture_external_types_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_fixture_external_types_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_fixture_external_types_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_f32(uint64_t); - float ffi_uniffi_fixture_external_types_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_f64(uint64_t); - double ffi_uniffi_fixture_external_types_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_fixture_external_types_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_fixture_external_types_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_external_types_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_cancel_void(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_free_void(uint64_t); - void ffi_uniffi_fixture_external_types_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_fixture_external_types_checksum_func_gradient(); - uint16_t uniffi_uniffi_fixture_external_types_checksum_func_intersection(); - uint16_t uniffi_uniffi_fixture_external_types_checksum_func_move_sprite_to_origin(); - uint32_t ffi_uniffi_fixture_external_types_uniffi_contract_version(); - typedef void (*CallbackInterfaceLoggerMethod0)(uint64_t, RustBuffer, void*, RustCallStatus*); - typedef void (*CallbackInterfaceLoggerMethod1)(uint64_t, RustBuffer, uint32_t, RustBuffer, void*, RustCallStatus*); - typedef void (*CallbackInterfaceLoggerMethod2)(uint64_t, void*, RustCallStatus*); - struct VTableCallbackInterfaceLogger { - CallbackInterfaceLoggerMethod0 log; - CallbackInterfaceLoggerMethod1 log_repeat; - CallbackInterfaceLoggerMethod2 finished; - CallbackInterfaceFree uniffi_free; + RustBuffer ffi_uniffi_bindings_tests_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_uniffi_bindings_tests_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_uniffi_bindings_tests_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_uniffi_bindings_tests_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_u8(uint64_t); + uint8_t ffi_uniffi_bindings_tests_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_u8(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_i8(uint64_t); + int8_t ffi_uniffi_bindings_tests_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_i8(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_u16(uint64_t); + uint16_t ffi_uniffi_bindings_tests_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_u16(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_i16(uint64_t); + int16_t ffi_uniffi_bindings_tests_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_i16(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_u32(uint64_t); + uint32_t ffi_uniffi_bindings_tests_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_u32(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_i32(uint64_t); + int32_t ffi_uniffi_bindings_tests_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_i32(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_u64(uint64_t); + uint64_t ffi_uniffi_bindings_tests_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_u64(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_i64(uint64_t); + int64_t ffi_uniffi_bindings_tests_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_i64(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_f32(uint64_t); + float ffi_uniffi_bindings_tests_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_f32(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_f64(uint64_t); + double ffi_uniffi_bindings_tests_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_f64(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_pointer(uint64_t); + void* ffi_uniffi_bindings_tests_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_pointer(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_uniffi_bindings_tests_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_rust_buffer(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_rust_future_cancel_void(uint64_t); + void ffi_uniffi_bindings_tests_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_rust_future_free_void(uint64_t); + void* uniffi_uniffi_bindings_tests_fn_clone_asyncinterface(void*, RustCallStatus*); + void uniffi_uniffi_bindings_tests_fn_free_asyncinterface(void*, RustCallStatus*); + void* uniffi_uniffi_bindings_tests_fn_clone_complexmethods(void*, RustCallStatus*); + void uniffi_uniffi_bindings_tests_fn_free_complexmethods(void*, RustCallStatus*); + void* uniffi_uniffi_bindings_tests_fn_clone_testinterface(void*, RustCallStatus*); + void uniffi_uniffi_bindings_tests_fn_free_testinterface(void*, RustCallStatus*); + typedef void (*CallbackInterfaceTestCallbackInterfaceMethod0)(uint64_t, uint32_t*, RustCallStatus*); + typedef void (*CallbackInterfaceFreeuniffi_bindings_tests_TestCallbackInterface)(uint64_t); + struct VTableCallbackInterfaceTestCallbackInterface { + CallbackInterfaceTestCallbackInterfaceMethod0 get_value; + CallbackInterfaceFreeuniffi_bindings_tests_TestCallbackInterface uniffi_free; }; - void uniffi_uniffi_fixture_callbacks_fn_init_callback_vtable_logger(VTableCallbackInterfaceLogger*); - void uniffi_uniffi_fixture_callbacks_fn_func_call_log_repeat(uint64_t, RustBuffer, uint32_t, RustBuffer, RustCallStatus*); - void uniffi_uniffi_fixture_callbacks_fn_func_log_even_numbers(uint64_t, RustBuffer, RustCallStatus*); - void uniffi_uniffi_fixture_callbacks_fn_func_log_even_numbers_main_thread(uint64_t, RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_callbacks_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_callbacks_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_callbacks_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_fixture_callbacks_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_fixture_callbacks_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_fixture_callbacks_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_fixture_callbacks_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_fixture_callbacks_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_fixture_callbacks_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_fixture_callbacks_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_fixture_callbacks_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_f32(uint64_t); - float ffi_uniffi_fixture_callbacks_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_f64(uint64_t); - double ffi_uniffi_fixture_callbacks_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_fixture_callbacks_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_fixture_callbacks_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_callbacks_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_cancel_void(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_free_void(uint64_t); - void ffi_uniffi_fixture_callbacks_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_fixture_callbacks_checksum_func_call_log_repeat(); - uint16_t uniffi_uniffi_fixture_callbacks_checksum_func_log_even_numbers(); - uint16_t uniffi_uniffi_fixture_callbacks_checksum_func_log_even_numbers_main_thread(); - uint16_t uniffi_uniffi_fixture_callbacks_checksum_method_logger_log(); - uint16_t uniffi_uniffi_fixture_callbacks_checksum_method_logger_log_repeat(); - uint16_t uniffi_uniffi_fixture_callbacks_checksum_method_logger_finished(); - uint32_t ffi_uniffi_fixture_callbacks_uniffi_contract_version(); - typedef void (*CallbackInterfaceRustTaskMethod0)(uint64_t, void*, RustCallStatus*); - typedef void (*CallbackInterfaceWorkerQueueMethod0)(uint64_t, void*, void*, RustCallStatus*); - struct VTableCallbackInterfaceRustTask { - CallbackInterfaceRustTaskMethod0 run; - CallbackInterfaceFree uniffi_free; - }; - struct VTableCallbackInterfaceWorkerQueue { - CallbackInterfaceWorkerQueueMethod0 add_task; - CallbackInterfaceFree uniffi_free; - }; - void* uniffi_uniffi_fixture_futures_fn_clone_futuretester(void*, RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_free_futuretester(void*, RustCallStatus*); - void* uniffi_uniffi_fixture_futures_fn_constructor_futuretester_init(RustCallStatus*); - uint32_t uniffi_uniffi_fixture_futures_fn_method_futuretester_complete_futures(void*, uint8_t, RustCallStatus*); - uint64_t uniffi_uniffi_fixture_futures_fn_method_futuretester_make_future(void*); - void uniffi_uniffi_fixture_futures_fn_method_futuretester_wake_futures(void*, RustCallStatus*); - void* uniffi_uniffi_fixture_futures_fn_clone_rusttask(void*, RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_free_rusttask(void*, RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_method_rusttask_run(void*, RustCallStatus*); - void* uniffi_uniffi_fixture_futures_fn_clone_traveller(void*, RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_free_traveller(void*, RustCallStatus*); - void* uniffi_uniffi_fixture_futures_fn_constructor_traveller_new(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_fixture_futures_fn_method_traveller_name(void*, RustCallStatus*); - void* uniffi_uniffi_fixture_futures_fn_clone_workerqueue(void*, RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_free_workerqueue(void*, RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_method_workerqueue_add_task(void*, void*, RustCallStatus*); - uint64_t uniffi_uniffi_fixture_futures_fn_func_expensive_computation(); - void uniffi_uniffi_fixture_futures_fn_func_initialize_gecko_global_worker_queue(RustCallStatus*); - void uniffi_uniffi_fixture_futures_fn_func_initialize_global_worker_queue(void*, RustCallStatus*); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_f32(float); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_f64(double); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_i16(int16_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_i32(int32_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_i64(int64_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_i8(int8_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_map(RustBuffer); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_obj(void*); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_string(RustBuffer); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_u16(uint16_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_u32(uint32_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_u64(uint64_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_u8(uint8_t); - uint64_t uniffi_uniffi_fixture_futures_fn_func_roundtrip_vec(RustBuffer); - RustBuffer ffi_uniffi_fixture_futures_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_futures_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_fixture_futures_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_futures_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_fixture_futures_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_fixture_futures_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_fixture_futures_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_fixture_futures_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_fixture_futures_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_fixture_futures_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_fixture_futures_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_fixture_futures_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_f32(uint64_t); - float ffi_uniffi_fixture_futures_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_f64(uint64_t); - double ffi_uniffi_fixture_futures_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_fixture_futures_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_fixture_futures_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_futures_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_futures_rust_future_cancel_void(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_free_void(uint64_t); - void ffi_uniffi_fixture_futures_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_expensive_computation(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_initialize_gecko_global_worker_queue(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_initialize_global_worker_queue(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_f32(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_f64(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_i16(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_i32(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_i64(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_i8(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_map(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_obj(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_string(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_u16(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_u32(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_u64(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_u8(); - uint16_t uniffi_uniffi_fixture_futures_checksum_func_roundtrip_vec(); - uint16_t uniffi_uniffi_fixture_futures_checksum_method_futuretester_complete_futures(); - uint16_t uniffi_uniffi_fixture_futures_checksum_method_futuretester_make_future(); - uint16_t uniffi_uniffi_fixture_futures_checksum_method_futuretester_wake_futures(); - uint16_t uniffi_uniffi_fixture_futures_checksum_method_rusttask_run(); - uint16_t uniffi_uniffi_fixture_futures_checksum_method_traveller_name(); - uint16_t uniffi_uniffi_fixture_futures_checksum_method_workerqueue_add_task(); - uint16_t uniffi_uniffi_fixture_futures_checksum_constructor_futuretester_init(); - uint16_t uniffi_uniffi_fixture_futures_checksum_constructor_traveller_new(); - uint32_t ffi_uniffi_fixture_futures_uniffi_contract_version(); - double uniffi_uniffi_geometry_fn_func_gradient(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_geometry_fn_func_intersection(RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_geometry_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_geometry_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_geometry_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_geometry_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_geometry_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_geometry_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_geometry_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_geometry_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_geometry_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_geometry_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_geometry_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_geometry_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_geometry_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_geometry_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_geometry_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_geometry_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_geometry_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_geometry_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_geometry_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_geometry_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_geometry_rust_future_free_f32(uint64_t); - float ffi_uniffi_geometry_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_geometry_rust_future_free_f64(uint64_t); - double ffi_uniffi_geometry_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_geometry_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_geometry_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_geometry_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_geometry_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_geometry_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_geometry_rust_future_cancel_void(uint64_t); - void ffi_uniffi_geometry_rust_future_free_void(uint64_t); - void ffi_uniffi_geometry_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_geometry_checksum_func_gradient(); - uint16_t uniffi_uniffi_geometry_checksum_func_intersection(); - uint32_t ffi_uniffi_geometry_uniffi_contract_version(); - void* uniffi_uniffi_fixture_refcounts_fn_clone_singletonobject(void*, RustCallStatus*); - void uniffi_uniffi_fixture_refcounts_fn_free_singletonobject(void*, RustCallStatus*); - void uniffi_uniffi_fixture_refcounts_fn_method_singletonobject_method(void*, RustCallStatus*); - int32_t uniffi_uniffi_fixture_refcounts_fn_func_get_js_refcount(RustCallStatus*); - void* uniffi_uniffi_fixture_refcounts_fn_func_get_singleton(RustCallStatus*); - RustBuffer ffi_uniffi_fixture_refcounts_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_refcounts_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_fixture_refcounts_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_fixture_refcounts_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_fixture_refcounts_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_fixture_refcounts_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_fixture_refcounts_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_fixture_refcounts_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_fixture_refcounts_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_fixture_refcounts_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_fixture_refcounts_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_f32(uint64_t); - float ffi_uniffi_fixture_refcounts_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_f64(uint64_t); - double ffi_uniffi_fixture_refcounts_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_fixture_refcounts_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_fixture_refcounts_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_fixture_refcounts_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_cancel_void(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_free_void(uint64_t); - void ffi_uniffi_fixture_refcounts_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_fixture_refcounts_checksum_func_get_js_refcount(); - uint16_t uniffi_uniffi_fixture_refcounts_checksum_func_get_singleton(); - uint16_t uniffi_uniffi_fixture_refcounts_checksum_method_singletonobject_method(); - uint32_t ffi_uniffi_fixture_refcounts_uniffi_contract_version(); - void* uniffi_uniffi_rondpoint_fn_clone_optionneur(void*, RustCallStatus*); - void uniffi_uniffi_rondpoint_fn_free_optionneur(void*, RustCallStatus*); - void* uniffi_uniffi_rondpoint_fn_constructor_optionneur_new(RustCallStatus*); - int8_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_boolean(void*, int8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_enum(void*, RustBuffer, RustCallStatus*); - float uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_f32(void*, float, RustCallStatus*); - double uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_f64(void*, double, RustCallStatus*); - int16_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i16_dec(void*, int16_t, RustCallStatus*); - int16_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i16_hex(void*, int16_t, RustCallStatus*); - int32_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i32_dec(void*, int32_t, RustCallStatus*); - int32_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i32_hex(void*, int32_t, RustCallStatus*); - int64_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i64_dec(void*, int64_t, RustCallStatus*); - int64_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i64_hex(void*, int64_t, RustCallStatus*); - int8_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i8_dec(void*, int8_t, RustCallStatus*); - int8_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i8_hex(void*, int8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_null(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_sequence(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_string(void*, RustBuffer, RustCallStatus*); - uint16_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u16_dec(void*, uint16_t, RustCallStatus*); - uint16_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u16_hex(void*, uint16_t, RustCallStatus*); - uint32_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_dec(void*, uint32_t, RustCallStatus*); - uint32_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_hex(void*, uint32_t, RustCallStatus*); - uint32_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_oct(void*, uint32_t, RustCallStatus*); - uint64_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u64_dec(void*, uint64_t, RustCallStatus*); - uint64_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u64_hex(void*, uint64_t, RustCallStatus*); - uint8_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u8_dec(void*, uint8_t, RustCallStatus*); - uint8_t uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u8_hex(void*, uint8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_zero(void*, RustBuffer, RustCallStatus*); - void* uniffi_uniffi_rondpoint_fn_clone_retourneur(void*, RustCallStatus*); - void uniffi_uniffi_rondpoint_fn_free_retourneur(void*, RustCallStatus*); - void* uniffi_uniffi_rondpoint_fn_constructor_retourneur_new(RustCallStatus*); - int8_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_boolean(void*, int8_t, RustCallStatus*); - double uniffi_uniffi_rondpoint_fn_method_retourneur_identique_double(void*, double, RustCallStatus*); - float uniffi_uniffi_rondpoint_fn_method_retourneur_identique_float(void*, float, RustCallStatus*); - int16_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i16(void*, int16_t, RustCallStatus*); - int32_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i32(void*, int32_t, RustCallStatus*); - int64_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i64(void*, int64_t, RustCallStatus*); - int8_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i8(void*, int8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_retourneur_identique_nombres(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_retourneur_identique_nombres_signes(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_retourneur_identique_optionneur_dictionnaire(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_retourneur_identique_string(void*, RustBuffer, RustCallStatus*); - uint16_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u16(void*, uint16_t, RustCallStatus*); - uint32_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u32(void*, uint32_t, RustCallStatus*); - uint64_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u64(void*, uint64_t, RustCallStatus*); - uint8_t uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u8(void*, uint8_t, RustCallStatus*); - void* uniffi_uniffi_rondpoint_fn_clone_stringifier(void*, RustCallStatus*); - void uniffi_uniffi_rondpoint_fn_free_stringifier(void*, RustCallStatus*); - void* uniffi_uniffi_rondpoint_fn_constructor_stringifier_new(RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_boolean(void*, int8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_double(void*, double, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_float(void*, float, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i16(void*, int16_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i32(void*, int32_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i64(void*, int64_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i8(void*, int8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u16(void*, uint16_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u32(void*, uint32_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u64(void*, uint64_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u8(void*, uint8_t, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_method_stringifier_well_known_string(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_func_copie_carte(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_func_copie_dictionnaire(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_func_copie_enumeration(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_rondpoint_fn_func_copie_enumerations(RustBuffer, RustCallStatus*); - int8_t uniffi_uniffi_rondpoint_fn_func_switcheroo(int8_t, RustCallStatus*); - RustBuffer ffi_uniffi_rondpoint_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_rondpoint_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_rondpoint_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_rondpoint_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_rondpoint_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_rondpoint_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_rondpoint_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_rondpoint_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_rondpoint_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_rondpoint_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_rondpoint_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_rondpoint_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_f32(uint64_t); - float ffi_uniffi_rondpoint_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_f64(uint64_t); - double ffi_uniffi_rondpoint_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_rondpoint_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_rondpoint_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_rondpoint_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_rondpoint_rust_future_cancel_void(uint64_t); - void ffi_uniffi_rondpoint_rust_future_free_void(uint64_t); - void ffi_uniffi_rondpoint_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_rondpoint_checksum_func_copie_carte(); - uint16_t uniffi_uniffi_rondpoint_checksum_func_copie_dictionnaire(); - uint16_t uniffi_uniffi_rondpoint_checksum_func_copie_enumeration(); - uint16_t uniffi_uniffi_rondpoint_checksum_func_copie_enumerations(); - uint16_t uniffi_uniffi_rondpoint_checksum_func_switcheroo(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_boolean(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_enum(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_f32(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_f64(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i16_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i16_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i32_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i32_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i64_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i64_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i8_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_i8_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_null(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_sequence(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_string(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u16_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u16_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u32_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u32_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u32_oct(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u64_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u64_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u8_dec(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_u8_hex(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_optionneur_sinon_zero(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_boolean(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_double(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_float(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_i16(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_i32(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_i64(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_i8(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_nombres(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_nombres_signes(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_optionneur_dictionnaire(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_string(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_u16(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_u32(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_u64(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_retourneur_identique_u8(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_boolean(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_double(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_float(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_i16(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_i32(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_i64(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_i8(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_u16(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_u32(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_u64(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_to_string_u8(); - uint16_t uniffi_uniffi_rondpoint_checksum_method_stringifier_well_known_string(); - uint16_t uniffi_uniffi_rondpoint_checksum_constructor_optionneur_new(); - uint16_t uniffi_uniffi_rondpoint_checksum_constructor_retourneur_new(); - uint16_t uniffi_uniffi_rondpoint_checksum_constructor_stringifier_new(); - uint32_t ffi_uniffi_rondpoint_uniffi_contract_version(); - void* uniffi_uniffi_sprites_fn_clone_sprite(void*, RustCallStatus*); - void uniffi_uniffi_sprites_fn_free_sprite(void*, RustCallStatus*); - void* uniffi_uniffi_sprites_fn_constructor_sprite_new(RustBuffer, RustCallStatus*); - void* uniffi_uniffi_sprites_fn_constructor_sprite_new_relative_to(RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_sprites_fn_method_sprite_get_position(void*, RustCallStatus*); - void uniffi_uniffi_sprites_fn_method_sprite_move_by(void*, RustBuffer, RustCallStatus*); - void uniffi_uniffi_sprites_fn_method_sprite_move_to(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_sprites_fn_func_translate(RustBuffer, RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_sprites_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_sprites_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_sprites_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_sprites_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_sprites_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_sprites_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_sprites_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_sprites_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_sprites_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_sprites_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_sprites_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_sprites_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_sprites_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_sprites_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_sprites_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_sprites_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_sprites_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_sprites_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_sprites_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_sprites_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_sprites_rust_future_free_f32(uint64_t); - float ffi_uniffi_sprites_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_sprites_rust_future_free_f64(uint64_t); - double ffi_uniffi_sprites_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_sprites_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_sprites_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_sprites_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_sprites_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_sprites_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_sprites_rust_future_cancel_void(uint64_t); - void ffi_uniffi_sprites_rust_future_free_void(uint64_t); - void ffi_uniffi_sprites_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_sprites_checksum_func_translate(); - uint16_t uniffi_uniffi_sprites_checksum_method_sprite_get_position(); - uint16_t uniffi_uniffi_sprites_checksum_method_sprite_move_by(); - uint16_t uniffi_uniffi_sprites_checksum_method_sprite_move_to(); - uint16_t uniffi_uniffi_sprites_checksum_constructor_sprite_new(); - uint16_t uniffi_uniffi_sprites_checksum_constructor_sprite_new_relative_to(); - uint32_t ffi_uniffi_sprites_uniffi_contract_version(); - void* uniffi_uniffi_todolist_fn_clone_todolist(void*, RustCallStatus*); - void uniffi_uniffi_todolist_fn_free_todolist(void*, RustCallStatus*); - void* uniffi_uniffi_todolist_fn_constructor_todolist_new(RustCallStatus*); - void uniffi_uniffi_todolist_fn_method_todolist_add_entries(void*, RustBuffer, RustCallStatus*); - void uniffi_uniffi_todolist_fn_method_todolist_add_entry(void*, RustBuffer, RustCallStatus*); - void uniffi_uniffi_todolist_fn_method_todolist_add_item(void*, RustBuffer, RustCallStatus*); - void uniffi_uniffi_todolist_fn_method_todolist_add_items(void*, RustBuffer, RustCallStatus*); - void uniffi_uniffi_todolist_fn_method_todolist_clear_item(void*, RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_method_todolist_get_entries(void*, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_method_todolist_get_first(void*, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_method_todolist_get_items(void*, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_method_todolist_get_last(void*, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_method_todolist_get_last_entry(void*, RustCallStatus*); - void uniffi_uniffi_todolist_fn_method_todolist_make_default(void*, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_func_create_entry_with(RustBuffer, RustCallStatus*); - RustBuffer uniffi_uniffi_todolist_fn_func_get_default_list(RustCallStatus*); - void uniffi_uniffi_todolist_fn_func_set_default_list(void*, RustCallStatus*); - RustBuffer ffi_uniffi_todolist_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_todolist_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_todolist_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_todolist_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_todolist_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_todolist_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_todolist_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_todolist_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_todolist_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_todolist_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_todolist_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_todolist_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_todolist_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_todolist_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_todolist_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_todolist_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_todolist_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_todolist_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_todolist_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_todolist_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_todolist_rust_future_free_f32(uint64_t); - float ffi_uniffi_todolist_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_todolist_rust_future_free_f64(uint64_t); - double ffi_uniffi_todolist_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_todolist_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_todolist_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_todolist_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_todolist_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_todolist_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_todolist_rust_future_cancel_void(uint64_t); - void ffi_uniffi_todolist_rust_future_free_void(uint64_t); - void ffi_uniffi_todolist_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_todolist_checksum_func_create_entry_with(); - uint16_t uniffi_uniffi_todolist_checksum_func_get_default_list(); - uint16_t uniffi_uniffi_todolist_checksum_func_set_default_list(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_add_entries(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_add_entry(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_add_item(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_add_items(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_clear_item(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_get_entries(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_get_first(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_get_items(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_get_last(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_get_last_entry(); - uint16_t uniffi_uniffi_todolist_checksum_method_todolist_make_default(); - uint16_t uniffi_uniffi_todolist_checksum_constructor_todolist_new(); - uint32_t ffi_uniffi_todolist_uniffi_contract_version(); - typedef void (*CallbackInterfaceCalcMethod0)(uint64_t, uint32_t, uint32_t, uint32_t*, RustCallStatus*); - struct VTableCallbackInterfaceCalc { - CallbackInterfaceCalcMethod0 add; - CallbackInterfaceFree uniffi_free; - }; - void* uniffi_uniffi_trait_interfaces_fn_clone_calc(void*, RustCallStatus*); - void uniffi_uniffi_trait_interfaces_fn_free_calc(void*, RustCallStatus*); - uint32_t uniffi_uniffi_trait_interfaces_fn_method_calc_add(void*, uint32_t, uint32_t, RustCallStatus*); - void* uniffi_uniffi_trait_interfaces_fn_func_make_buggy_calculator(RustCallStatus*); - void* uniffi_uniffi_trait_interfaces_fn_func_make_calculator(RustCallStatus*); - RustBuffer ffi_uniffi_trait_interfaces_rustbuffer_alloc(uint64_t, RustCallStatus*); - RustBuffer ffi_uniffi_trait_interfaces_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rustbuffer_free(RustBuffer, RustCallStatus*); - RustBuffer ffi_uniffi_trait_interfaces_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_u8(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_u8(uint64_t); - uint8_t ffi_uniffi_trait_interfaces_rust_future_complete_u8(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_i8(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_i8(uint64_t); - int8_t ffi_uniffi_trait_interfaces_rust_future_complete_i8(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_u16(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_u16(uint64_t); - uint16_t ffi_uniffi_trait_interfaces_rust_future_complete_u16(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_i16(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_i16(uint64_t); - int16_t ffi_uniffi_trait_interfaces_rust_future_complete_i16(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_u32(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_u32(uint64_t); - uint32_t ffi_uniffi_trait_interfaces_rust_future_complete_u32(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_i32(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_i32(uint64_t); - int32_t ffi_uniffi_trait_interfaces_rust_future_complete_i32(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_u64(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_u64(uint64_t); - uint64_t ffi_uniffi_trait_interfaces_rust_future_complete_u64(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_i64(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_i64(uint64_t); - int64_t ffi_uniffi_trait_interfaces_rust_future_complete_i64(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_f32(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_f32(uint64_t); - float ffi_uniffi_trait_interfaces_rust_future_complete_f32(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_f64(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_f64(uint64_t); - double ffi_uniffi_trait_interfaces_rust_future_complete_f64(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_pointer(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_pointer(uint64_t); - void* ffi_uniffi_trait_interfaces_rust_future_complete_pointer(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_rust_buffer(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_rust_buffer(uint64_t); - RustBuffer ffi_uniffi_trait_interfaces_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); - void ffi_uniffi_trait_interfaces_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_cancel_void(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_free_void(uint64_t); - void ffi_uniffi_trait_interfaces_rust_future_complete_void(uint64_t, RustCallStatus*); - uint16_t uniffi_uniffi_trait_interfaces_checksum_func_make_buggy_calculator(); - uint16_t uniffi_uniffi_trait_interfaces_checksum_func_make_calculator(); - uint16_t uniffi_uniffi_trait_interfaces_checksum_method_calc_add(); - uint32_t ffi_uniffi_trait_interfaces_uniffi_contract_version(); + void uniffi_uniffi_bindings_tests_fn_init_callback_vtable_testcallbackinterface(VTableCallbackInterfaceTestCallbackInterface*); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_f32(float); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_f64(double); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i16(int16_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i32(int32_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i64(int64_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i8(int8_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_map(RustBuffer); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_obj(void*); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_string(RustBuffer); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u16(uint16_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u32(uint32_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u64(uint64_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u8(uint8_t); + uint64_t uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_vec(RustBuffer); + void* uniffi_uniffi_bindings_tests_fn_func_clone_interface(void*, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_func_with_default(RustBuffer, RustCallStatus*); + void uniffi_uniffi_bindings_tests_fn_func_func_with_error(uint32_t, RustCallStatus*); + void uniffi_uniffi_bindings_tests_fn_func_func_with_flat_error(uint32_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_func_with_multi_word_arg(RustBuffer, RustCallStatus*); + uint32_t uniffi_uniffi_bindings_tests_fn_func_invoke_test_callback_interface_method(uint64_t, RustCallStatus*); + int8_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_bool(int8_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_compound(RustBuffer, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_enum(RustBuffer, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_rec(RustBuffer, RustCallStatus*); + uint64_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_custom_type(uint64_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_enum_no_data(RustBuffer, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_enum_with_data(RustBuffer, RustCallStatus*); + float uniffi_uniffi_bindings_tests_fn_func_roundtrip_f32(float, RustCallStatus*); + double uniffi_uniffi_bindings_tests_fn_func_roundtrip_f64(double, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_hash_map(RustBuffer, RustCallStatus*); + int16_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_i16(int16_t, RustCallStatus*); + int32_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_i32(int32_t, RustCallStatus*); + int64_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_i64(int64_t, RustCallStatus*); + int8_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_i8(int8_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_option(RustBuffer, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_simple_rec(RustBuffer, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_string(RustBuffer, RustCallStatus*); + uint16_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_u16(uint16_t, RustCallStatus*); + uint32_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_u32(uint32_t, RustCallStatus*); + uint64_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_u64(uint64_t, RustCallStatus*); + uint8_t uniffi_uniffi_bindings_tests_fn_func_roundtrip_u8(uint8_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_roundtrip_vec(RustBuffer, RustCallStatus*); + double uniffi_uniffi_bindings_tests_fn_func_sum_with_many_types(uint8_t, int8_t, uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t, float, double, int8_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_func_swap_test_interfaces(RustBuffer, RustCallStatus*); + void uniffi_uniffi_bindings_tests_fn_func_test_func(RustCallStatus*); + void* uniffi_uniffi_bindings_tests_fn_constructor_asyncinterface_new(RustBuffer, RustCallStatus*); + uint64_t uniffi_uniffi_bindings_tests_fn_method_asyncinterface_name(void*); + void* uniffi_uniffi_bindings_tests_fn_constructor_complexmethods_new(RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_method_complexmethods_method_with_default(void*, RustBuffer, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_fn_method_complexmethods_method_with_multi_word_arg(void*, RustBuffer, RustCallStatus*); + void* uniffi_uniffi_bindings_tests_fn_constructor_testinterface_new(uint32_t, RustCallStatus*); + uint32_t uniffi_uniffi_bindings_tests_fn_method_testinterface_get_value(void*, RustCallStatus*); + uint32_t uniffi_uniffi_bindings_tests_fn_method_testinterface_ref_count(void*, RustCallStatus*); + uint32_t ffi_uniffi_bindings_tests_uniffi_contract_version(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_f32(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_f64(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_i16(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_i32(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_i64(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_i8(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_map(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_obj(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_string(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_u16(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_u32(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_u64(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_u8(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_async_roundtrip_vec(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_clone_interface(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_func_with_default(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_func_with_error(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_func_with_flat_error(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_func_with_multi_word_arg(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_invoke_test_callback_interface_method(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_bool(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_complex_compound(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_complex_enum(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_complex_rec(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_custom_type(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_enum_no_data(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_enum_with_data(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_f32(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_f64(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_hash_map(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_i16(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_i32(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_i64(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_i8(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_option(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_simple_rec(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_string(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_u16(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_u32(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_u64(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_u8(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_roundtrip_vec(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_sum_with_many_types(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_swap_test_interfaces(); + uint16_t uniffi_uniffi_bindings_tests_checksum_func_test_func(); + uint16_t uniffi_uniffi_bindings_tests_checksum_constructor_asyncinterface_new(); + uint16_t uniffi_uniffi_bindings_tests_checksum_method_asyncinterface_name(); + uint16_t uniffi_uniffi_bindings_tests_checksum_constructor_complexmethods_new(); + uint16_t uniffi_uniffi_bindings_tests_checksum_method_complexmethods_method_with_default(); + uint16_t uniffi_uniffi_bindings_tests_checksum_method_complexmethods_method_with_multi_word_arg(); + uint16_t uniffi_uniffi_bindings_tests_checksum_constructor_testinterface_new(); + uint16_t uniffi_uniffi_bindings_tests_checksum_method_testinterface_get_value(); + uint16_t uniffi_uniffi_bindings_tests_checksum_method_testinterface_ref_count(); + uint16_t uniffi_uniffi_bindings_tests_checksum_method_testcallbackinterface_get_value(); + RustBuffer ffi_uniffi_bindings_tests_external_types_rustbuffer_alloc(uint64_t, RustCallStatus*); + RustBuffer ffi_uniffi_bindings_tests_external_types_rustbuffer_from_bytes(ForeignBytes, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rustbuffer_free(RustBuffer, RustCallStatus*); + RustBuffer ffi_uniffi_bindings_tests_external_types_rustbuffer_reserve(RustBuffer, uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_u8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_u8(uint64_t); + uint8_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_u8(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_u8(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_i8(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_i8(uint64_t); + int8_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_i8(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_i8(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_u16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_u16(uint64_t); + uint16_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_u16(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_u16(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_i16(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_i16(uint64_t); + int16_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_i16(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_i16(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_u32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_u32(uint64_t); + uint32_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_u32(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_u32(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_i32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_i32(uint64_t); + int32_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_i32(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_i32(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_u64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_u64(uint64_t); + uint64_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_u64(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_u64(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_i64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_i64(uint64_t); + int64_t ffi_uniffi_bindings_tests_external_types_rust_future_complete_i64(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_i64(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_f32(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_f32(uint64_t); + float ffi_uniffi_bindings_tests_external_types_rust_future_complete_f32(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_f32(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_f64(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_f64(uint64_t); + double ffi_uniffi_bindings_tests_external_types_rust_future_complete_f64(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_f64(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_pointer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_pointer(uint64_t); + void* ffi_uniffi_bindings_tests_external_types_rust_future_complete_pointer(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_pointer(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_rust_buffer(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_rust_buffer(uint64_t); + RustBuffer ffi_uniffi_bindings_tests_external_types_rust_future_complete_rust_buffer(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_rust_buffer(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_poll_void(uint64_t, RustFutureContinuationCallback, uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_cancel_void(uint64_t); + void ffi_uniffi_bindings_tests_external_types_rust_future_complete_void(uint64_t, RustCallStatus*); + void ffi_uniffi_bindings_tests_external_types_rust_future_free_void(uint64_t); + uint64_t uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_custom_type(uint64_t, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_enum(RustBuffer, RustCallStatus*); + void* uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_interface(void*, RustCallStatus*); + RustBuffer uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_record(RustBuffer, RustCallStatus*); + uint32_t ffi_uniffi_bindings_tests_external_types_uniffi_contract_version(); + uint16_t uniffi_uniffi_bindings_tests_external_types_checksum_func_roundtrip_ext_custom_type(); + uint16_t uniffi_uniffi_bindings_tests_external_types_checksum_func_roundtrip_ext_enum(); + uint16_t uniffi_uniffi_bindings_tests_external_types_checksum_func_roundtrip_ext_interface(); + uint16_t uniffi_uniffi_bindings_tests_external_types_checksum_func_roundtrip_ext_record(); #endif /* MOZ_UNIFFI_FIXTURES */ } +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -// Define pointer types and FfiValueObjectHandle* classes +// Define pointer types const static mozilla::uniffi::UniFFIPointerType kContextIdContextIdComponentPointerType { "context_id::ContextIDComponent"_ns, @@ -2783,25 +2023,25 @@ class FfiValueObjectHandleWebextstorageWebExtStorageStore { }; #ifdef MOZ_UNIFFI_FIXTURES -const static mozilla::uniffi::UniFFIPointerType kFuturesFutureTesterPointerType { - "futures::FutureTester"_ns, - uniffi_uniffi_fixture_futures_fn_clone_futuretester, - uniffi_uniffi_fixture_futures_fn_free_futuretester, +const static mozilla::uniffi::UniFFIPointerType kUniffiBindingsTestsTestInterfacePointerType { + "uniffi_bindings_tests::TestInterface"_ns, + uniffi_uniffi_bindings_tests_fn_clone_testinterface, + uniffi_uniffi_bindings_tests_fn_free_testinterface, }; -class FfiValueObjectHandleFuturesFutureTester { +class FfiValueObjectHandleUniffiBindingsTestsTestInterface { private: void* mValue = nullptr; public: - FfiValueObjectHandleFuturesFutureTester() = default; - explicit FfiValueObjectHandleFuturesFutureTester(void* aValue) : mValue(aValue) {} + FfiValueObjectHandleUniffiBindingsTestsTestInterface() = default; + explicit FfiValueObjectHandleUniffiBindingsTestsTestInterface(void* aValue) : mValue(aValue) {} // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleFuturesFutureTester(const FfiValueObjectHandleFuturesFutureTester&) = delete; - FfiValueObjectHandleFuturesFutureTester& operator=(const FfiValueObjectHandleFuturesFutureTester&) = delete; + FfiValueObjectHandleUniffiBindingsTestsTestInterface(const FfiValueObjectHandleUniffiBindingsTestsTestInterface&) = delete; + FfiValueObjectHandleUniffiBindingsTestsTestInterface& operator=(const FfiValueObjectHandleUniffiBindingsTestsTestInterface&) = delete; - FfiValueObjectHandleFuturesFutureTester& operator=(FfiValueObjectHandleFuturesFutureTester&& aOther) { + FfiValueObjectHandleUniffiBindingsTestsTestInterface& operator=(FfiValueObjectHandleUniffiBindingsTestsTestInterface&& aOther) { FreeHandle(); mValue = aOther.mValue; aOther.mValue = nullptr; @@ -2815,7 +2055,7 @@ class FfiValueObjectHandleFuturesFutureTester { return; } dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kFuturesFutureTesterPointerType)) { + if (!value.IsSamePtrType(&kUniffiBindingsTestsTestInterfacePointerType)) { aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); return; } @@ -2826,7 +2066,7 @@ class FfiValueObjectHandleFuturesFutureTester { void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, ErrorResult& aError) { aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kFuturesFutureTesterPointerType); + dom::UniFFIPointer::Create(mValue, &kUniffiBindingsTestsTestInterfacePointerType); mValue = nullptr; } @@ -2836,45 +2076,45 @@ class FfiValueObjectHandleFuturesFutureTester { return temp; } - static FfiValueObjectHandleFuturesFutureTester FromRust(void* aValue) { - return FfiValueObjectHandleFuturesFutureTester(aValue); + static FfiValueObjectHandleUniffiBindingsTestsTestInterface FromRust(void* aValue) { + return FfiValueObjectHandleUniffiBindingsTestsTestInterface(aValue); } void FreeHandle() { if (mValue) { RustCallStatus callStatus{}; - (uniffi_uniffi_fixture_futures_fn_free_futuretester)(mValue, &callStatus); + (uniffi_uniffi_bindings_tests_fn_free_testinterface)(mValue, &callStatus); // No need to check `RustCallStatus`, it's only part of the API to match // other FFI calls. The free function can never fail. } } - ~FfiValueObjectHandleFuturesFutureTester() { + ~FfiValueObjectHandleUniffiBindingsTestsTestInterface() { // If the pointer is non-null, this means Lift/IntoRust was never called // because there was some failure along the way. Free the pointer to avoid a // leak FreeHandle(); } }; -const static mozilla::uniffi::UniFFIPointerType kFuturesRustTaskPointerType { - "futures::RustTask"_ns, - uniffi_uniffi_fixture_futures_fn_clone_rusttask, - uniffi_uniffi_fixture_futures_fn_free_rusttask, +const static mozilla::uniffi::UniFFIPointerType kUniffiBindingsTestsAsyncInterfacePointerType { + "uniffi_bindings_tests::AsyncInterface"_ns, + uniffi_uniffi_bindings_tests_fn_clone_asyncinterface, + uniffi_uniffi_bindings_tests_fn_free_asyncinterface, }; -class FfiValueObjectHandleFuturesRustTask { +class FfiValueObjectHandleUniffiBindingsTestsAsyncInterface { private: void* mValue = nullptr; public: - FfiValueObjectHandleFuturesRustTask() = default; - explicit FfiValueObjectHandleFuturesRustTask(void* aValue) : mValue(aValue) {} + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface() = default; + explicit FfiValueObjectHandleUniffiBindingsTestsAsyncInterface(void* aValue) : mValue(aValue) {} // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleFuturesRustTask(const FfiValueObjectHandleFuturesRustTask&) = delete; - FfiValueObjectHandleFuturesRustTask& operator=(const FfiValueObjectHandleFuturesRustTask&) = delete; + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface(const FfiValueObjectHandleUniffiBindingsTestsAsyncInterface&) = delete; + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface& operator=(const FfiValueObjectHandleUniffiBindingsTestsAsyncInterface&) = delete; - FfiValueObjectHandleFuturesRustTask& operator=(FfiValueObjectHandleFuturesRustTask&& aOther) { + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface& operator=(FfiValueObjectHandleUniffiBindingsTestsAsyncInterface&& aOther) { FreeHandle(); mValue = aOther.mValue; aOther.mValue = nullptr; @@ -2888,7 +2128,7 @@ class FfiValueObjectHandleFuturesRustTask { return; } dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kFuturesRustTaskPointerType)) { + if (!value.IsSamePtrType(&kUniffiBindingsTestsAsyncInterfacePointerType)) { aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); return; } @@ -2899,7 +2139,7 @@ class FfiValueObjectHandleFuturesRustTask { void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, ErrorResult& aError) { aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kFuturesRustTaskPointerType); + dom::UniFFIPointer::Create(mValue, &kUniffiBindingsTestsAsyncInterfacePointerType); mValue = nullptr; } @@ -2909,45 +2149,45 @@ class FfiValueObjectHandleFuturesRustTask { return temp; } - static FfiValueObjectHandleFuturesRustTask FromRust(void* aValue) { - return FfiValueObjectHandleFuturesRustTask(aValue); + static FfiValueObjectHandleUniffiBindingsTestsAsyncInterface FromRust(void* aValue) { + return FfiValueObjectHandleUniffiBindingsTestsAsyncInterface(aValue); } void FreeHandle() { if (mValue) { RustCallStatus callStatus{}; - (uniffi_uniffi_fixture_futures_fn_free_rusttask)(mValue, &callStatus); + (uniffi_uniffi_bindings_tests_fn_free_asyncinterface)(mValue, &callStatus); // No need to check `RustCallStatus`, it's only part of the API to match // other FFI calls. The free function can never fail. } } - ~FfiValueObjectHandleFuturesRustTask() { + ~FfiValueObjectHandleUniffiBindingsTestsAsyncInterface() { // If the pointer is non-null, this means Lift/IntoRust was never called // because there was some failure along the way. Free the pointer to avoid a // leak FreeHandle(); } }; -const static mozilla::uniffi::UniFFIPointerType kFuturesTravellerPointerType { - "futures::Traveller"_ns, - uniffi_uniffi_fixture_futures_fn_clone_traveller, - uniffi_uniffi_fixture_futures_fn_free_traveller, +const static mozilla::uniffi::UniFFIPointerType kUniffiBindingsTestsComplexMethodsPointerType { + "uniffi_bindings_tests::ComplexMethods"_ns, + uniffi_uniffi_bindings_tests_fn_clone_complexmethods, + uniffi_uniffi_bindings_tests_fn_free_complexmethods, }; -class FfiValueObjectHandleFuturesTraveller { +class FfiValueObjectHandleUniffiBindingsTestsComplexMethods { private: void* mValue = nullptr; public: - FfiValueObjectHandleFuturesTraveller() = default; - explicit FfiValueObjectHandleFuturesTraveller(void* aValue) : mValue(aValue) {} + FfiValueObjectHandleUniffiBindingsTestsComplexMethods() = default; + explicit FfiValueObjectHandleUniffiBindingsTestsComplexMethods(void* aValue) : mValue(aValue) {} // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleFuturesTraveller(const FfiValueObjectHandleFuturesTraveller&) = delete; - FfiValueObjectHandleFuturesTraveller& operator=(const FfiValueObjectHandleFuturesTraveller&) = delete; + FfiValueObjectHandleUniffiBindingsTestsComplexMethods(const FfiValueObjectHandleUniffiBindingsTestsComplexMethods&) = delete; + FfiValueObjectHandleUniffiBindingsTestsComplexMethods& operator=(const FfiValueObjectHandleUniffiBindingsTestsComplexMethods&) = delete; - FfiValueObjectHandleFuturesTraveller& operator=(FfiValueObjectHandleFuturesTraveller&& aOther) { + FfiValueObjectHandleUniffiBindingsTestsComplexMethods& operator=(FfiValueObjectHandleUniffiBindingsTestsComplexMethods&& aOther) { FreeHandle(); mValue = aOther.mValue; aOther.mValue = nullptr; @@ -2961,7 +2201,7 @@ class FfiValueObjectHandleFuturesTraveller { return; } dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kFuturesTravellerPointerType)) { + if (!value.IsSamePtrType(&kUniffiBindingsTestsComplexMethodsPointerType)) { aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); return; } @@ -2972,7 +2212,7 @@ class FfiValueObjectHandleFuturesTraveller { void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, ErrorResult& aError) { aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kFuturesTravellerPointerType); + dom::UniFFIPointer::Create(mValue, &kUniffiBindingsTestsComplexMethodsPointerType); mValue = nullptr; } @@ -2982,604 +2222,20 @@ class FfiValueObjectHandleFuturesTraveller { return temp; } - static FfiValueObjectHandleFuturesTraveller FromRust(void* aValue) { - return FfiValueObjectHandleFuturesTraveller(aValue); + static FfiValueObjectHandleUniffiBindingsTestsComplexMethods FromRust(void* aValue) { + return FfiValueObjectHandleUniffiBindingsTestsComplexMethods(aValue); } void FreeHandle() { if (mValue) { RustCallStatus callStatus{}; - (uniffi_uniffi_fixture_futures_fn_free_traveller)(mValue, &callStatus); + (uniffi_uniffi_bindings_tests_fn_free_complexmethods)(mValue, &callStatus); // No need to check `RustCallStatus`, it's only part of the API to match // other FFI calls. The free function can never fail. } } - ~FfiValueObjectHandleFuturesTraveller() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kFuturesWorkerQueuePointerType { - "futures::WorkerQueue"_ns, - uniffi_uniffi_fixture_futures_fn_clone_workerqueue, - uniffi_uniffi_fixture_futures_fn_free_workerqueue, -}; - -class FfiValueObjectHandleFuturesWorkerQueue { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleFuturesWorkerQueue() = default; - explicit FfiValueObjectHandleFuturesWorkerQueue(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleFuturesWorkerQueue(const FfiValueObjectHandleFuturesWorkerQueue&) = delete; - FfiValueObjectHandleFuturesWorkerQueue& operator=(const FfiValueObjectHandleFuturesWorkerQueue&) = delete; - - FfiValueObjectHandleFuturesWorkerQueue& operator=(FfiValueObjectHandleFuturesWorkerQueue&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kFuturesWorkerQueuePointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kFuturesWorkerQueuePointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleFuturesWorkerQueue FromRust(void* aValue) { - return FfiValueObjectHandleFuturesWorkerQueue(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_fixture_futures_fn_free_workerqueue)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleFuturesWorkerQueue() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kRefcountsSingletonObjectPointerType { - "refcounts::SingletonObject"_ns, - uniffi_uniffi_fixture_refcounts_fn_clone_singletonobject, - uniffi_uniffi_fixture_refcounts_fn_free_singletonobject, -}; - -class FfiValueObjectHandleRefcountsSingletonObject { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleRefcountsSingletonObject() = default; - explicit FfiValueObjectHandleRefcountsSingletonObject(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleRefcountsSingletonObject(const FfiValueObjectHandleRefcountsSingletonObject&) = delete; - FfiValueObjectHandleRefcountsSingletonObject& operator=(const FfiValueObjectHandleRefcountsSingletonObject&) = delete; - - FfiValueObjectHandleRefcountsSingletonObject& operator=(FfiValueObjectHandleRefcountsSingletonObject&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kRefcountsSingletonObjectPointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kRefcountsSingletonObjectPointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleRefcountsSingletonObject FromRust(void* aValue) { - return FfiValueObjectHandleRefcountsSingletonObject(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_fixture_refcounts_fn_free_singletonobject)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleRefcountsSingletonObject() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kRondpointOptionneurPointerType { - "rondpoint::Optionneur"_ns, - uniffi_uniffi_rondpoint_fn_clone_optionneur, - uniffi_uniffi_rondpoint_fn_free_optionneur, -}; - -class FfiValueObjectHandleRondpointOptionneur { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleRondpointOptionneur() = default; - explicit FfiValueObjectHandleRondpointOptionneur(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleRondpointOptionneur(const FfiValueObjectHandleRondpointOptionneur&) = delete; - FfiValueObjectHandleRondpointOptionneur& operator=(const FfiValueObjectHandleRondpointOptionneur&) = delete; - - FfiValueObjectHandleRondpointOptionneur& operator=(FfiValueObjectHandleRondpointOptionneur&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kRondpointOptionneurPointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kRondpointOptionneurPointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleRondpointOptionneur FromRust(void* aValue) { - return FfiValueObjectHandleRondpointOptionneur(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_rondpoint_fn_free_optionneur)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleRondpointOptionneur() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kRondpointRetourneurPointerType { - "rondpoint::Retourneur"_ns, - uniffi_uniffi_rondpoint_fn_clone_retourneur, - uniffi_uniffi_rondpoint_fn_free_retourneur, -}; - -class FfiValueObjectHandleRondpointRetourneur { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleRondpointRetourneur() = default; - explicit FfiValueObjectHandleRondpointRetourneur(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleRondpointRetourneur(const FfiValueObjectHandleRondpointRetourneur&) = delete; - FfiValueObjectHandleRondpointRetourneur& operator=(const FfiValueObjectHandleRondpointRetourneur&) = delete; - - FfiValueObjectHandleRondpointRetourneur& operator=(FfiValueObjectHandleRondpointRetourneur&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kRondpointRetourneurPointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kRondpointRetourneurPointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleRondpointRetourneur FromRust(void* aValue) { - return FfiValueObjectHandleRondpointRetourneur(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_rondpoint_fn_free_retourneur)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleRondpointRetourneur() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kRondpointStringifierPointerType { - "rondpoint::Stringifier"_ns, - uniffi_uniffi_rondpoint_fn_clone_stringifier, - uniffi_uniffi_rondpoint_fn_free_stringifier, -}; - -class FfiValueObjectHandleRondpointStringifier { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleRondpointStringifier() = default; - explicit FfiValueObjectHandleRondpointStringifier(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleRondpointStringifier(const FfiValueObjectHandleRondpointStringifier&) = delete; - FfiValueObjectHandleRondpointStringifier& operator=(const FfiValueObjectHandleRondpointStringifier&) = delete; - - FfiValueObjectHandleRondpointStringifier& operator=(FfiValueObjectHandleRondpointStringifier&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kRondpointStringifierPointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kRondpointStringifierPointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleRondpointStringifier FromRust(void* aValue) { - return FfiValueObjectHandleRondpointStringifier(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_rondpoint_fn_free_stringifier)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleRondpointStringifier() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kSpritesSpritePointerType { - "sprites::Sprite"_ns, - uniffi_uniffi_sprites_fn_clone_sprite, - uniffi_uniffi_sprites_fn_free_sprite, -}; - -class FfiValueObjectHandleSpritesSprite { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleSpritesSprite() = default; - explicit FfiValueObjectHandleSpritesSprite(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleSpritesSprite(const FfiValueObjectHandleSpritesSprite&) = delete; - FfiValueObjectHandleSpritesSprite& operator=(const FfiValueObjectHandleSpritesSprite&) = delete; - - FfiValueObjectHandleSpritesSprite& operator=(FfiValueObjectHandleSpritesSprite&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kSpritesSpritePointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kSpritesSpritePointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleSpritesSprite FromRust(void* aValue) { - return FfiValueObjectHandleSpritesSprite(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_sprites_fn_free_sprite)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleSpritesSprite() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kTodolistTodoListPointerType { - "todolist::TodoList"_ns, - uniffi_uniffi_todolist_fn_clone_todolist, - uniffi_uniffi_todolist_fn_free_todolist, -}; - -class FfiValueObjectHandleTodolistTodoList { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleTodolistTodoList() = default; - explicit FfiValueObjectHandleTodolistTodoList(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleTodolistTodoList(const FfiValueObjectHandleTodolistTodoList&) = delete; - FfiValueObjectHandleTodolistTodoList& operator=(const FfiValueObjectHandleTodolistTodoList&) = delete; - - FfiValueObjectHandleTodolistTodoList& operator=(FfiValueObjectHandleTodolistTodoList&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kTodolistTodoListPointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kTodolistTodoListPointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleTodolistTodoList FromRust(void* aValue) { - return FfiValueObjectHandleTodolistTodoList(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_todolist_fn_free_todolist)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleTodolistTodoList() { - // If the pointer is non-null, this means Lift/IntoRust was never called - // because there was some failure along the way. Free the pointer to avoid a - // leak - FreeHandle(); - } -}; -const static mozilla::uniffi::UniFFIPointerType kUniffiTraitInterfacesCalcPointerType { - "uniffi_trait_interfaces::Calc"_ns, - uniffi_uniffi_trait_interfaces_fn_clone_calc, - uniffi_uniffi_trait_interfaces_fn_free_calc, -}; - -class FfiValueObjectHandleUniffiTraitInterfacesCalc { - private: - void* mValue = nullptr; - - public: - FfiValueObjectHandleUniffiTraitInterfacesCalc() = default; - explicit FfiValueObjectHandleUniffiTraitInterfacesCalc(void* aValue) : mValue(aValue) {} - - // Delete copy constructor and assignment as this type is non-copyable. - FfiValueObjectHandleUniffiTraitInterfacesCalc(const FfiValueObjectHandleUniffiTraitInterfacesCalc&) = delete; - FfiValueObjectHandleUniffiTraitInterfacesCalc& operator=(const FfiValueObjectHandleUniffiTraitInterfacesCalc&) = delete; - - FfiValueObjectHandleUniffiTraitInterfacesCalc& operator=(FfiValueObjectHandleUniffiTraitInterfacesCalc&& aOther) { - FreeHandle(); - mValue = aOther.mValue; - aOther.mValue = nullptr; - return *this; - } - - void Lower(const dom::OwningUniFFIScaffoldingValue& aValue, - ErrorResult& aError) { - if (!aValue.IsUniFFIPointer()) { - aError.ThrowTypeError("Expected UniFFI pointer argument"_ns); - return; - } - dom::UniFFIPointer& value = aValue.GetAsUniFFIPointer(); - if (!value.IsSamePtrType(&kUniffiTraitInterfacesCalcPointerType)) { - aError.ThrowTypeError("Incorrect UniFFI pointer type"_ns); - return; - } - FreeHandle(); - mValue = value.ClonePtr(); - } - - void Lift(JSContext* aContext, dom::OwningUniFFIScaffoldingValue* aDest, - ErrorResult& aError) { - aDest->SetAsUniFFIPointer() = - dom::UniFFIPointer::Create(mValue, &kUniffiTraitInterfacesCalcPointerType); - mValue = nullptr; - } - - void* IntoRust() { - auto temp = mValue; - mValue = nullptr; - return temp; - } - - static FfiValueObjectHandleUniffiTraitInterfacesCalc FromRust(void* aValue) { - return FfiValueObjectHandleUniffiTraitInterfacesCalc(aValue); - } - - void FreeHandle() { - if (mValue) { - RustCallStatus callStatus{}; - (uniffi_uniffi_trait_interfaces_fn_free_calc)(mValue, &callStatus); - // No need to check `RustCallStatus`, it's only part of the API to match - // other FFI calls. The free function can never fail. - } - } - - ~FfiValueObjectHandleUniffiTraitInterfacesCalc() { + ~FfiValueObjectHandleUniffiBindingsTestsComplexMethods() { // If the pointer is non-null, this means Lift/IntoRust was never called // because there was some failure along the way. Free the pointer to avoid a // leak @@ -3588,631 +2244,166 @@ class FfiValueObjectHandleUniffiTraitInterfacesCalc { }; #endif /* MOZ_UNIFFI_FIXTURES */ -// Callback interface method handlers, vtables, etc. +Maybe> ReadPointer(const GlobalObject& aGlobal, uint64_t aId, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { + const UniFFIPointerType* type; + switch (aId) { -static StaticRefPtr gCallbackInterfaceJsHandlerContextIdCallback; - -class CallbackInterfaceMethodContextIdCallbackPersist : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - FfiValueRustBuffer context_id{}; - FfiValueInt creation_date{}; - -public: - CallbackInterfaceMethodContextIdCallbackPersist(size_t aObjectHandle, RustBuffer context_id, int64_t creation_date) - : UniffiCallbackMethodHandlerBase("context_id:ContextIdCallback", aObjectHandle), context_id(FfiValueRustBuffer::FromRust(context_id)), creation_date(FfiValueInt::FromRust(creation_date)) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - // Setup - if (!uniffiArgs.AppendElements(2, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; + case 1: { + type = &kContextIdContextIdComponentPointerType; + break; } - - // Convert each argument - context_id.Lift( - aCx, - &uniffiArgs[0], - aError); - if (aError.Failed()) { - return; + case 2: { + type = &kRelevancyRelevancyStorePointerType; + break; } - creation_date.Lift( - aCx, - &uniffiArgs[1], - aError); - if (aError.Failed()) { - return; + case 3: { + type = &kRemoteSettingsRemoteSettingsPointerType; + break; } - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 0, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_context_id_callback_persist( - uint64_t uniffiHandle, - RustBuffer context_id, int64_t creation_date, - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle, context_id, creation_date); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerContextIdCallback); -} - -class CallbackInterfaceMethodContextIdCallbackRotated : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - FfiValueRustBuffer old_context_id{}; - -public: - CallbackInterfaceMethodContextIdCallbackRotated(size_t aObjectHandle, RustBuffer old_context_id) - : UniffiCallbackMethodHandlerBase("context_id:ContextIdCallback", aObjectHandle), old_context_id(FfiValueRustBuffer::FromRust(old_context_id)) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - // Setup - if (!uniffiArgs.AppendElements(1, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; + case 4: { + type = &kRemoteSettingsRemoteSettingsClientPointerType; + break; } - - // Convert each argument - old_context_id.Lift( - aCx, - &uniffiArgs[0], - aError); - if (aError.Failed()) { - return; + case 5: { + type = &kRemoteSettingsRemoteSettingsServicePointerType; + break; } - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 1, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_context_id_callback_rotated( - uint64_t uniffiHandle, - RustBuffer old_context_id, - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle, old_context_id); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerContextIdCallback); -} - -extern "C" void callbackInterfaceFreeContextIdCallback(uint64_t uniffiHandle) { - // Callback object handles are keys in a map stored in the JS handler. To - // handle the free call, make a call into JS which will remove the key. - // Fire-and-forget is perfect for this. - UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("context_id:ContextIdCallback", uniffiHandle), &gCallbackInterfaceJsHandlerContextIdCallback); -} - - -static VTableCallbackInterfaceContextIdCallback kCallbackInterfaceVtableContextIdCallback { - callback_interface_context_id_callback_persist, - callback_interface_context_id_callback_rotated, - callbackInterfaceFreeContextIdCallback -}; -static StaticRefPtr gCallbackInterfaceJsHandlerApplicationErrorReporter; - -class CallbackInterfaceMethodApplicationErrorReporterReportError : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - FfiValueRustBuffer type_name{}; - FfiValueRustBuffer message{}; - -public: - CallbackInterfaceMethodApplicationErrorReporterReportError(size_t aObjectHandle, RustBuffer type_name, RustBuffer message) - : UniffiCallbackMethodHandlerBase("errorsupport:ApplicationErrorReporter", aObjectHandle), type_name(FfiValueRustBuffer::FromRust(type_name)), message(FfiValueRustBuffer::FromRust(message)) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - // Setup - if (!uniffiArgs.AppendElements(2, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; + case 6: { + type = &kSearchSearchEngineSelectorPointerType; + break; } - - // Convert each argument - type_name.Lift( - aCx, - &uniffiArgs[0], - aError); - if (aError.Failed()) { - return; + case 7: { + type = &kSuggestSuggestStorePointerType; + break; } - message.Lift( - aCx, - &uniffiArgs[1], - aError); - if (aError.Failed()) { - return; + case 8: { + type = &kSuggestSuggestStoreBuilderPointerType; + break; } - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 0, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_application_error_reporter_report_error( - uint64_t uniffiHandle, - RustBuffer type_name, RustBuffer message, - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle, type_name, message); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerApplicationErrorReporter); -} - -class CallbackInterfaceMethodApplicationErrorReporterReportBreadcrumb : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - FfiValueRustBuffer message{}; - FfiValueRustBuffer module{}; - FfiValueInt line{}; - FfiValueInt column{}; - -public: - CallbackInterfaceMethodApplicationErrorReporterReportBreadcrumb(size_t aObjectHandle, RustBuffer message, RustBuffer module, uint32_t line, uint32_t column) - : UniffiCallbackMethodHandlerBase("errorsupport:ApplicationErrorReporter", aObjectHandle), message(FfiValueRustBuffer::FromRust(message)), module(FfiValueRustBuffer::FromRust(module)), line(FfiValueInt::FromRust(line)), column(FfiValueInt::FromRust(column)) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - // Setup - if (!uniffiArgs.AppendElements(4, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; + case 9: { + type = &kTabsRemoteCommandStorePointerType; + break; } - - // Convert each argument - message.Lift( - aCx, - &uniffiArgs[0], - aError); - if (aError.Failed()) { - return; + case 10: { + type = &kTabsTabsBridgedEnginePointerType; + break; } - module.Lift( - aCx, - &uniffiArgs[1], - aError); - if (aError.Failed()) { - return; + case 11: { + type = &kTabsTabsStorePointerType; + break; } - line.Lift( - aCx, - &uniffiArgs[2], - aError); - if (aError.Failed()) { - return; + case 12: { + type = &kWebextstorageWebExtStorageBridgedEnginePointerType; + break; } - column.Lift( - aCx, - &uniffiArgs[3], - aError); - if (aError.Failed()) { - return; + case 13: { + type = &kWebextstorageWebExtStorageStorePointerType; + break; } - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 1, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_application_error_reporter_report_breadcrumb( - uint64_t uniffiHandle, - RustBuffer message, RustBuffer module, uint32_t line, uint32_t column, - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle, message, module, line, column); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerApplicationErrorReporter); -} - -extern "C" void callbackInterfaceFreeApplicationErrorReporter(uint64_t uniffiHandle) { - // Callback object handles are keys in a map stored in the JS handler. To - // handle the free call, make a call into JS which will remove the key. - // Fire-and-forget is perfect for this. - UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("errorsupport:ApplicationErrorReporter", uniffiHandle), &gCallbackInterfaceJsHandlerApplicationErrorReporter); -} - - -static VTableCallbackInterfaceApplicationErrorReporter kCallbackInterfaceVtableApplicationErrorReporter { - callback_interface_application_error_reporter_report_error, - callback_interface_application_error_reporter_report_breadcrumb, - callbackInterfaceFreeApplicationErrorReporter -}; - #ifdef MOZ_UNIFFI_FIXTURES -static StaticRefPtr gCallbackInterfaceJsHandlerLogger; - -class CallbackInterfaceMethodLoggerLog : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - FfiValueRustBuffer message{}; - -public: - CallbackInterfaceMethodLoggerLog(size_t aObjectHandle, RustBuffer message) - : UniffiCallbackMethodHandlerBase("fixture_callbacks:Logger", aObjectHandle), message(FfiValueRustBuffer::FromRust(message)) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - // Setup - if (!uniffiArgs.AppendElements(1, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; + case 14: { + type = &kUniffiBindingsTestsTestInterfacePointerType; + break; } - - // Convert each argument - message.Lift( - aCx, - &uniffiArgs[0], - aError); - if (aError.Failed()) { - return; + case 15: { + type = &kUniffiBindingsTestsAsyncInterfacePointerType; + break; } - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 0, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_logger_log( - uint64_t uniffiHandle, - RustBuffer message, - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle, message); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerLogger); -} - -class CallbackInterfaceMethodLoggerLogRepeat : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - FfiValueRustBuffer message{}; - FfiValueInt count{}; - FfiValueRustBuffer exclude{}; - -public: - CallbackInterfaceMethodLoggerLogRepeat(size_t aObjectHandle, RustBuffer message, uint32_t count, RustBuffer exclude) - : UniffiCallbackMethodHandlerBase("fixture_callbacks:Logger", aObjectHandle), message(FfiValueRustBuffer::FromRust(message)), count(FfiValueInt::FromRust(count)), exclude(FfiValueRustBuffer::FromRust(exclude)) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - // Setup - if (!uniffiArgs.AppendElements(3, mozilla::fallible)) { - aError.Throw(NS_ERROR_OUT_OF_MEMORY); - return; + case 16: { + type = &kUniffiBindingsTestsComplexMethodsPointerType; + break; } - - // Convert each argument - message.Lift( - aCx, - &uniffiArgs[0], - aError); - if (aError.Failed()) { - return; - } - count.Lift( - aCx, - &uniffiArgs[1], - aError); - if (aError.Failed()) { - return; - } - exclude.Lift( - aCx, - &uniffiArgs[2], - aError); - if (aError.Failed()) { - return; - } - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 1, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_logger_log_repeat( - uint64_t uniffiHandle, - RustBuffer message, uint32_t count, RustBuffer exclude, - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle, message, count, exclude); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerLogger); -} - -class CallbackInterfaceMethodLoggerFinished : public UniffiCallbackMethodHandlerBase { -private: - // Rust arguments - -public: - CallbackInterfaceMethodLoggerFinished(size_t aObjectHandle) - : UniffiCallbackMethodHandlerBase("fixture_callbacks:Logger", aObjectHandle) { - } - - MOZ_CAN_RUN_SCRIPT - void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { - nsTArray uniffiArgs; - - // Stores the return value. For now, we currently don't do anything with it, since we only support - // fire-and-forget callbacks. - NullableRootedUnion returnValue(aCx); - // Make the call - aJsHandler->Call(mObjectHandle, 2, uniffiArgs, returnValue, aError); - } -}; - -extern "C" void callback_interface_logger_finished( - uint64_t uniffiHandle, - - void* uniffiOutReturn, - RustCallStatus* uniffiCallStatus -) { - UniquePtr handler = MakeUnique(uniffiHandle); - // Note: currently we only support queueing fire-and-forget async callbacks - - // For fire-and-forget callbacks, we don't know if the method succeeds or not - // since it's called later. uniffiCallStatus is initialized to a successful - // state by the Rust code, so there's no need to modify it. - UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gCallbackInterfaceJsHandlerLogger); -} - -extern "C" void callbackInterfaceFreeLogger(uint64_t uniffiHandle) { - // Callback object handles are keys in a map stored in the JS handler. To - // handle the free call, make a call into JS which will remove the key. - // Fire-and-forget is perfect for this. - UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("fixture_callbacks:Logger", uniffiHandle), &gCallbackInterfaceJsHandlerLogger); -} - - -static VTableCallbackInterfaceLogger kCallbackInterfaceVtableLogger { - callback_interface_logger_log, - callback_interface_logger_log_repeat, - callback_interface_logger_finished, - callbackInterfaceFreeLogger -}; #endif /* MOZ_UNIFFI_FIXTURES */ - -void RegisterCallbackHandler(uint64_t aInterfaceId, UniFFICallbackHandler& aCallbackHandler, ErrorResult& aError) { - switch (aInterfaceId) { - - case 0: { - if (gCallbackInterfaceJsHandlerContextIdCallback) { - aError.ThrowUnknownError("[UniFFI] Callback handler already registered for context_id:ContextIdCallback"_ns); - return; - } - - gCallbackInterfaceJsHandlerContextIdCallback = &aCallbackHandler; - uniffi_context_id_fn_init_callback_vtable_contextidcallback(&kCallbackInterfaceVtableContextIdCallback); - break; - } - case 1: { - if (gCallbackInterfaceJsHandlerApplicationErrorReporter) { - aError.ThrowUnknownError("[UniFFI] Callback handler already registered for errorsupport:ApplicationErrorReporter"_ns); - return; - } - - gCallbackInterfaceJsHandlerApplicationErrorReporter = &aCallbackHandler; - uniffi_error_support_fn_init_callback_vtable_applicationerrorreporter(&kCallbackInterfaceVtableApplicationErrorReporter); - break; - } - - #ifdef MOZ_UNIFFI_FIXTURES - case 2: { - if (gCallbackInterfaceJsHandlerLogger) { - aError.ThrowUnknownError("[UniFFI] Callback handler already registered for fixture_callbacks:Logger"_ns); - return; - } - - gCallbackInterfaceJsHandlerLogger = &aCallbackHandler; - uniffi_uniffi_fixture_callbacks_fn_init_callback_vtable_logger(&kCallbackInterfaceVtableLogger); - break; - } - #endif /* MOZ_UNIFFI_FIXTURES */ - default: - aError.ThrowUnknownError(nsPrintfCString("Unknown interface id: %" PRIu64, aInterfaceId)); - return; + return Nothing(); } + return Some(UniFFIPointer::Read(aArrayBuff, aPosition, type, aError)); } -void DeregisterCallbackHandler(uint64_t aInterfaceId, ErrorResult& aError) { - switch (aInterfaceId) { - - case 0: { - if (!gCallbackInterfaceJsHandlerContextIdCallback) { - aError.ThrowUnknownError("[UniFFI] Callback handler not registered for context_id:ContextIdCallback"_ns); - return; - } +bool WritePointer(const GlobalObject& aGlobal, uint64_t aId, const UniFFIPointer& aPtr, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { + const UniFFIPointerType* type; + switch (aId) { - gCallbackInterfaceJsHandlerContextIdCallback = nullptr; - break; - } case 1: { - if (!gCallbackInterfaceJsHandlerApplicationErrorReporter) { - aError.ThrowUnknownError("[UniFFI] Callback handler not registered for errorsupport:ApplicationErrorReporter"_ns); - return; - } - - gCallbackInterfaceJsHandlerApplicationErrorReporter = nullptr; + type = &kContextIdContextIdComponentPointerType; break; } - - #ifdef MOZ_UNIFFI_FIXTURES case 2: { - if (!gCallbackInterfaceJsHandlerLogger) { - aError.ThrowUnknownError("[UniFFI] Callback handler not registered for fixture_callbacks:Logger"_ns); - return; - } - - gCallbackInterfaceJsHandlerLogger = nullptr; + type = &kRelevancyRelevancyStorePointerType; + break; + } + case 3: { + type = &kRemoteSettingsRemoteSettingsPointerType; + break; + } + case 4: { + type = &kRemoteSettingsRemoteSettingsClientPointerType; + break; + } + case 5: { + type = &kRemoteSettingsRemoteSettingsServicePointerType; + break; + } + case 6: { + type = &kSearchSearchEngineSelectorPointerType; + break; + } + case 7: { + type = &kSuggestSuggestStorePointerType; + break; + } + case 8: { + type = &kSuggestSuggestStoreBuilderPointerType; + break; + } + case 9: { + type = &kTabsRemoteCommandStorePointerType; + break; + } + case 10: { + type = &kTabsTabsBridgedEnginePointerType; + break; + } + case 11: { + type = &kTabsTabsStorePointerType; + break; + } + case 12: { + type = &kWebextstorageWebExtStorageBridgedEnginePointerType; + break; + } + case 13: { + type = &kWebextstorageWebExtStorageStorePointerType; break; } - #endif /* MOZ_UNIFFI_FIXTURES */ +#ifdef MOZ_UNIFFI_FIXTURES + case 14: { + type = &kUniffiBindingsTestsTestInterfacePointerType; + break; + } + case 15: { + type = &kUniffiBindingsTestsAsyncInterfacePointerType; + break; + } + case 16: { + type = &kUniffiBindingsTestsComplexMethodsPointerType; + break; + } +#endif /* MOZ_UNIFFI_FIXTURES */ default: - aError.ThrowUnknownError(nsPrintfCString("Unknown interface id: %" PRIu64, aInterfaceId)); - return; + return false; } + aPtr.Write(aArrayBuff, aPosition, type, aError); + return true; } - +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ // Define scaffolding call classes for each combination of return/argument types -class ScaffoldingCallHandlerUniffiContextIdFnMethodContextidcomponentForceRotation : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleContextIdContextIdComponent mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_context_id_fn_method_contextidcomponent_force_rotation( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiContextIdFnMethodContextidcomponentRequest : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleContextIdContextIdComponent mPtr{}; - FfiValueInt mRotationDaysInS{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mRotationDaysInS.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_context_id_fn_method_contextidcomponent_request( - mPtr.IntoRust(), - mRotationDaysInS.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiContextIdFnMethodContextidcomponentUnsetCallback : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleContextIdContextIdComponent mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_context_id_fn_method_contextidcomponent_unset_callback( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; class ScaffoldingCallHandlerUniffiContextIdFnConstructorContextidcomponentNew : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields @@ -4264,6 +2455,95 @@ public: ); } }; +class ScaffoldingCallHandlerUniffiContextIdFnMethodContextidcomponentForceRotation : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleContextIdContextIdComponent mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_context_id_fn_method_contextidcomponent_force_rotation( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiContextIdFnMethodContextidcomponentRequest : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleContextIdContextIdComponent mUniffiPtr{}; + FfiValueInt mRotationDaysInS{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mRotationDaysInS.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_context_id_fn_method_contextidcomponent_request( + mUniffiPtr.IntoRust(), + mRotationDaysInS.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiContextIdFnMethodContextidcomponentUnsetCallback : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleContextIdContextIdComponent mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_context_id_fn_method_contextidcomponent_unset_callback( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; class ScaffoldingCallHandlerUniffiErrorSupportFnFuncSetApplicationErrorReporter : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields @@ -4347,323 +2627,6 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreBanditInit : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - FfiValueRustBuffer mBandit{}; - FfiValueRustBuffer mArms{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mBandit.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mArms.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_relevancy_fn_method_relevancystore_bandit_init( - mPtr.IntoRust(), - mBandit.IntoRust(), - mArms.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreBanditSelect : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - FfiValueRustBuffer mBandit{}; - FfiValueRustBuffer mArms{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mBandit.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mArms.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_relevancy_fn_method_relevancystore_bandit_select( - mPtr.IntoRust(), - mBandit.IntoRust(), - mArms.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreBanditUpdate : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - FfiValueRustBuffer mBandit{}; - FfiValueRustBuffer mArm{}; - FfiValueInt mSelected{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mBandit.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mArm.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - mSelected.Lower(aArgs[3], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_relevancy_fn_method_relevancystore_bandit_update( - mPtr.IntoRust(), - mBandit.IntoRust(), - mArm.IntoRust(), - mSelected.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreClose : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_relevancy_fn_method_relevancystore_close( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreEnsureInterestDataPopulated : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_relevancy_fn_method_relevancystore_ensure_interest_data_populated( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreGetBanditData : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - FfiValueRustBuffer mBandit{}; - FfiValueRustBuffer mArm{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mBandit.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mArm.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_relevancy_fn_method_relevancystore_get_bandit_data( - mPtr.IntoRust(), - mBandit.IntoRust(), - mArm.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreIngest : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - FfiValueRustBuffer mTopUrlsByFrecency{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mTopUrlsByFrecency.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_relevancy_fn_method_relevancystore_ingest( - mPtr.IntoRust(), - mTopUrlsByFrecency.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreInterrupt : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_relevancy_fn_method_relevancystore_interrupt( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreUserInterestVector : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRelevancyRelevancyStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_relevancy_fn_method_relevancystore_user_interest_vector( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; class ScaffoldingCallHandlerUniffiRelevancyFnConstructorRelevancystoreNew : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields @@ -4703,36 +2666,36 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsDownloadAttachmentToPath : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreBanditInit : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettings mPtr{}; - FfiValueRustBuffer mAttachmentId{}; - FfiValueRustBuffer mPath{}; + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + FfiValueRustBuffer mBandit{}; + FfiValueRustBuffer mArms{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mAttachmentId.Lower(aArgs[1], aError); + mBandit.Lower(aArgs[1], aError); if (aError.Failed()) { return; } - mPath.Lower(aArgs[2], aError); + mArms.Lower(aArgs[2], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_remote_settings_fn_method_remotesettings_download_attachment_to_path( - mPtr.IntoRust(), - mAttachmentId.IntoRust(), - mPath.IntoRust(), + uniffi_relevancy_fn_method_relevancystore_bandit_init( + mUniffiPtr.IntoRust(), + mBandit.IntoRust(), + mArms.IntoRust(), aOutStatus ); } @@ -4740,17 +2703,27 @@ public: virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { } }; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsGetRecords : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreBanditSelect : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettings mPtr{}; + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + FfiValueRustBuffer mBandit{}; + FfiValueRustBuffer mArms{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mBandit.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mArms.Lower(aArgs[2], aError); if (aError.Failed()) { return; } @@ -4758,8 +2731,10 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_remote_settings_fn_method_remotesettings_get_records( - mPtr.IntoRust(), + uniffi_relevancy_fn_method_relevancystore_bandit_select( + mUniffiPtr.IntoRust(), + mBandit.IntoRust(), + mArms.IntoRust(), aOutStatus ) ); @@ -4773,22 +2748,120 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsGetRecordsSince : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreBanditUpdate : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettings mPtr{}; - FfiValueInt mTimestamp{}; + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + FfiValueRustBuffer mBandit{}; + FfiValueRustBuffer mArm{}; + FfiValueInt mSelected{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mBandit.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mArm.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + mSelected.Lower(aArgs[3], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_relevancy_fn_method_relevancystore_bandit_update( + mUniffiPtr.IntoRust(), + mBandit.IntoRust(), + mArm.IntoRust(), + mSelected.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreClose : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_relevancy_fn_method_relevancystore_close( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreEnsureInterestDataPopulated : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_relevancy_fn_method_relevancystore_ensure_interest_data_populated( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreGetBanditData : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + FfiValueRustBuffer mBandit{}; + FfiValueRustBuffer mArm{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mTimestamp.Lower(aArgs[1], aError); + mBandit.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mArm.Lower(aArgs[2], aError); if (aError.Failed()) { return; } @@ -4796,9 +2869,107 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_remote_settings_fn_method_remotesettings_get_records_since( - mPtr.IntoRust(), - mTimestamp.IntoRust(), + uniffi_relevancy_fn_method_relevancystore_get_bandit_data( + mUniffiPtr.IntoRust(), + mBandit.IntoRust(), + mArm.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreIngest : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + FfiValueRustBuffer mTopUrlsByFrecency{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mTopUrlsByFrecency.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_relevancy_fn_method_relevancystore_ingest( + mUniffiPtr.IntoRust(), + mTopUrlsByFrecency.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreInterrupt : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_relevancy_fn_method_relevancystore_interrupt( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiRelevancyFnMethodRelevancystoreUserInterestVector : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRelevancyRelevancyStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_relevancy_fn_method_relevancystore_user_interest_vector( + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -4845,17 +3016,126 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientCollectionName : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsDownloadAttachmentToPath : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettings mUniffiPtr{}; + FfiValueRustBuffer mAttachmentId{}; + FfiValueRustBuffer mPath{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mAttachmentId.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mPath.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_remote_settings_fn_method_remotesettings_download_attachment_to_path( + mUniffiPtr.IntoRust(), + mAttachmentId.IntoRust(), + mPath.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsGetRecords : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRemoteSettingsRemoteSettings mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_remote_settings_fn_method_remotesettings_get_records( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsGetRecordsSince : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRemoteSettingsRemoteSettings mUniffiPtr{}; + FfiValueInt mTimestamp{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mTimestamp.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_remote_settings_fn_method_remotesettings_get_records_since( + mUniffiPtr.IntoRust(), + mTimestamp.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientCollectionName : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -4864,7 +3144,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_remote_settings_fn_method_remotesettingsclient_collection_name( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -4881,7 +3161,7 @@ public: class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientGetAttachment : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiPtr{}; FfiValueRustBuffer mRecord{}; // MakeRustCall stores the result of the call in these fields @@ -4889,7 +3169,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -4902,7 +3182,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_remote_settings_fn_method_remotesettingsclient_get_attachment( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mRecord.IntoRust(), aOutStatus ) @@ -4920,7 +3200,7 @@ public: class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientGetRecords : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiPtr{}; FfiValueInt mSyncIfEmpty{}; // MakeRustCall stores the result of the call in these fields @@ -4928,7 +3208,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -4941,7 +3221,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_remote_settings_fn_method_remotesettingsclient_get_records( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mSyncIfEmpty.IntoRust(), aOutStatus ) @@ -4959,7 +3239,7 @@ public: class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientGetRecordsMap : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiPtr{}; FfiValueInt mSyncIfEmpty{}; // MakeRustCall stores the result of the call in these fields @@ -4967,7 +3247,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -4980,7 +3260,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_remote_settings_fn_method_remotesettingsclient_get_records_map( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mSyncIfEmpty.IntoRust(), aOutStatus ) @@ -4998,13 +3278,13 @@ public: class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientShutdown : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -5012,7 +3292,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_remote_settings_fn_method_remotesettingsclient_shutdown( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -5023,13 +3303,13 @@ public: class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsclientSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -5037,110 +3317,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_remote_settings_fn_method_remotesettingsclient_sync( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsserviceMakeClient : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsService mPtr{}; - FfiValueRustBuffer mCollectionName{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mCollectionName.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleRemoteSettingsRemoteSettingsClient::FromRust( - uniffi_remote_settings_fn_method_remotesettingsservice_make_client( - mPtr.IntoRust(), - mCollectionName.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsserviceSync : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsService mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_remote_settings_fn_method_remotesettingsservice_sync( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsserviceUpdateConfig : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRemoteSettingsRemoteSettingsService mPtr{}; - FfiValueRustBuffer mConfig{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mConfig.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_remote_settings_fn_method_remotesettingsservice_update_config( - mPtr.IntoRust(), - mConfig.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -5187,57 +3364,32 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorClearSearchConfig : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsserviceMakeClient : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSearchSearchEngineSelector mPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsService mUniffiPtr{}; + FfiValueRustBuffer mCollectionName{}; // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleRemoteSettingsRemoteSettingsClient mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mCollectionName.Lower(aArgs[1], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_search_fn_method_searchengineselector_clear_search_config( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorFilterEngineConfiguration : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSearchSearchEngineSelector mPtr{}; - FfiValueRustBuffer mUserEnvironment{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mUserEnvironment.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_search_fn_method_searchengineselector_filter_engine_configuration( - mPtr.IntoRust(), - mUserEnvironment.IntoRust(), + mUniffiReturnValue = FfiValueObjectHandleRemoteSettingsRemoteSettingsClient::FromRust( + uniffi_remote_settings_fn_method_remotesettingsservice_make_client( + mUniffiPtr.IntoRust(), + mCollectionName.IntoRust(), aOutStatus ) ); @@ -5251,98 +3403,63 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorSetConfigOverrides : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsserviceSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSearchSearchEngineSelector mPtr{}; - FfiValueRustBuffer mOverrides{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsService mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mOverrides.Lower(aArgs[1], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_search_fn_method_searchengineselector_set_config_overrides( - mPtr.IntoRust(), - mOverrides.IntoRust(), - aOutStatus + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_remote_settings_fn_method_remotesettingsservice_sync( + mUniffiPtr.IntoRust(), + aOutStatus + ) ); } virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorSetSearchConfig : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSearchSearchEngineSelector mPtr{}; - FfiValueRustBuffer mConfiguration{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mConfiguration.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_search_fn_method_searchengineselector_set_search_config( - mPtr.IntoRust(), - mConfiguration.IntoRust(), - aOutStatus + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError ); } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } }; -class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorUseRemoteSettingsServer : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiRemoteSettingsFnMethodRemotesettingsserviceUpdateConfig : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSearchSearchEngineSelector mPtr{}; - FfiValueObjectHandleRemoteSettingsRemoteSettingsService mService{}; - FfiValueInt mApplyEngineOverrides{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsService mUniffiPtr{}; + FfiValueRustBuffer mConfig{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mService.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mApplyEngineOverrides.Lower(aArgs[2], aError); + mConfig.Lower(aArgs[1], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_search_fn_method_searchengineselector_use_remote_settings_server( - mPtr.IntoRust(), - mService.IntoRust(), - mApplyEngineOverrides.IntoRust(), + uniffi_remote_settings_fn_method_remotesettingsservice_update_config( + mUniffiPtr.IntoRust(), + mConfig.IntoRust(), aOutStatus ); } @@ -5377,6 +3494,169 @@ public: ); } }; +class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorClearSearchConfig : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSearchSearchEngineSelector mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_search_fn_method_searchengineselector_clear_search_config( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorFilterEngineConfiguration : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSearchSearchEngineSelector mUniffiPtr{}; + FfiValueRustBuffer mUserEnvironment{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mUserEnvironment.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_search_fn_method_searchengineselector_filter_engine_configuration( + mUniffiPtr.IntoRust(), + mUserEnvironment.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorSetConfigOverrides : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSearchSearchEngineSelector mUniffiPtr{}; + FfiValueRustBuffer mOverrides{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mOverrides.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_search_fn_method_searchengineselector_set_config_overrides( + mUniffiPtr.IntoRust(), + mOverrides.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorSetSearchConfig : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSearchSearchEngineSelector mUniffiPtr{}; + FfiValueRustBuffer mConfiguration{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mConfiguration.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_search_fn_method_searchengineselector_set_search_config( + mUniffiPtr.IntoRust(), + mConfiguration.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSearchFnMethodSearchengineselectorUseRemoteSettingsServer : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSearchSearchEngineSelector mUniffiPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsService mService{}; + FfiValueInt mApplyEngineOverrides{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mService.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mApplyEngineOverrides.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_search_fn_method_searchengineselector_use_remote_settings_server( + mUniffiPtr.IntoRust(), + mService.IntoRust(), + mApplyEngineOverrides.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; class ScaffoldingCallHandlerUniffiSuggestFnFuncRawSuggestionUrlMatches : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields @@ -5416,537 +3696,6 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreAnyDismissedSuggestions : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_suggest_fn_method_suggeststore_any_dismissed_suggestions( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreClear : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_suggest_fn_method_suggeststore_clear( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreClearDismissedSuggestions : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_suggest_fn_method_suggeststore_clear_dismissed_suggestions( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreDismissByKey : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mKey{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mKey.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_suggest_fn_method_suggeststore_dismiss_by_key( - mPtr.IntoRust(), - mKey.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreDismissBySuggestion : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mSuggestion{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mSuggestion.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_suggest_fn_method_suggeststore_dismiss_by_suggestion( - mPtr.IntoRust(), - mSuggestion.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreDismissSuggestion : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mSuggestionUrl{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mSuggestionUrl.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_suggest_fn_method_suggeststore_dismiss_suggestion( - mPtr.IntoRust(), - mSuggestionUrl.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreFetchGeonames : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mQuery{}; - FfiValueInt mMatchNamePrefix{}; - FfiValueRustBuffer mGeonameType{}; - FfiValueRustBuffer mFilter{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mQuery.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mMatchNamePrefix.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - mGeonameType.Lower(aArgs[3], aError); - if (aError.Failed()) { - return; - } - mFilter.Lower(aArgs[4], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_suggest_fn_method_suggeststore_fetch_geonames( - mPtr.IntoRust(), - mQuery.IntoRust(), - mMatchNamePrefix.IntoRust(), - mGeonameType.IntoRust(), - mFilter.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreFetchGlobalConfig : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_suggest_fn_method_suggeststore_fetch_global_config( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreFetchProviderConfig : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mProvider{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mProvider.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_suggest_fn_method_suggeststore_fetch_provider_config( - mPtr.IntoRust(), - mProvider.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreIngest : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mConstraints{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mConstraints.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_suggest_fn_method_suggeststore_ingest( - mPtr.IntoRust(), - mConstraints.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreInterrupt : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mKind{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mKind.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_suggest_fn_method_suggeststore_interrupt( - mPtr.IntoRust(), - mKind.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreIsDismissedByKey : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mKey{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mKey.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_suggest_fn_method_suggeststore_is_dismissed_by_key( - mPtr.IntoRust(), - mKey.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreIsDismissedBySuggestion : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mSuggestion{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mSuggestion.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_suggest_fn_method_suggeststore_is_dismissed_by_suggestion( - mPtr.IntoRust(), - mSuggestion.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreQuery : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mQuery{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mQuery.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_suggest_fn_method_suggeststore_query( - mPtr.IntoRust(), - mQuery.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreQueryWithMetrics : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStore mPtr{}; - FfiValueRustBuffer mQuery{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mQuery.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_suggest_fn_method_suggeststore_query_with_metrics( - mPtr.IntoRust(), - mQuery.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; class ScaffoldingCallHandlerUniffiSuggestFnConstructorSuggeststoreNew : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields @@ -5986,26 +3735,26 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderBuild : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreAnyDismissedSuggestions : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStore mUniffiReturnValue{}; + FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStore::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_build( - mPtr.IntoRust(), + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_suggest_fn_method_suggeststore_any_dismissed_suggestions( + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6019,32 +3768,193 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderCachePath : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreClear : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; - FfiValueRustBuffer mPath{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mPath.Lower(aArgs[1], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_cache_path( - mPtr.IntoRust(), - mPath.IntoRust(), + uniffi_suggest_fn_method_suggeststore_clear( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreClearDismissedSuggestions : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_suggest_fn_method_suggeststore_clear_dismissed_suggestions( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreDismissByKey : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mKey{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mKey.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_suggest_fn_method_suggeststore_dismiss_by_key( + mUniffiPtr.IntoRust(), + mKey.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreDismissBySuggestion : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mSuggestion{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mSuggestion.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_suggest_fn_method_suggeststore_dismiss_by_suggestion( + mUniffiPtr.IntoRust(), + mSuggestion.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreDismissSuggestion : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mSuggestionUrl{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mSuggestionUrl.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_suggest_fn_method_suggeststore_dismiss_suggestion( + mUniffiPtr.IntoRust(), + mSuggestionUrl.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreFetchGeonames : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mQuery{}; + FfiValueInt mMatchNamePrefix{}; + FfiValueRustBuffer mGeonameType{}; + FfiValueRustBuffer mFilter{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mQuery.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mMatchNamePrefix.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + mGeonameType.Lower(aArgs[3], aError); + if (aError.Failed()) { + return; + } + mFilter.Lower(aArgs[4], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_suggest_fn_method_suggeststore_fetch_geonames( + mUniffiPtr.IntoRust(), + mQuery.IntoRust(), + mMatchNamePrefix.IntoRust(), + mGeonameType.IntoRust(), + mFilter.IntoRust(), aOutStatus ) ); @@ -6058,32 +3968,26 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderDataPath : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreFetchGlobalConfig : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; - FfiValueRustBuffer mPath{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mPath.Lower(aArgs[1], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_data_path( - mPtr.IntoRust(), - mPath.IntoRust(), + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_suggest_fn_method_suggeststore_fetch_global_config( + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6097,38 +4001,32 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderLoadExtension : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreFetchProviderConfig : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; - FfiValueRustBuffer mLibrary{}; - FfiValueRustBuffer mEntryPoint{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mProvider{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mLibrary.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mEntryPoint.Lower(aArgs[2], aError); + mProvider.Lower(aArgs[1], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_load_extension( - mPtr.IntoRust(), - mLibrary.IntoRust(), - mEntryPoint.IntoRust(), + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_suggest_fn_method_suggeststore_fetch_provider_config( + mUniffiPtr.IntoRust(), + mProvider.IntoRust(), aOutStatus ) ); @@ -6142,32 +4040,32 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderRemoteSettingsBucketName : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreIngest : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; - FfiValueRustBuffer mBucketName{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mConstraints{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mBucketName.Lower(aArgs[1], aError); + mConstraints.Lower(aArgs[1], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_bucket_name( - mPtr.IntoRust(), - mBucketName.IntoRust(), + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_suggest_fn_method_suggeststore_ingest( + mUniffiPtr.IntoRust(), + mConstraints.IntoRust(), aOutStatus ) ); @@ -6181,32 +4079,63 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderRemoteSettingsServer : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreInterrupt : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; - FfiValueRustBuffer mServer{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mKind{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mServer.Lower(aArgs[1], aError); + mKind.Lower(aArgs[1], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_server( - mPtr.IntoRust(), - mServer.IntoRust(), + uniffi_suggest_fn_method_suggeststore_interrupt( + mUniffiPtr.IntoRust(), + mKind.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreIsDismissedByKey : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mKey{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mKey.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_suggest_fn_method_suggeststore_is_dismissed_by_key( + mUniffiPtr.IntoRust(), + mKey.IntoRust(), aOutStatus ) ); @@ -6220,32 +4149,110 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderRemoteSettingsService : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreIsDismissedBySuggestion : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mPtr{}; - FfiValueObjectHandleRemoteSettingsRemoteSettingsService mRsService{}; + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mSuggestion{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mRsService.Lower(aArgs[1], aError); + mSuggestion.Lower(aArgs[1], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( - uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_service( - mPtr.IntoRust(), - mRsService.IntoRust(), + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_suggest_fn_method_suggeststore_is_dismissed_by_suggestion( + mUniffiPtr.IntoRust(), + mSuggestion.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreQuery : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mQuery{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mQuery.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_suggest_fn_method_suggeststore_query( + mUniffiPtr.IntoRust(), + mQuery.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststoreQueryWithMetrics : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiPtr{}; + FfiValueRustBuffer mQuery{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mQuery.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_suggest_fn_method_suggeststore_query_with_metrics( + mUniffiPtr.IntoRust(), + mQuery.IntoRust(), aOutStatus ) ); @@ -6286,10 +4293,283 @@ public: ); } }; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderBuild : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStore mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStore::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_build( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderCachePath : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + FfiValueRustBuffer mPath{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mPath.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_cache_path( + mUniffiPtr.IntoRust(), + mPath.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderDataPath : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + FfiValueRustBuffer mPath{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mPath.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_data_path( + mUniffiPtr.IntoRust(), + mPath.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderLoadExtension : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + FfiValueRustBuffer mLibrary{}; + FfiValueRustBuffer mEntryPoint{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mLibrary.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mEntryPoint.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_load_extension( + mUniffiPtr.IntoRust(), + mLibrary.IntoRust(), + mEntryPoint.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderRemoteSettingsBucketName : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + FfiValueRustBuffer mBucketName{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mBucketName.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_bucket_name( + mUniffiPtr.IntoRust(), + mBucketName.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderRemoteSettingsServer : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + FfiValueRustBuffer mServer{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mServer.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_server( + mUniffiPtr.IntoRust(), + mServer.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiSuggestFnMethodSuggeststorebuilderRemoteSettingsService : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiPtr{}; + FfiValueObjectHandleRemoteSettingsRemoteSettingsService mRsService{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleSuggestSuggestStoreBuilder mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mRsService.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleSuggestSuggestStoreBuilder::FromRust( + uniffi_suggest_fn_method_suggeststorebuilder_remote_settings_service( + mUniffiPtr.IntoRust(), + mRsService.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; class ScaffoldingCallHandlerUniffiTabsFnMethodRemotecommandstoreAddRemoteCommand : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsRemoteCommandStore mPtr{}; + FfiValueObjectHandleTabsRemoteCommandStore mUniffiPtr{}; FfiValueRustBuffer mDeviceId{}; FfiValueRustBuffer mCommand{}; @@ -6298,7 +4578,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6315,7 +4595,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( uniffi_tabs_fn_method_remotecommandstore_add_remote_command( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mDeviceId.IntoRust(), mCommand.IntoRust(), aOutStatus @@ -6334,7 +4614,7 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodRemotecommandstoreAddRemoteCommandAt : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsRemoteCommandStore mPtr{}; + FfiValueObjectHandleTabsRemoteCommandStore mUniffiPtr{}; FfiValueRustBuffer mDeviceId{}; FfiValueRustBuffer mCommand{}; FfiValueInt mWhen{}; @@ -6344,7 +4624,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6365,7 +4645,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( uniffi_tabs_fn_method_remotecommandstore_add_remote_command_at( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mDeviceId.IntoRust(), mCommand.IntoRust(), mWhen.IntoRust(), @@ -6385,14 +4665,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodRemotecommandstoreGetUnsentCommands : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsRemoteCommandStore mPtr{}; + FfiValueObjectHandleTabsRemoteCommandStore mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6401,7 +4681,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_tabs_fn_method_remotecommandstore_get_unsent_commands( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6418,7 +4698,7 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodRemotecommandstoreRemoveRemoteCommand : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsRemoteCommandStore mPtr{}; + FfiValueObjectHandleTabsRemoteCommandStore mUniffiPtr{}; FfiValueRustBuffer mDeviceId{}; FfiValueRustBuffer mCommand{}; @@ -6427,7 +4707,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6444,7 +4724,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( uniffi_tabs_fn_method_remotecommandstore_remove_remote_command( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mDeviceId.IntoRust(), mCommand.IntoRust(), aOutStatus @@ -6463,7 +4743,7 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodRemotecommandstoreSetPendingCommandSent : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsRemoteCommandStore mPtr{}; + FfiValueObjectHandleTabsRemoteCommandStore mUniffiPtr{}; FfiValueRustBuffer mCommand{}; // MakeRustCall stores the result of the call in these fields @@ -6471,7 +4751,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6484,7 +4764,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( uniffi_tabs_fn_method_remotecommandstore_set_pending_command_sent( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mCommand.IntoRust(), aOutStatus ) @@ -6502,14 +4782,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineApply : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6518,7 +4798,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_tabs_fn_method_tabsbridgedengine_apply( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6535,7 +4815,7 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineEnsureCurrentSyncId : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; FfiValueRustBuffer mNewSyncId{}; // MakeRustCall stores the result of the call in these fields @@ -6543,7 +4823,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6556,7 +4836,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_tabs_fn_method_tabsbridgedengine_ensure_current_sync_id( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mNewSyncId.IntoRust(), aOutStatus ) @@ -6574,14 +4854,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineLastSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6590,7 +4870,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( uniffi_tabs_fn_method_tabsbridgedengine_last_sync( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6607,14 +4887,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedenginePrepareForSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; FfiValueRustBuffer mClientData{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6626,7 +4906,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_prepare_for_sync( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mClientData.IntoRust(), aOutStatus ); @@ -6638,13 +4918,13 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineReset : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6652,7 +4932,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_reset( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -6663,14 +4943,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineResetSyncId : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6679,7 +4959,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_tabs_fn_method_tabsbridgedengine_reset_sync_id( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6696,14 +4976,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineSetLastSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; FfiValueInt mLastSync{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6715,7 +4995,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_set_last_sync( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mLastSync.IntoRust(), aOutStatus ); @@ -6727,7 +5007,7 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineSetUploaded : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; FfiValueInt mNewTimestamp{}; FfiValueRustBuffer mUploadedIds{}; @@ -6735,7 +5015,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6751,7 +5031,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_set_uploaded( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mNewTimestamp.IntoRust(), mUploadedIds.IntoRust(), aOutStatus @@ -6764,14 +5044,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineStoreIncoming : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; FfiValueRustBuffer mIncomingEnvelopesAsJson{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6783,7 +5063,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_store_incoming( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mIncomingEnvelopesAsJson.IntoRust(), aOutStatus ); @@ -6795,13 +5075,13 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineSyncFinished : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6809,7 +5089,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_sync_finished( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -6820,14 +5100,14 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineSyncId : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6836,7 +5116,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_tabs_fn_method_tabsbridgedengine_sync_id( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -6853,13 +5133,13 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineSyncStarted : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6867,7 +5147,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_sync_started( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -6878,13 +5158,13 @@ public: class ScaffoldingCallHandlerUniffiTabsFnMethodTabsbridgedengineWipe : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -6892,187 +5172,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_tabs_fn_method_tabsbridgedengine_wipe( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreBridgedEngine : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleTabsTabsBridgedEngine mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleTabsTabsBridgedEngine::FromRust( - uniffi_tabs_fn_method_tabsstore_bridged_engine( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreCloseConnection : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_tabs_fn_method_tabsstore_close_connection( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreGetAll : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_tabs_fn_method_tabsstore_get_all( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreNewRemoteCommandStore : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleTabsRemoteCommandStore mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleTabsRemoteCommandStore::FromRust( - uniffi_tabs_fn_method_tabsstore_new_remote_command_store( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreRegisterWithSyncManager : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_tabs_fn_method_tabsstore_register_with_sync_manager( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreSetLocalTabs : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTabsTabsStore mPtr{}; - FfiValueRustBuffer mRemoteTabs{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mRemoteTabs.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_tabs_fn_method_tabsstore_set_local_tabs( - mPtr.IntoRust(), - mRemoteTabs.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -7113,17 +5213,197 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineApply : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreBridgedEngine : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleTabsTabsStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleTabsTabsBridgedEngine mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleTabsTabsBridgedEngine::FromRust( + uniffi_tabs_fn_method_tabsstore_bridged_engine( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreCloseConnection : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleTabsTabsStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_tabs_fn_method_tabsstore_close_connection( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreGetAll : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleTabsTabsStore mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_tabs_fn_method_tabsstore_get_all( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreNewRemoteCommandStore : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleTabsTabsStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleTabsRemoteCommandStore mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleTabsRemoteCommandStore::FromRust( + uniffi_tabs_fn_method_tabsstore_new_remote_command_store( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreRegisterWithSyncManager : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleTabsTabsStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_tabs_fn_method_tabsstore_register_with_sync_manager( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiTabsFnMethodTabsstoreSetLocalTabs : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleTabsTabsStore mUniffiPtr{}; + FfiValueRustBuffer mRemoteTabs{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mRemoteTabs.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_tabs_fn_method_tabsstore_set_local_tabs( + mUniffiPtr.IntoRust(), + mRemoteTabs.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineApply : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7132,7 +5412,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_webext_storage_fn_method_webextstoragebridgedengine_apply( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -7149,7 +5429,7 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineEnsureCurrentSyncId : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; FfiValueRustBuffer mNewSyncId{}; // MakeRustCall stores the result of the call in these fields @@ -7157,7 +5437,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7170,7 +5450,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_webext_storage_fn_method_webextstoragebridgedengine_ensure_current_sync_id( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mNewSyncId.IntoRust(), aOutStatus ) @@ -7188,14 +5468,14 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineLastSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7204,7 +5484,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( uniffi_webext_storage_fn_method_webextstoragebridgedengine_last_sync( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -7221,14 +5501,14 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedenginePrepareForSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; FfiValueRustBuffer mClientData{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7240,7 +5520,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_prepare_for_sync( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mClientData.IntoRust(), aOutStatus ); @@ -7252,13 +5532,13 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineReset : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7266,7 +5546,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_reset( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -7277,14 +5557,14 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineResetSyncId : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7293,7 +5573,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_webext_storage_fn_method_webextstoragebridgedengine_reset_sync_id( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -7310,14 +5590,14 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineSetLastSync : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; FfiValueInt mLastSync{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7329,7 +5609,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_set_last_sync( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mLastSync.IntoRust(), aOutStatus ); @@ -7341,7 +5621,7 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineSetUploaded : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; FfiValueInt mServerModifiedMillis{}; FfiValueRustBuffer mGuids{}; @@ -7349,7 +5629,7 @@ private: public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7365,7 +5645,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_set_uploaded( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mServerModifiedMillis.IntoRust(), mGuids.IntoRust(), aOutStatus @@ -7378,14 +5658,14 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineStoreIncoming : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; FfiValueRustBuffer mIncoming{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7397,7 +5677,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_store_incoming( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), mIncoming.IntoRust(), aOutStatus ); @@ -7409,13 +5689,13 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineSyncFinished : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7423,7 +5703,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_finished( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -7434,14 +5714,14 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineSyncId : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7450,7 +5730,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_id( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -7467,13 +5747,13 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineSyncStarted : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7481,7 +5761,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_sync_started( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -7492,13 +5772,13 @@ public: class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragebridgedengineWipe : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mPtr{}; + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -7506,7 +5786,7 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { uniffi_webext_storage_fn_method_webextstoragebridgedengine_wipe( - mPtr.IntoRust(), + mUniffiPtr.IntoRust(), aOutStatus ); } @@ -7514,316 +5794,6 @@ public: virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { } }; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreBridgedEngine : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_bridged_engine( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreClear : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - FfiValueRustBuffer mExtId{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mExtId.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_clear( - mPtr.IntoRust(), - mExtId.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreClose : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_webext_storage_fn_method_webextstoragestore_close( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreGet : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - FfiValueRustBuffer mExtId{}; - FfiValueRustBuffer mKeys{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mExtId.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mKeys.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_get( - mPtr.IntoRust(), - mExtId.IntoRust(), - mKeys.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreGetBytesInUse : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - FfiValueRustBuffer mExtId{}; - FfiValueRustBuffer mKeys{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mExtId.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mKeys.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_get_bytes_in_use( - mPtr.IntoRust(), - mExtId.IntoRust(), - mKeys.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreGetSyncedChanges : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_get_synced_changes( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreRemove : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - FfiValueRustBuffer mExtId{}; - FfiValueRustBuffer mKeys{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mExtId.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mKeys.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_remove( - mPtr.IntoRust(), - mExtId.IntoRust(), - mKeys.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreSet : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleWebextstorageWebExtStorageStore mPtr{}; - FfiValueRustBuffer mExtId{}; - FfiValueRustBuffer mVal{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mExtId.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mVal.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_webext_storage_fn_method_webextstoragestore_set( - mPtr.IntoRust(), - mExtId.IntoRust(), - mVal.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; class ScaffoldingCallHandlerUniffiWebextStorageFnConstructorWebextstoragestoreNew : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields @@ -7857,730 +5827,324 @@ public: ); } }; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreBridgedEngine : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleWebextstorageWebExtStorageBridgedEngine::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_bridged_engine( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreClear : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + FfiValueRustBuffer mExtId{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mExtId.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_clear( + mUniffiPtr.IntoRust(), + mExtId.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreClose : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_webext_storage_fn_method_webextstoragestore_close( + mUniffiPtr.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreGet : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + FfiValueRustBuffer mExtId{}; + FfiValueRustBuffer mKeys{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mExtId.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mKeys.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_get( + mUniffiPtr.IntoRust(), + mExtId.IntoRust(), + mKeys.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreGetBytesInUse : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + FfiValueRustBuffer mExtId{}; + FfiValueRustBuffer mKeys{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mExtId.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mKeys.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_get_bytes_in_use( + mUniffiPtr.IntoRust(), + mExtId.IntoRust(), + mKeys.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreGetSyncedChanges : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_get_synced_changes( + mUniffiPtr.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreRemove : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + FfiValueRustBuffer mExtId{}; + FfiValueRustBuffer mKeys{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mExtId.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mKeys.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_remove( + mUniffiPtr.IntoRust(), + mExtId.IntoRust(), + mKeys.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiWebextStorageFnMethodWebextstoragestoreSet : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleWebextstorageWebExtStorageStore mUniffiPtr{}; + FfiValueRustBuffer mExtId{}; + FfiValueRustBuffer mVal{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mExtId.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mVal.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_webext_storage_fn_method_webextstoragestore_set( + mUniffiPtr.IntoRust(), + mExtId.IntoRust(), + mVal.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; #ifdef MOZ_UNIFFI_FIXTURES -class ScaffoldingCallHandlerUniffiArithmeticalFnFuncAdd : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mA{}; - FfiValueInt mB{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripF32 : public UniffiAsyncCallHandler { public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mA.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mB.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_arithmetical_fn_func_add( - mA.IntoRust(), - mB.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiArithmeticalFnFuncDiv : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mDividend{}; - FfiValueInt mDivisor{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mDividend.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mDivisor.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_arithmetical_fn_func_div( - mDividend.IntoRust(), - mDivisor.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiArithmeticalFnFuncEqual : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mA{}; - FfiValueInt mB{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mA.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mB.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_arithmetical_fn_func_equal( - mA.IntoRust(), - mB.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiArithmeticalFnFuncSub : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mA{}; - FfiValueInt mB{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mA.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mB.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_arithmetical_fn_func_sub( - mA.IntoRust(), - mB.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncEchoExplicitValue : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_custom_types_fn_func_echo_explicit_value( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncEchoGappedValue : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_custom_types_fn_func_echo_gapped_value( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncEchoSequentialValue : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_custom_types_fn_func_echo_sequential_value( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncGetCustomTypesDemo : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mDemo{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mDemo.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_custom_types_fn_func_get_custom_types_demo( - mDemo.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncGetExplicitDiscriminant : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_custom_types_fn_func_get_explicit_discriminant( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncGetExplicitEnumValues : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_custom_types_fn_func_get_explicit_enum_values( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncGetGappedDiscriminant : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_custom_types_fn_func_get_gapped_discriminant( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncGetGappedEnumValues : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_custom_types_fn_func_get_gapped_enum_values( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiCustomTypesFnFuncGetSequentialDiscriminant : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_custom_types_fn_func_get_sequential_discriminant( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureExternalTypesFnFuncGradient : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueFloat mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mValue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueFloat::FromRust( - uniffi_uniffi_fixture_external_types_fn_func_gradient( - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureExternalTypesFnFuncIntersection : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mLn1{}; - FfiValueRustBuffer mLn2{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mLn1.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mLn2.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_fixture_external_types_fn_func_intersection( - mLn1.IntoRust(), - mLn2.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureExternalTypesFnFuncMoveSpriteToOrigin : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSpritesSprite mSprite{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mSprite.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_external_types_fn_func_move_sprite_to_origin( - mSprite.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureCallbacksFnFuncCallLogRepeat : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mLogger{}; - FfiValueRustBuffer mMessage{}; - FfiValueInt mCount{}; - FfiValueRustBuffer mExclude{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mLogger.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mMessage.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mCount.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - mExclude.Lower(aArgs[3], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_callbacks_fn_func_call_log_repeat( - mLogger.IntoRust(), - mMessage.IntoRust(), - mCount.IntoRust(), - mExclude.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureCallbacksFnFuncLogEvenNumbers : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mLogger{}; - FfiValueRustBuffer mItems{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mLogger.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mItems.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_callbacks_fn_func_log_even_numbers( - mLogger.IntoRust(), - mItems.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureCallbacksFnFuncLogEvenNumbersMainThread : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mLogger{}; - FfiValueRustBuffer mItems{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mLogger.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mItems.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_callbacks_fn_func_log_even_numbers_main_thread( - mLogger.IntoRust(), - mItems.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncExpensiveComputation : public UniffiAsyncCallHandler { -public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncExpensiveComputation() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_u32, ffi_uniffi_fixture_futures_rust_future_free_u32) { } - -private: - // Complete stores the result of the call in mUniffiReturnValue - FfiValueInt mUniffiReturnValue{}; - -protected: - // Convert a sequence of JS arguments and call the scaffolding function. - // Always called on the main thread since async Rust calls don't block, they - // return a future. - void LowerArgsAndMakeRustCall(const dom::Sequence& aArgs, ErrorResult& aError) override { - - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_expensive_computation( - ); - } - - void CallCompleteFn(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_u32(mFutureHandle, aOutStatus)); - } - -public: - void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncInitializeGeckoGlobalWorkerQueue : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_futures_fn_func_initialize_gecko_global_worker_queue( - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncInitializeGlobalWorkerQueue : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleFuturesWorkerQueue mWorkerQueue{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mWorkerQueue.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_futures_fn_func_initialize_global_worker_queue( - mWorkerQueue.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripF32 : public UniffiAsyncCallHandler { -public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripF32() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_f32, ffi_uniffi_fixture_futures_rust_future_free_f32) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripF32() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_f32, + ffi_uniffi_bindings_tests_rust_future_free_f32 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8597,14 +6161,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_f32( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_f32( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueFloat::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_f32(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_f32(mFutureHandle, aOutStatus)); } public: @@ -8616,9 +6180,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripF64 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripF64 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripF64() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_f64, ffi_uniffi_fixture_futures_rust_future_free_f64) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripF64() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_f64, + ffi_uniffi_bindings_tests_rust_future_free_f64 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8635,14 +6202,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_f64( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_f64( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueFloat::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_f64(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_f64(mFutureHandle, aOutStatus)); } public: @@ -8654,9 +6221,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI16 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI16 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI16() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_i16, ffi_uniffi_fixture_futures_rust_future_free_i16) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI16() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_i16, + ffi_uniffi_bindings_tests_rust_future_free_i16 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8673,14 +6243,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_i16( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i16( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_i16(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_i16(mFutureHandle, aOutStatus)); } public: @@ -8692,9 +6262,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI32 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI32 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI32() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_i32, ffi_uniffi_fixture_futures_rust_future_free_i32) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI32() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_i32, + ffi_uniffi_bindings_tests_rust_future_free_i32 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8711,14 +6284,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_i32( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i32( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_i32(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_i32(mFutureHandle, aOutStatus)); } public: @@ -8730,9 +6303,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI64 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI64 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI64() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_i64, ffi_uniffi_fixture_futures_rust_future_free_i64) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI64() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_i64, + ffi_uniffi_bindings_tests_rust_future_free_i64 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8749,14 +6325,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_i64( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i64( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_i64(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_i64(mFutureHandle, aOutStatus)); } public: @@ -8768,9 +6344,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI8 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI8 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripI8() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_i8, ffi_uniffi_fixture_futures_rust_future_free_i8) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripI8() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_i8, + ffi_uniffi_bindings_tests_rust_future_free_i8 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8787,14 +6366,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_i8( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_i8( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_i8(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_i8(mFutureHandle, aOutStatus)); } public: @@ -8806,9 +6385,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripMap : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripMap : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripMap() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_rust_buffer, ffi_uniffi_fixture_futures_rust_future_free_rust_buffer) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripMap() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_rust_buffer, + ffi_uniffi_bindings_tests_rust_future_free_rust_buffer + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8825,14 +6407,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_map( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_map( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); } public: @@ -8844,33 +6426,36 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripObj : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripObj : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripObj() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_pointer, ffi_uniffi_fixture_futures_rust_future_free_pointer) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripObj() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_pointer, + ffi_uniffi_bindings_tests_rust_future_free_pointer + ) { } private: // Complete stores the result of the call in mUniffiReturnValue - FfiValueObjectHandleFuturesTraveller mUniffiReturnValue{}; + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface mUniffiReturnValue{}; protected: // Convert a sequence of JS arguments and call the scaffolding function. // Always called on the main thread since async Rust calls don't block, they // return a future. void LowerArgsAndMakeRustCall(const dom::Sequence& aArgs, ErrorResult& aError) override { - FfiValueObjectHandleFuturesTraveller mV{}; + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface mV{}; mV.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_obj( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_obj( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleFuturesTraveller::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_pointer(mFutureHandle, aOutStatus)); + mUniffiReturnValue = FfiValueObjectHandleUniffiBindingsTestsAsyncInterface::FromRust( + ffi_uniffi_bindings_tests_rust_future_complete_pointer(mFutureHandle, aOutStatus)); } public: @@ -8882,9 +6467,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripString : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripString : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripString() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_rust_buffer, ffi_uniffi_fixture_futures_rust_future_free_rust_buffer) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripString() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_rust_buffer, + ffi_uniffi_bindings_tests_rust_future_free_rust_buffer + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8901,14 +6489,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_string( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_string( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); } public: @@ -8920,9 +6508,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU16 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU16 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU16() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_u16, ffi_uniffi_fixture_futures_rust_future_free_u16) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU16() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_u16, + ffi_uniffi_bindings_tests_rust_future_free_u16 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8939,14 +6530,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_u16( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u16( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_u16(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_u16(mFutureHandle, aOutStatus)); } public: @@ -8958,9 +6549,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU32 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU32 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU32() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_u32, ffi_uniffi_fixture_futures_rust_future_free_u32) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU32() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_u32, + ffi_uniffi_bindings_tests_rust_future_free_u32 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -8977,14 +6571,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_u32( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u32( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_u32(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_u32(mFutureHandle, aOutStatus)); } public: @@ -8996,9 +6590,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU64 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU64 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU64() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_u64, ffi_uniffi_fixture_futures_rust_future_free_u64) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU64() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_u64, + ffi_uniffi_bindings_tests_rust_future_free_u64 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -9015,14 +6612,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_u64( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u64( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_u64(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_u64(mFutureHandle, aOutStatus)); } public: @@ -9034,9 +6631,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU8 : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU8 : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripU8() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_u8, ffi_uniffi_fixture_futures_rust_future_free_u8) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripU8() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_u8, + ffi_uniffi_bindings_tests_rust_future_free_u8 + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -9053,14 +6653,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_u8( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_u8( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_u8(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_u8(mFutureHandle, aOutStatus)); } public: @@ -9072,9 +6672,12 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripVec : public UniffiAsyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripVec : public UniffiAsyncCallHandler { public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnFuncRoundtripVec() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_rust_buffer, ffi_uniffi_fixture_futures_rust_future_free_rust_buffer) { } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncAsyncRoundtripVec() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_rust_buffer, + ffi_uniffi_bindings_tests_rust_future_free_rust_buffer + ) { } private: // Complete stores the result of the call in mUniffiReturnValue @@ -9091,14 +6694,14 @@ protected: return; } - mFutureHandle = uniffi_uniffi_fixture_futures_fn_func_roundtrip_vec( + mFutureHandle = uniffi_uniffi_bindings_tests_fn_func_async_roundtrip_vec( mV.IntoRust() ); } void CallCompleteFn(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); + ffi_uniffi_bindings_tests_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); } public: @@ -9110,22 +6713,166 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodFuturetesterCompleteFutures : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncCloneInterface : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleFuturesFutureTester mPtr{}; - FfiValueInt mValue{}; + FfiValueObjectHandleUniffiBindingsTestsTestInterface mInt{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleUniffiBindingsTestsTestInterface mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mInt.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleUniffiBindingsTestsTestInterface::FromRust( + uniffi_uniffi_bindings_tests_fn_func_clone_interface( + mInt.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncFuncWithDefault : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mArg{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mArg.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_func_with_default( + mArg.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncFuncWithError : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mInput{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mInput.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_uniffi_bindings_tests_fn_func_func_with_error( + mInput.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncFuncWithFlatError : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mInput{}; + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mInput.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_uniffi_bindings_tests_fn_func_func_with_flat_error( + mInput.IntoRust(), + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncFuncWithMultiWordArg : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mTheArgument{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mTheArgument.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_func_with_multi_word_arg( + mTheArgument.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncInvokeTestCallbackInterfaceMethod : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mCbi{}; // MakeRustCall stores the result of the call in these fields FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); + mCbi.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -9133,8 +6880,911 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_fixture_futures_fn_method_futuretester_complete_futures( - mPtr.IntoRust(), + uniffi_uniffi_bindings_tests_fn_func_invoke_test_callback_interface_method( + mCbi.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripBool : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_bool( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripComplexCompound : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_compound( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripComplexEnum : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mEn{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mEn.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_enum( + mEn.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripComplexRec : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mRec{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mRec.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_complex_rec( + mRec.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripCustomType : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mHandle{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mHandle.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_custom_type( + mHandle.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripEnumNoData : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mEn{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mEn.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_enum_no_data( + mEn.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripEnumWithData : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mEn{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mEn.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_enum_with_data( + mEn.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripF32 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueFloat mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueFloat mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueFloat::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_f32( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripF64 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueFloat mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueFloat mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueFloat::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_f64( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripHashMap : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_hash_map( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripI16 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_i16( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripI32 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_i32( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripI64 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_i64( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripI8 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_i8( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripOption : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_option( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripSimpleRec : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mRec{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mRec.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_simple_rec( + mRec.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripString : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_string( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripU16 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_u16( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripU32 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_u32( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripU64 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_u64( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripU8 : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_u8( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncRoundtripVec : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mA{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_roundtrip_vec( + mA.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncSumWithManyTypes : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mA{}; + FfiValueInt mB{}; + FfiValueInt mC{}; + FfiValueInt mD{}; + FfiValueInt mE{}; + FfiValueInt mF{}; + FfiValueInt mG{}; + FfiValueInt mH{}; + FfiValueFloat mI{}; + FfiValueFloat mJ{}; + FfiValueInt mNegate{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueFloat mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mA.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mB.Lower(aArgs[1], aError); + if (aError.Failed()) { + return; + } + mC.Lower(aArgs[2], aError); + if (aError.Failed()) { + return; + } + mD.Lower(aArgs[3], aError); + if (aError.Failed()) { + return; + } + mE.Lower(aArgs[4], aError); + if (aError.Failed()) { + return; + } + mF.Lower(aArgs[5], aError); + if (aError.Failed()) { + return; + } + mG.Lower(aArgs[6], aError); + if (aError.Failed()) { + return; + } + mH.Lower(aArgs[7], aError); + if (aError.Failed()) { + return; + } + mI.Lower(aArgs[8], aError); + if (aError.Failed()) { + return; + } + mJ.Lower(aArgs[9], aError); + if (aError.Failed()) { + return; + } + mNegate.Lower(aArgs[10], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueFloat::FromRust( + uniffi_uniffi_bindings_tests_fn_func_sum_with_many_types( + mA.IntoRust(), + mB.IntoRust(), + mC.IntoRust(), + mD.IntoRust(), + mE.IntoRust(), + mF.IntoRust(), + mG.IntoRust(), + mH.IntoRust(), + mI.IntoRust(), + mJ.IntoRust(), + mNegate.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncSwapTestInterfaces : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueRustBuffer mInterfaces{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueRustBuffer mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mInterfaces.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + uniffi_uniffi_bindings_tests_fn_func_swap_test_interfaces( + mInterfaces.IntoRust(), + aOutStatus + ) + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnFuncTestFunc : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + + // MakeRustCall stores the result of the call in these fields + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + uniffi_uniffi_bindings_tests_fn_func_test_func( + aOutStatus + ); + } + + virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + } +}; +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnConstructorTestinterfaceNew : public UniffiSyncCallHandler { +private: + // LowerRustArgs stores the resulting arguments in these fields + FfiValueInt mValue{}; + + // MakeRustCall stores the result of the call in these fields + FfiValueObjectHandleUniffiBindingsTestsTestInterface mUniffiReturnValue{}; + +public: + void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { + mValue.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + } + + void MakeRustCall(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueObjectHandleUniffiBindingsTestsTestInterface::FromRust( + uniffi_uniffi_bindings_tests_fn_constructor_testinterface_new( mValue.IntoRust(), aOutStatus ) @@ -9149,83 +7799,26 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodFuturetesterMakeFuture : public UniffiAsyncCallHandler { -public: - ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodFuturetesterMakeFuture() : UniffiAsyncCallHandler(ffi_uniffi_fixture_futures_rust_future_poll_u8, ffi_uniffi_fixture_futures_rust_future_free_u8) { } - -private: - // Complete stores the result of the call in mUniffiReturnValue - FfiValueInt mUniffiReturnValue{}; - -protected: - // Convert a sequence of JS arguments and call the scaffolding function. - // Always called on the main thread since async Rust calls don't block, they - // return a future. - void LowerArgsAndMakeRustCall(const dom::Sequence& aArgs, ErrorResult& aError) override { - FfiValueObjectHandleFuturesFutureTester mPtr{}; - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - - mFutureHandle = uniffi_uniffi_fixture_futures_fn_method_futuretester_make_future( - mPtr.IntoRust() - ); - } - - void CallCompleteFn(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - ffi_uniffi_fixture_futures_rust_future_complete_u8(mFutureHandle, aOutStatus)); - } - -public: - void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodFuturetesterWakeFutures : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnMethodTestinterfaceGetValue : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleFuturesFutureTester mPtr{}; + FfiValueObjectHandleUniffiBindingsTestsTestInterface mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_futures_fn_method_futuretester_wake_futures( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnConstructorFuturetesterInit : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleFuturesFutureTester mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleFuturesFutureTester::FromRust( - uniffi_uniffi_fixture_futures_fn_constructor_futuretester_init( + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_method_testinterface_get_value( + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -9239,51 +7832,26 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodRusttaskRun : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnMethodTestinterfaceRefCount : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleFuturesRustTask mPtr{}; + FfiValueObjectHandleUniffiBindingsTestsTestInterface mUniffiPtr{}; // MakeRustCall stores the result of the call in these fields + FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_futures_fn_method_rusttask_run( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodTravellerName : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleFuturesTraveller mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_fixture_futures_fn_method_traveller_name( - mPtr.IntoRust(), + mUniffiReturnValue = FfiValueInt::FromRust( + uniffi_uniffi_bindings_tests_fn_method_testinterface_ref_count( + mUniffiPtr.IntoRust(), aOutStatus ) ); @@ -9297,13 +7865,13 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnConstructorTravellerNew : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnConstructorAsyncinterfaceNew : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields FfiValueRustBuffer mName{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleFuturesTraveller mUniffiReturnValue{}; + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { @@ -9314,8 +7882,8 @@ public: } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleFuturesTraveller::FromRust( - uniffi_uniffi_fixture_futures_fn_constructor_traveller_new( + mUniffiReturnValue = FfiValueObjectHandleUniffiBindingsTestsAsyncInterface::FromRust( + uniffi_uniffi_bindings_tests_fn_constructor_asyncinterface_new( mName.IntoRust(), aOutStatus ) @@ -9330,57 +7898,61 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureFuturesFnMethodWorkerqueueAddTask : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleFuturesWorkerQueue mPtr{}; - FfiValueObjectHandleFuturesRustTask mTask{}; - - // MakeRustCall stores the result of the call in these fields - +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnMethodAsyncinterfaceName : public UniffiAsyncCallHandler { public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mTask.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } + ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnMethodAsyncinterfaceName() : UniffiAsyncCallHandler( + ffi_uniffi_bindings_tests_rust_future_poll_rust_buffer, + ffi_uniffi_bindings_tests_rust_future_free_rust_buffer + ) { } - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_futures_fn_method_workerqueue_add_task( - mPtr.IntoRust(), - mTask.IntoRust(), - aOutStatus +private: + // Complete stores the result of the call in mUniffiReturnValue + FfiValueRustBuffer mUniffiReturnValue{}; + +protected: + // Convert a sequence of JS arguments and call the scaffolding function. + // Always called on the main thread since async Rust calls don't block, they + // return a future. + void LowerArgsAndMakeRustCall(const dom::Sequence& aArgs, ErrorResult& aError) override { + FfiValueObjectHandleUniffiBindingsTestsAsyncInterface mUniffiPtr{}; + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + + mFutureHandle = uniffi_uniffi_bindings_tests_fn_method_asyncinterface_name( + mUniffiPtr.IntoRust() ); } - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + void CallCompleteFn(RustCallStatus* aOutStatus) override { + mUniffiReturnValue = FfiValueRustBuffer::FromRust( + ffi_uniffi_bindings_tests_rust_future_complete_rust_buffer(mFutureHandle, aOutStatus)); + } + +public: + void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { + mUniffiReturnValue.Lift( + aCx, + &aDest.Construct(), + aError + ); } }; -class ScaffoldingCallHandlerUniffiUniffiGeometryFnFuncGradient : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnConstructorComplexmethodsNew : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mLn{}; // MakeRustCall stores the result of the call in these fields - FfiValueFloat mUniffiReturnValue{}; + FfiValueObjectHandleUniffiBindingsTestsComplexMethods mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mLn.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueFloat::FromRust( - uniffi_uniffi_geometry_fn_func_gradient( - mLn.IntoRust(), + mUniffiReturnValue = FfiValueObjectHandleUniffiBindingsTestsComplexMethods::FromRust( + uniffi_uniffi_bindings_tests_fn_constructor_complexmethods_new( aOutStatus ) ); @@ -9394,22 +7966,22 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiGeometryFnFuncIntersection : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnMethodComplexmethodsMethodWithDefault : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mLn1{}; - FfiValueRustBuffer mLn2{}; + FfiValueObjectHandleUniffiBindingsTestsComplexMethods mUniffiPtr{}; + FfiValueRustBuffer mArg{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mLn1.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); if (aError.Failed()) { return; } - mLn2.Lower(aArgs[1], aError); + mArg.Lower(aArgs[1], aError); if (aError.Failed()) { return; } @@ -9417,9 +7989,9 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_geometry_fn_func_intersection( - mLn1.IntoRust(), - mLn2.IntoRust(), + uniffi_uniffi_bindings_tests_fn_method_complexmethods_method_with_default( + mUniffiPtr.IntoRust(), + mArg.IntoRust(), aOutStatus ) ); @@ -9433,96 +8005,22 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiFixtureRefcountsFnFuncGetJsRefcount : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsFnMethodComplexmethodsMethodWithMultiWordArg : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_fixture_refcounts_fn_func_get_js_refcount( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureRefcountsFnFuncGetSingleton : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleRefcountsSingletonObject mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleRefcountsSingletonObject::FromRust( - uniffi_uniffi_fixture_refcounts_fn_func_get_singleton( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiFixtureRefcountsFnMethodSingletonobjectMethod : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRefcountsSingletonObject mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_fixture_refcounts_fn_method_singletonobject_method( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnFuncCopieCarte : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mC{}; + FfiValueObjectHandleUniffiBindingsTestsComplexMethods mUniffiPtr{}; + FfiValueRustBuffer mTheArgument{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mC.Lower(aArgs[0], aError); + mUniffiPtr.Lower(aArgs[0], aError); + if (aError.Failed()) { + return; + } + mTheArgument.Lower(aArgs[1], aError); if (aError.Failed()) { return; } @@ -9530,8 +8028,9 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_func_copie_carte( - mC.IntoRust(), + uniffi_uniffi_bindings_tests_fn_method_complexmethods_method_with_multi_word_arg( + mUniffiPtr.IntoRust(), + mTheArgument.IntoRust(), aOutStatus ) ); @@ -9545,934 +8044,17 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnFuncCopieDictionnaire : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsExternalTypesFnFuncRoundtripExtCustomType : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mD{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mD.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_func_copie_dictionnaire( - mD.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnFuncCopieEnumeration : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mE{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mE.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_func_copie_enumeration( - mE.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnFuncCopieEnumerations : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mE{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mE.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_func_copie_enumerations( - mE.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnFuncSwitcheroo : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueInt mB{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mB.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_func_switcheroo( - mB.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonBoolean : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_boolean( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonEnum : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_enum( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonF32 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueFloat mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueFloat mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueFloat::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_f32( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonF64 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueFloat mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueFloat mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueFloat::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_f64( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI16Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i16_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI16Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i16_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI32Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i32_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI32Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i32_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI64Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i64_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI64Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i64_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI8Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i8_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonI8Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_i8_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonNull : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_null( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonSequence : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_sequence( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonString : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_string( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU16Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u16_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU16Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u16_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU32Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU32Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU32Oct : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u32_oct( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU64Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; + FfiValueInt mCustom{}; // MakeRustCall stores the result of the call in these fields FfiValueInt mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); + mCustom.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -10480,9 +8062,8 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u64_dec( - mPtr.IntoRust(), - mValue.IntoRust(), + uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_custom_type( + mCustom.IntoRust(), aOutStatus ) ); @@ -10496,139 +8077,17 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU64Hex : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsExternalTypesFnFuncRoundtripExtEnum : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u64_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU8Dec : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u8_dec( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonU8Hex : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_u8_hex( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodOptionneurSinonZero : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointOptionneur mPtr{}; - FfiValueRustBuffer mValue{}; + FfiValueRustBuffer mEn{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); + mEn.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -10636,9 +8095,8 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_optionneur_sinon_zero( - mPtr.IntoRust(), - mValue.IntoRust(), + uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_enum( + mEn.IntoRust(), aOutStatus ) ); @@ -10652,59 +8110,26 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnConstructorOptionneurNew : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsExternalTypesFnFuncRoundtripExtInterface : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields + FfiValueObjectHandleUniffiBindingsTestsTestInterface mInt{}; // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleRondpointOptionneur mUniffiReturnValue{}; + FfiValueObjectHandleUniffiBindingsTestsTestInterface mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleRondpointOptionneur::FromRust( - uniffi_uniffi_rondpoint_fn_constructor_optionneur_new( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueBoolean : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); + mInt.Lower(aArgs[0], aError); if (aError.Failed()) { return; } } void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_boolean( - mPtr.IntoRust(), - mValue.IntoRust(), + mUniffiReturnValue = FfiValueObjectHandleUniffiBindingsTestsTestInterface::FromRust( + uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_interface( + mInt.IntoRust(), aOutStatus ) ); @@ -10718,256 +8143,17 @@ public: ); } }; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueDouble : public UniffiSyncCallHandler { +class ScaffoldingCallHandlerUniffiUniffiBindingsTestsExternalTypesFnFuncRoundtripExtRecord : public UniffiSyncCallHandler { private: // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueFloat mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueFloat mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueFloat::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_double( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueFloat : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueFloat mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueFloat mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueFloat::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_float( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueI16 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i16( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueI32 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i32( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueI64 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i64( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueI8 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_i8( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueNombres : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueRustBuffer mValue{}; + FfiValueRustBuffer mRec{}; // MakeRustCall stores the result of the call in these fields FfiValueRustBuffer mUniffiReturnValue{}; public: void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); + mRec.Lower(aArgs[0], aError); if (aError.Failed()) { return; } @@ -10975,1566 +8161,8 @@ public: void MakeRustCall(RustCallStatus* aOutStatus) override { mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_nombres( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueNombresSignes : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_nombres_signes( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueOptionneurDictionnaire : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_optionneur_dictionnaire( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueString : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_string( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueU16 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u16( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueU32 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u32( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueU64 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u64( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodRetourneurIdentiqueU8 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointRetourneur mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_rondpoint_fn_method_retourneur_identique_u8( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnConstructorRetourneurNew : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleRondpointRetourneur mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleRondpointRetourneur::FromRust( - uniffi_uniffi_rondpoint_fn_constructor_retourneur_new( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringBoolean : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_boolean( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringDouble : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueFloat mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_double( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringFloat : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueFloat mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_float( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringI16 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i16( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringI32 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i32( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringI64 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i64( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringI8 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_i8( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringU16 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u16( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringU32 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u32( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringU64 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u64( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierToStringU8 : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueInt mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_to_string_u8( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnMethodStringifierWellKnownString : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleRondpointStringifier mPtr{}; - FfiValueRustBuffer mValue{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mValue.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_rondpoint_fn_method_stringifier_well_known_string( - mPtr.IntoRust(), - mValue.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiRondpointFnConstructorStringifierNew : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleRondpointStringifier mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleRondpointStringifier::FromRust( - uniffi_uniffi_rondpoint_fn_constructor_stringifier_new( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiSpritesFnFuncTranslate : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mP{}; - FfiValueRustBuffer mV{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mP.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mV.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_sprites_fn_func_translate( - mP.IntoRust(), - mV.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiSpritesFnMethodSpriteGetPosition : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSpritesSprite mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_sprites_fn_method_sprite_get_position( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiSpritesFnMethodSpriteMoveBy : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSpritesSprite mPtr{}; - FfiValueRustBuffer mDirection{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mDirection.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_sprites_fn_method_sprite_move_by( - mPtr.IntoRust(), - mDirection.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiSpritesFnMethodSpriteMoveTo : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleSpritesSprite mPtr{}; - FfiValueRustBuffer mPosition{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mPosition.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_sprites_fn_method_sprite_move_to( - mPtr.IntoRust(), - mPosition.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiSpritesFnConstructorSpriteNew : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mInitialPosition{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSpritesSprite mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mInitialPosition.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSpritesSprite::FromRust( - uniffi_uniffi_sprites_fn_constructor_sprite_new( - mInitialPosition.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiSpritesFnConstructorSpriteNewRelativeTo : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mReference{}; - FfiValueRustBuffer mDirection{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleSpritesSprite mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mReference.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mDirection.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleSpritesSprite::FromRust( - uniffi_uniffi_sprites_fn_constructor_sprite_new_relative_to( - mReference.IntoRust(), - mDirection.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnFuncCreateEntryWith : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueRustBuffer mTodo{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mTodo.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_func_create_entry_with( - mTodo.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnFuncGetDefaultList : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_func_get_default_list( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnFuncSetDefaultList : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mList{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mList.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_func_set_default_list( - mList.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistAddEntries : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - FfiValueRustBuffer mEntries{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mEntries.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_method_todolist_add_entries( - mPtr.IntoRust(), - mEntries.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistAddEntry : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - FfiValueRustBuffer mEntry{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mEntry.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_method_todolist_add_entry( - mPtr.IntoRust(), - mEntry.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistAddItem : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - FfiValueRustBuffer mTodo{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mTodo.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_method_todolist_add_item( - mPtr.IntoRust(), - mTodo.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistAddItems : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - FfiValueRustBuffer mItems{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mItems.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_method_todolist_add_items( - mPtr.IntoRust(), - mItems.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistClearItem : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - FfiValueRustBuffer mTodo{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mTodo.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_method_todolist_clear_item( - mPtr.IntoRust(), - mTodo.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistGetEntries : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_method_todolist_get_entries( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistGetFirst : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_method_todolist_get_first( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistGetItems : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_method_todolist_get_items( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistGetLast : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_method_todolist_get_last( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistGetLastEntry : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueRustBuffer mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueRustBuffer::FromRust( - uniffi_uniffi_todolist_fn_method_todolist_get_last_entry( - mPtr.IntoRust(), - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnMethodTodolistMakeDefault : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleTodolistTodoList mPtr{}; - - // MakeRustCall stores the result of the call in these fields - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - uniffi_uniffi_todolist_fn_method_todolist_make_default( - mPtr.IntoRust(), - aOutStatus - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - } -}; -class ScaffoldingCallHandlerUniffiUniffiTodolistFnConstructorTodolistNew : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleTodolistTodoList mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleTodolistTodoList::FromRust( - uniffi_uniffi_todolist_fn_constructor_todolist_new( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTraitInterfacesFnFuncMakeBuggyCalculator : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleUniffiTraitInterfacesCalc mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleUniffiTraitInterfacesCalc::FromRust( - uniffi_uniffi_trait_interfaces_fn_func_make_buggy_calculator( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTraitInterfacesFnFuncMakeCalculator : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - - // MakeRustCall stores the result of the call in these fields - FfiValueObjectHandleUniffiTraitInterfacesCalc mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueObjectHandleUniffiTraitInterfacesCalc::FromRust( - uniffi_uniffi_trait_interfaces_fn_func_make_calculator( - aOutStatus - ) - ); - } - - virtual void LiftSuccessfulCallResult(JSContext* aCx, dom::Optional& aDest, ErrorResult& aError) override { - mUniffiReturnValue.Lift( - aCx, - &aDest.Construct(), - aError - ); - } -}; -class ScaffoldingCallHandlerUniffiUniffiTraitInterfacesFnMethodCalcAdd : public UniffiSyncCallHandler { -private: - // LowerRustArgs stores the resulting arguments in these fields - FfiValueObjectHandleUniffiTraitInterfacesCalc mPtr{}; - FfiValueInt mA{}; - FfiValueInt mB{}; - - // MakeRustCall stores the result of the call in these fields - FfiValueInt mUniffiReturnValue{}; - -public: - void LowerRustArgs(const dom::Sequence& aArgs, ErrorResult& aError) override { - mPtr.Lower(aArgs[0], aError); - if (aError.Failed()) { - return; - } - mA.Lower(aArgs[1], aError); - if (aError.Failed()) { - return; - } - mB.Lower(aArgs[2], aError); - if (aError.Failed()) { - return; - } - } - - void MakeRustCall(RustCallStatus* aOutStatus) override { - mUniffiReturnValue = FfiValueInt::FromRust( - uniffi_uniffi_trait_interfaces_fn_method_calc_add( - mPtr.IntoRust(), - mA.IntoRust(), - mB.IntoRust(), + uniffi_uniffi_bindings_tests_external_types_fn_func_roundtrip_ext_record( + mRec.IntoRust(), aOutStatus ) ); @@ -12553,685 +8181,460 @@ public: UniquePtr GetSyncCallHandler(uint64_t aId) { switch (aId) { - case 0: { - return MakeUnique(); - } case 1: { - return MakeUnique(); - } - case 2: { - return MakeUnique(); - } - case 3: { return MakeUnique(); } + case 2: { + return MakeUnique(); + } + case 3: { + return MakeUnique(); + } case 4: { - return MakeUnique(); + return MakeUnique(); } case 5: { - return MakeUnique(); + return MakeUnique(); } case 6: { - return MakeUnique(); + return MakeUnique(); } case 7: { - return MakeUnique(); + return MakeUnique(); } case 8: { - return MakeUnique(); - } - case 9: { - return MakeUnique(); - } - case 10: { - return MakeUnique(); - } - case 11: { - return MakeUnique(); - } - case 12: { - return MakeUnique(); - } - case 13: { - return MakeUnique(); - } - case 14: { - return MakeUnique(); - } - case 15: { - return MakeUnique(); - } - case 16: { return MakeUnique(); } + case 9: { + return MakeUnique(); + } + case 10: { + return MakeUnique(); + } + case 11: { + return MakeUnique(); + } + case 12: { + return MakeUnique(); + } + case 13: { + return MakeUnique(); + } + case 14: { + return MakeUnique(); + } + case 15: { + return MakeUnique(); + } + case 16: { + return MakeUnique(); + } case 17: { - return MakeUnique(); + return MakeUnique(); } case 18: { - return MakeUnique(); - } - case 19: { - return MakeUnique(); - } - case 20: { return MakeUnique(); } + case 19: { + return MakeUnique(); + } + case 20: { + return MakeUnique(); + } case 21: { - return MakeUnique(); + return MakeUnique(); } case 22: { - return MakeUnique(); + return MakeUnique(); } case 23: { - return MakeUnique(); + return MakeUnique(); } case 24: { - return MakeUnique(); + return MakeUnique(); } case 25: { - return MakeUnique(); + return MakeUnique(); } case 26: { - return MakeUnique(); + return MakeUnique(); } case 27: { - return MakeUnique(); + return MakeUnique(); } case 28: { - return MakeUnique(); - } - case 29: { - return MakeUnique(); - } - case 30: { return MakeUnique(); } + case 29: { + return MakeUnique(); + } + case 30: { + return MakeUnique(); + } case 31: { - return MakeUnique(); + return MakeUnique(); } case 32: { - return MakeUnique(); - } - case 33: { - return MakeUnique(); - } - case 34: { - return MakeUnique(); - } - case 35: { - return MakeUnique(); - } - case 36: { return MakeUnique(); } + case 33: { + return MakeUnique(); + } + case 34: { + return MakeUnique(); + } + case 35: { + return MakeUnique(); + } + case 36: { + return MakeUnique(); + } case 37: { - return MakeUnique(); + return MakeUnique(); } case 38: { - return MakeUnique(); + return MakeUnique(); } case 39: { - return MakeUnique(); - } - case 40: { - return MakeUnique(); - } - case 41: { - return MakeUnique(); - } - case 42: { - return MakeUnique(); - } - case 43: { - return MakeUnique(); - } - case 44: { - return MakeUnique(); - } - case 45: { - return MakeUnique(); - } - case 46: { - return MakeUnique(); - } - case 47: { - return MakeUnique(); - } - case 48: { - return MakeUnique(); - } - case 49: { - return MakeUnique(); - } - case 50: { - return MakeUnique(); - } - case 51: { - return MakeUnique(); - } - case 52: { - return MakeUnique(); - } - case 53: { return MakeUnique(); } + case 40: { + return MakeUnique(); + } + case 41: { + return MakeUnique(); + } + case 42: { + return MakeUnique(); + } + case 43: { + return MakeUnique(); + } + case 44: { + return MakeUnique(); + } + case 45: { + return MakeUnique(); + } + case 46: { + return MakeUnique(); + } + case 47: { + return MakeUnique(); + } + case 48: { + return MakeUnique(); + } + case 49: { + return MakeUnique(); + } + case 50: { + return MakeUnique(); + } + case 51: { + return MakeUnique(); + } + case 52: { + return MakeUnique(); + } + case 53: { + return MakeUnique(); + } case 54: { - return MakeUnique(); + return MakeUnique(); } case 55: { - return MakeUnique(); - } - case 56: { - return MakeUnique(); - } - case 57: { - return MakeUnique(); - } - case 58: { - return MakeUnique(); - } - case 59: { - return MakeUnique(); - } - case 60: { - return MakeUnique(); - } - case 61: { return MakeUnique(); } + case 56: { + return MakeUnique(); + } + case 57: { + return MakeUnique(); + } + case 58: { + return MakeUnique(); + } + case 59: { + return MakeUnique(); + } + case 60: { + return MakeUnique(); + } + case 61: { + return MakeUnique(); + } case 62: { - return MakeUnique(); + return MakeUnique(); } case 63: { - return MakeUnique(); + return MakeUnique(); } case 64: { - return MakeUnique(); + return MakeUnique(); } case 65: { - return MakeUnique(); + return MakeUnique(); } case 66: { - return MakeUnique(); + return MakeUnique(); } case 67: { - return MakeUnique(); + return MakeUnique(); } case 68: { - return MakeUnique(); + return MakeUnique(); } case 69: { - return MakeUnique(); + return MakeUnique(); } case 70: { - return MakeUnique(); + return MakeUnique(); } case 71: { - return MakeUnique(); + return MakeUnique(); } case 72: { - return MakeUnique(); + return MakeUnique(); } case 73: { - return MakeUnique(); + return MakeUnique(); } case 74: { - return MakeUnique(); + return MakeUnique(); } case 75: { - return MakeUnique(); + return MakeUnique(); } case 76: { - return MakeUnique(); + return MakeUnique(); } case 77: { - return MakeUnique(); + return MakeUnique(); } case 78: { - return MakeUnique(); + return MakeUnique(); } case 79: { - return MakeUnique(); + return MakeUnique(); } case 80: { - return MakeUnique(); + return MakeUnique(); } case 81: { - return MakeUnique(); - } - case 82: { - return MakeUnique(); - } - case 83: { - return MakeUnique(); - } - case 84: { - return MakeUnique(); - } - case 85: { - return MakeUnique(); - } - case 86: { return MakeUnique(); } + case 82: { + return MakeUnique(); + } + case 83: { + return MakeUnique(); + } + case 84: { + return MakeUnique(); + } + case 85: { + return MakeUnique(); + } + case 86: { + return MakeUnique(); + } case 87: { - return MakeUnique(); + return MakeUnique(); } case 88: { - return MakeUnique(); + return MakeUnique(); } case 89: { - return MakeUnique(); + return MakeUnique(); } case 90: { - return MakeUnique(); + return MakeUnique(); } case 91: { - return MakeUnique(); + return MakeUnique(); } case 92: { - return MakeUnique(); + return MakeUnique(); } case 93: { - return MakeUnique(); + return MakeUnique(); } case 94: { - return MakeUnique(); + return MakeUnique(); } case 95: { - return MakeUnique(); + return MakeUnique(); } case 96: { - return MakeUnique(); + return MakeUnique(); } case 97: { - return MakeUnique(); + return MakeUnique(); } case 98: { - return MakeUnique(); + return MakeUnique(); } case 99: { - return MakeUnique(); + return MakeUnique(); } case 100: { - return MakeUnique(); + return MakeUnique(); } case 101: { - return MakeUnique(); + return MakeUnique(); } case 102: { - return MakeUnique(); + return MakeUnique(); } case 103: { - return MakeUnique(); + return MakeUnique(); } case 104: { - return MakeUnique(); + return MakeUnique(); } case 105: { - return MakeUnique(); + return MakeUnique(); } case 106: { - return MakeUnique(); + return MakeUnique(); } case 107: { - return MakeUnique(); + return MakeUnique(); } case 108: { - return MakeUnique(); + return MakeUnique(); + } + case 109: { + return MakeUnique(); } #ifdef MOZ_UNIFFI_FIXTURES - case 109: { - return MakeUnique(); - } - case 110: { - return MakeUnique(); - } - case 111: { - return MakeUnique(); - } - case 112: { - return MakeUnique(); - } - case 113: { - return MakeUnique(); - } - case 114: { - return MakeUnique(); - } - case 115: { - return MakeUnique(); - } - case 116: { - return MakeUnique(); - } - case 117: { - return MakeUnique(); - } - case 118: { - return MakeUnique(); - } - case 119: { - return MakeUnique(); - } - case 120: { - return MakeUnique(); - } - case 121: { - return MakeUnique(); - } - case 122: { - return MakeUnique(); - } - case 123: { - return MakeUnique(); - } case 124: { - return MakeUnique(); + return MakeUnique(); } case 125: { - return MakeUnique(); + return MakeUnique(); } case 126: { - return MakeUnique(); + return MakeUnique(); } case 127: { - return MakeUnique(); + return MakeUnique(); + } + case 128: { + return MakeUnique(); } case 129: { - return MakeUnique(); + return MakeUnique(); } case 130: { - return MakeUnique(); + return MakeUnique(); + } + case 131: { + return MakeUnique(); + } + case 132: { + return MakeUnique(); + } + case 133: { + return MakeUnique(); + } + case 134: { + return MakeUnique(); + } + case 135: { + return MakeUnique(); + } + case 136: { + return MakeUnique(); + } + case 137: { + return MakeUnique(); + } + case 138: { + return MakeUnique(); + } + case 139: { + return MakeUnique(); + } + case 140: { + return MakeUnique(); + } + case 141: { + return MakeUnique(); + } + case 142: { + return MakeUnique(); + } + case 143: { + return MakeUnique(); + } + case 144: { + return MakeUnique(); } case 145: { - return MakeUnique(); + return MakeUnique(); + } + case 146: { + return MakeUnique(); } case 147: { - return MakeUnique(); + return MakeUnique(); } case 148: { - return MakeUnique(); + return MakeUnique(); } case 149: { - return MakeUnique(); + return MakeUnique(); } case 150: { - return MakeUnique(); + return MakeUnique(); } case 151: { - return MakeUnique(); + return MakeUnique(); } case 152: { - return MakeUnique(); + return MakeUnique(); } case 153: { - return MakeUnique(); + return MakeUnique(); } case 154: { - return MakeUnique(); + return MakeUnique(); } case 155: { - return MakeUnique(); + return MakeUnique(); } case 156: { - return MakeUnique(); + return MakeUnique(); } case 157: { - return MakeUnique(); + return MakeUnique(); } case 158: { - return MakeUnique(); - } - case 159: { - return MakeUnique(); + return MakeUnique(); } case 160: { - return MakeUnique(); + return MakeUnique(); } case 161: { - return MakeUnique(); + return MakeUnique(); } case 162: { - return MakeUnique(); + return MakeUnique(); } case 163: { - return MakeUnique(); + return MakeUnique(); } case 164: { - return MakeUnique(); + return MakeUnique(); } case 165: { - return MakeUnique(); + return MakeUnique(); } case 166: { - return MakeUnique(); - } - case 167: { - return MakeUnique(); - } - case 168: { - return MakeUnique(); - } - case 169: { - return MakeUnique(); - } - case 170: { - return MakeUnique(); - } - case 171: { - return MakeUnique(); - } - case 172: { - return MakeUnique(); - } - case 173: { - return MakeUnique(); - } - case 174: { - return MakeUnique(); - } - case 175: { - return MakeUnique(); - } - case 176: { - return MakeUnique(); - } - case 177: { - return MakeUnique(); - } - case 178: { - return MakeUnique(); - } - case 179: { - return MakeUnique(); - } - case 180: { - return MakeUnique(); - } - case 181: { - return MakeUnique(); - } - case 182: { - return MakeUnique(); - } - case 183: { - return MakeUnique(); - } - case 184: { - return MakeUnique(); - } - case 185: { - return MakeUnique(); - } - case 186: { - return MakeUnique(); - } - case 187: { - return MakeUnique(); - } - case 188: { - return MakeUnique(); - } - case 189: { - return MakeUnique(); - } - case 190: { - return MakeUnique(); - } - case 191: { - return MakeUnique(); - } - case 192: { - return MakeUnique(); - } - case 193: { - return MakeUnique(); - } - case 194: { - return MakeUnique(); - } - case 195: { - return MakeUnique(); - } - case 196: { - return MakeUnique(); - } - case 197: { - return MakeUnique(); - } - case 198: { - return MakeUnique(); - } - case 199: { - return MakeUnique(); - } - case 200: { - return MakeUnique(); - } - case 201: { - return MakeUnique(); - } - case 202: { - return MakeUnique(); - } - case 203: { - return MakeUnique(); - } - case 204: { - return MakeUnique(); - } - case 205: { - return MakeUnique(); - } - case 206: { - return MakeUnique(); - } - case 207: { - return MakeUnique(); - } - case 208: { - return MakeUnique(); - } - case 209: { - return MakeUnique(); - } - case 210: { - return MakeUnique(); - } - case 211: { - return MakeUnique(); - } - case 212: { - return MakeUnique(); - } - case 213: { - return MakeUnique(); - } - case 214: { - return MakeUnique(); - } - case 215: { - return MakeUnique(); - } - case 216: { - return MakeUnique(); - } - case 217: { - return MakeUnique(); - } - case 218: { - return MakeUnique(); - } - case 219: { - return MakeUnique(); - } - case 220: { - return MakeUnique(); - } - case 221: { - return MakeUnique(); - } - case 222: { - return MakeUnique(); - } - case 223: { - return MakeUnique(); - } - case 224: { - return MakeUnique(); - } - case 225: { - return MakeUnique(); - } - case 226: { - return MakeUnique(); - } - case 227: { - return MakeUnique(); - } - case 228: { - return MakeUnique(); - } - case 229: { - return MakeUnique(); - } - case 230: { - return MakeUnique(); - } - case 231: { - return MakeUnique(); - } - case 232: { - return MakeUnique(); - } - case 233: { - return MakeUnique(); - } - case 234: { - return MakeUnique(); - } - case 235: { - return MakeUnique(); - } - case 236: { - return MakeUnique(); - } - case 237: { - return MakeUnique(); - } - case 238: { - return MakeUnique(); - } - case 239: { - return MakeUnique(); - } - case 240: { - return MakeUnique(); - } - case 241: { - return MakeUnique(); + return MakeUnique(); } #endif /* MOZ_UNIFFI_FIXTURES */ @@ -13245,53 +8648,50 @@ UniquePtr GetAsyncCallHandler(uint64_t aId) { #ifdef MOZ_UNIFFI_FIXTURES - case 128: { - return MakeUnique(); + case 110: { + return MakeUnique(); } - case 131: { - return MakeUnique(); + case 111: { + return MakeUnique(); } - case 132: { - return MakeUnique(); + case 112: { + return MakeUnique(); } - case 133: { - return MakeUnique(); + case 113: { + return MakeUnique(); } - case 134: { - return MakeUnique(); + case 114: { + return MakeUnique(); } - case 135: { - return MakeUnique(); + case 115: { + return MakeUnique(); } - case 136: { - return MakeUnique(); + case 116: { + return MakeUnique(); } - case 137: { - return MakeUnique(); + case 117: { + return MakeUnique(); } - case 138: { - return MakeUnique(); + case 118: { + return MakeUnique(); } - case 139: { - return MakeUnique(); + case 119: { + return MakeUnique(); } - case 140: { - return MakeUnique(); + case 120: { + return MakeUnique(); } - case 141: { - return MakeUnique(); + case 121: { + return MakeUnique(); } - case 142: { - return MakeUnique(); + case 122: { + return MakeUnique(); } - case 143: { - return MakeUnique(); + case 123: { + return MakeUnique(); } - case 144: { - return MakeUnique(); - } - case 146: { - return MakeUnique(); + case 159: { + return MakeUnique(); } #endif /* MOZ_UNIFFI_FIXTURES */ @@ -13299,225 +8699,469 @@ UniquePtr GetAsyncCallHandler(uint64_t aId) { return nullptr; } } +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +// Callback interface method handlers, vtables, etc. -Maybe> ReadPointer(const GlobalObject& aGlobal, uint64_t aId, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { - const UniFFIPointerType* type; - switch (aId) { +static StaticRefPtr gUniffiCallbackHandlerContextIdCallback; - case 0: { - type = &kContextIdContextIdComponentPointerType; - break; - } - case 1: { - type = &kRelevancyRelevancyStorePointerType; - break; - } - case 2: { - type = &kRemoteSettingsRemoteSettingsPointerType; - break; - } - case 3: { - type = &kRemoteSettingsRemoteSettingsClientPointerType; - break; - } - case 4: { - type = &kRemoteSettingsRemoteSettingsServicePointerType; - break; - } - case 5: { - type = &kSearchSearchEngineSelectorPointerType; - break; - } - case 6: { - type = &kSuggestSuggestStorePointerType; - break; - } - case 7: { - type = &kSuggestSuggestStoreBuilderPointerType; - break; - } - case 8: { - type = &kTabsRemoteCommandStorePointerType; - break; - } - case 9: { - type = &kTabsTabsBridgedEnginePointerType; - break; - } - case 10: { - type = &kTabsTabsStorePointerType; - break; - } - case 11: { - type = &kWebextstorageWebExtStorageBridgedEnginePointerType; - break; - } - case 12: { - type = &kWebextstorageWebExtStorageStorePointerType; - break; - } +class CallbackInterfaceMethodContextIdContextIdCallbackPersist : public UniffiCallbackMethodHandlerBase { +private: + // Rust arguments + FfiValueRustBuffer mContextId{}; + FfiValueInt mCreationDate{}; -#ifdef MOZ_UNIFFI_FIXTURES - case 13: { - type = &kFuturesFutureTesterPointerType; - break; - } - case 14: { - type = &kFuturesRustTaskPointerType; - break; - } - case 15: { - type = &kFuturesTravellerPointerType; - break; - } - case 16: { - type = &kFuturesWorkerQueuePointerType; - break; - } - case 17: { - type = &kRefcountsSingletonObjectPointerType; - break; - } - case 18: { - type = &kRondpointOptionneurPointerType; - break; - } - case 19: { - type = &kRondpointRetourneurPointerType; - break; - } - case 20: { - type = &kRondpointStringifierPointerType; - break; - } - case 21: { - type = &kSpritesSpritePointerType; - break; - } - case 22: { - type = &kTodolistTodoListPointerType; - break; - } - case 23: { - type = &kUniffiTraitInterfacesCalcPointerType; - break; - } -#endif /* MOZ_UNIFFI_FIXTURES */ - default: - return Nothing(); +public: + CallbackInterfaceMethodContextIdContextIdCallbackPersist(uint64_t aUniffiHandle, RustBuffer aContextId, int64_t aCreationDate) + : UniffiCallbackMethodHandlerBase("ContextIdCallback", aUniffiHandle), mContextId(FfiValueRustBuffer::FromRust(aContextId)), mCreationDate(FfiValueInt::FromRust(aCreationDate)) { } - return Some(UniFFIPointer::Read(aArrayBuff, aPosition, type, aError)); + + MOZ_CAN_RUN_SCRIPT + void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { + nsTArray uniffiArgs; + + // Setup + if (!uniffiArgs.AppendElements(3, mozilla::fallible)) { + aError.Throw(NS_ERROR_OUT_OF_MEMORY); + return; + } + + // Convert each argument + mUniffiHandle.Lift( + aCx, + &uniffiArgs[0], + aError); + if (aError.Failed()) { + return; + } + mContextId.Lift( + aCx, + &uniffiArgs[1], + aError); + if (aError.Failed()) { + return; + } + mCreationDate.Lift( + aCx, + &uniffiArgs[2], + aError); + if (aError.Failed()) { + return; + } + + // Stores the return value. For now, we currently don't do anything with it, since we only support + // fire-and-forget callbacks. + NullableRootedUnion returnValue(aCx); + // Make the call + aJsHandler->Call(mUniffiHandle.IntoRust(), 0, uniffiArgs, returnValue, aError); + } +}; + +extern "C" void callback_interface_context_id_context_id_callback_persist( + uint64_t aUniffiHandle, + RustBuffer aContextId, + int64_t aCreationDate, + void* aUniffiOutReturn, + RustCallStatus* uniffiOutStatus +) { + UniquePtr handler = MakeUnique(aUniffiHandle, aContextId, aCreationDate); + // Note: currently we only support queueing fire-and-forget async callbacks + + // For fire-and-forget callbacks, we don't know if the method succeeds or not + // since it's called later. uniffiCallStatus is initialized to a successful + // state by the Rust code, so there's no need to modify it. + UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gUniffiCallbackHandlerContextIdCallback); } -bool WritePointer(const GlobalObject& aGlobal, uint64_t aId, const UniFFIPointer& aPtr, const ArrayBuffer& aArrayBuff, long aPosition, ErrorResult& aError) { - const UniFFIPointerType* type; - switch (aId) { +class CallbackInterfaceMethodContextIdContextIdCallbackRotated : public UniffiCallbackMethodHandlerBase { +private: + // Rust arguments + FfiValueRustBuffer mOldContextId{}; - case 0: { - type = &kContextIdContextIdComponentPointerType; - break; +public: + CallbackInterfaceMethodContextIdContextIdCallbackRotated(uint64_t aUniffiHandle, RustBuffer aOldContextId) + : UniffiCallbackMethodHandlerBase("ContextIdCallback", aUniffiHandle), mOldContextId(FfiValueRustBuffer::FromRust(aOldContextId)) { + } + + MOZ_CAN_RUN_SCRIPT + void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { + nsTArray uniffiArgs; + + // Setup + if (!uniffiArgs.AppendElements(2, mozilla::fallible)) { + aError.Throw(NS_ERROR_OUT_OF_MEMORY); + return; } + + // Convert each argument + mUniffiHandle.Lift( + aCx, + &uniffiArgs[0], + aError); + if (aError.Failed()) { + return; + } + mOldContextId.Lift( + aCx, + &uniffiArgs[1], + aError); + if (aError.Failed()) { + return; + } + + // Stores the return value. For now, we currently don't do anything with it, since we only support + // fire-and-forget callbacks. + NullableRootedUnion returnValue(aCx); + // Make the call + aJsHandler->Call(mUniffiHandle.IntoRust(), 1, uniffiArgs, returnValue, aError); + } +}; + +extern "C" void callback_interface_context_id_context_id_callback_rotated( + uint64_t aUniffiHandle, + RustBuffer aOldContextId, + void* aUniffiOutReturn, + RustCallStatus* uniffiOutStatus +) { + UniquePtr handler = MakeUnique(aUniffiHandle, aOldContextId); + // Note: currently we only support queueing fire-and-forget async callbacks + + // For fire-and-forget callbacks, we don't know if the method succeeds or not + // since it's called later. uniffiCallStatus is initialized to a successful + // state by the Rust code, so there's no need to modify it. + UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gUniffiCallbackHandlerContextIdCallback); +} + +extern "C" void callback_free_context_id_context_id_callback(uint64_t uniffiHandle) { + // Callback object handles are keys in a map stored in the JS handler. To + // handle the free call, make a call into JS which will remove the key. + // Fire-and-forget is perfect for this. + UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("ContextIdCallback", uniffiHandle), &gUniffiCallbackHandlerContextIdCallback); +} + +static VTableCallbackInterfaceContextIdCallback kUniffiVtableContextIdCallback { + callback_interface_context_id_context_id_callback_persist, + callback_interface_context_id_context_id_callback_rotated, + callback_free_context_id_context_id_callback +}; +static StaticRefPtr gUniffiCallbackHandlerApplicationErrorReporter; + +class CallbackInterfaceMethodErrorsupportApplicationErrorReporterReportError : public UniffiCallbackMethodHandlerBase { +private: + // Rust arguments + FfiValueRustBuffer mTypeName{}; + FfiValueRustBuffer mMessage{}; + +public: + CallbackInterfaceMethodErrorsupportApplicationErrorReporterReportError(uint64_t aUniffiHandle, RustBuffer aTypeName, RustBuffer aMessage) + : UniffiCallbackMethodHandlerBase("ApplicationErrorReporter", aUniffiHandle), mTypeName(FfiValueRustBuffer::FromRust(aTypeName)), mMessage(FfiValueRustBuffer::FromRust(aMessage)) { + } + + MOZ_CAN_RUN_SCRIPT + void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { + nsTArray uniffiArgs; + + // Setup + if (!uniffiArgs.AppendElements(3, mozilla::fallible)) { + aError.Throw(NS_ERROR_OUT_OF_MEMORY); + return; + } + + // Convert each argument + mUniffiHandle.Lift( + aCx, + &uniffiArgs[0], + aError); + if (aError.Failed()) { + return; + } + mTypeName.Lift( + aCx, + &uniffiArgs[1], + aError); + if (aError.Failed()) { + return; + } + mMessage.Lift( + aCx, + &uniffiArgs[2], + aError); + if (aError.Failed()) { + return; + } + + // Stores the return value. For now, we currently don't do anything with it, since we only support + // fire-and-forget callbacks. + NullableRootedUnion returnValue(aCx); + // Make the call + aJsHandler->Call(mUniffiHandle.IntoRust(), 0, uniffiArgs, returnValue, aError); + } +}; + +extern "C" void callback_interface_errorsupport_application_error_reporter_report_error( + uint64_t aUniffiHandle, + RustBuffer aTypeName, + RustBuffer aMessage, + void* aUniffiOutReturn, + RustCallStatus* uniffiOutStatus +) { + UniquePtr handler = MakeUnique(aUniffiHandle, aTypeName, aMessage); + // Note: currently we only support queueing fire-and-forget async callbacks + + // For fire-and-forget callbacks, we don't know if the method succeeds or not + // since it's called later. uniffiCallStatus is initialized to a successful + // state by the Rust code, so there's no need to modify it. + UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gUniffiCallbackHandlerApplicationErrorReporter); +} + +class CallbackInterfaceMethodErrorsupportApplicationErrorReporterReportBreadcrumb : public UniffiCallbackMethodHandlerBase { +private: + // Rust arguments + FfiValueRustBuffer mMessage{}; + FfiValueRustBuffer mModule{}; + FfiValueInt mLine{}; + FfiValueInt mColumn{}; + +public: + CallbackInterfaceMethodErrorsupportApplicationErrorReporterReportBreadcrumb(uint64_t aUniffiHandle, RustBuffer aMessage, RustBuffer aModule, uint32_t aLine, uint32_t aColumn) + : UniffiCallbackMethodHandlerBase("ApplicationErrorReporter", aUniffiHandle), mMessage(FfiValueRustBuffer::FromRust(aMessage)), mModule(FfiValueRustBuffer::FromRust(aModule)), mLine(FfiValueInt::FromRust(aLine)), mColumn(FfiValueInt::FromRust(aColumn)) { + } + + MOZ_CAN_RUN_SCRIPT + void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { + nsTArray uniffiArgs; + + // Setup + if (!uniffiArgs.AppendElements(5, mozilla::fallible)) { + aError.Throw(NS_ERROR_OUT_OF_MEMORY); + return; + } + + // Convert each argument + mUniffiHandle.Lift( + aCx, + &uniffiArgs[0], + aError); + if (aError.Failed()) { + return; + } + mMessage.Lift( + aCx, + &uniffiArgs[1], + aError); + if (aError.Failed()) { + return; + } + mModule.Lift( + aCx, + &uniffiArgs[2], + aError); + if (aError.Failed()) { + return; + } + mLine.Lift( + aCx, + &uniffiArgs[3], + aError); + if (aError.Failed()) { + return; + } + mColumn.Lift( + aCx, + &uniffiArgs[4], + aError); + if (aError.Failed()) { + return; + } + + // Stores the return value. For now, we currently don't do anything with it, since we only support + // fire-and-forget callbacks. + NullableRootedUnion returnValue(aCx); + // Make the call + aJsHandler->Call(mUniffiHandle.IntoRust(), 1, uniffiArgs, returnValue, aError); + } +}; + +extern "C" void callback_interface_errorsupport_application_error_reporter_report_breadcrumb( + uint64_t aUniffiHandle, + RustBuffer aMessage, + RustBuffer aModule, + uint32_t aLine, + uint32_t aColumn, + void* aUniffiOutReturn, + RustCallStatus* uniffiOutStatus +) { + UniquePtr handler = MakeUnique(aUniffiHandle, aMessage, aModule, aLine, aColumn); + // Note: currently we only support queueing fire-and-forget async callbacks + + // For fire-and-forget callbacks, we don't know if the method succeeds or not + // since it's called later. uniffiCallStatus is initialized to a successful + // state by the Rust code, so there's no need to modify it. + UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gUniffiCallbackHandlerApplicationErrorReporter); +} + +extern "C" void callback_free_errorsupport_application_error_reporter(uint64_t uniffiHandle) { + // Callback object handles are keys in a map stored in the JS handler. To + // handle the free call, make a call into JS which will remove the key. + // Fire-and-forget is perfect for this. + UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("ApplicationErrorReporter", uniffiHandle), &gUniffiCallbackHandlerApplicationErrorReporter); +} + +static VTableCallbackInterfaceApplicationErrorReporter kUniffiVtableApplicationErrorReporter { + callback_interface_errorsupport_application_error_reporter_report_error, + callback_interface_errorsupport_application_error_reporter_report_breadcrumb, + callback_free_errorsupport_application_error_reporter +}; + +#ifdef MOZ_UNIFFI_FIXTURES +static StaticRefPtr gUniffiCallbackHandlerTestCallbackInterface; + +class CallbackInterfaceMethodUniffiBindingsTestsTestCallbackInterfaceGetValue : public UniffiCallbackMethodHandlerBase { +private: + // Rust arguments + +public: + CallbackInterfaceMethodUniffiBindingsTestsTestCallbackInterfaceGetValue(uint64_t aUniffiHandle) + : UniffiCallbackMethodHandlerBase("TestCallbackInterface", aUniffiHandle) { + } + + MOZ_CAN_RUN_SCRIPT + void MakeCall(JSContext* aCx, dom::UniFFICallbackHandler* aJsHandler, ErrorResult& aError) override { + nsTArray uniffiArgs; + + // Setup + if (!uniffiArgs.AppendElements(1, mozilla::fallible)) { + aError.Throw(NS_ERROR_OUT_OF_MEMORY); + return; + } + + // Convert each argument + mUniffiHandle.Lift( + aCx, + &uniffiArgs[0], + aError); + if (aError.Failed()) { + return; + } + + // Stores the return value. For now, we currently don't do anything with it, since we only support + // fire-and-forget callbacks. + NullableRootedUnion returnValue(aCx); + // Make the call + aJsHandler->Call(mUniffiHandle.IntoRust(), 0, uniffiArgs, returnValue, aError); + } +}; + +extern "C" void callback_interface_uniffi_bindings_tests_test_callback_interface_get_value( + uint64_t aUniffiHandle, + uint32_t* aUniffiOutReturn, + RustCallStatus* uniffiOutStatus +) { + UniquePtr handler = MakeUnique(aUniffiHandle); + // Note: currently we only support queueing fire-and-forget async callbacks + + // For fire-and-forget callbacks, we don't know if the method succeeds or not + // since it's called later. uniffiCallStatus is initialized to a successful + // state by the Rust code, so there's no need to modify it. + UniffiCallbackMethodHandlerBase::FireAndForget(std::move(handler), &gUniffiCallbackHandlerTestCallbackInterface); +} + +extern "C" void callback_free_uniffi_bindings_tests_test_callback_interface(uint64_t uniffiHandle) { + // Callback object handles are keys in a map stored in the JS handler. To + // handle the free call, make a call into JS which will remove the key. + // Fire-and-forget is perfect for this. + UniffiCallbackMethodHandlerBase::FireAndForget(MakeUnique("TestCallbackInterface", uniffiHandle), &gUniffiCallbackHandlerTestCallbackInterface); +} + +static VTableCallbackInterfaceTestCallbackInterface kUniffiVtableTestCallbackInterface { + callback_interface_uniffi_bindings_tests_test_callback_interface_get_value, + callback_free_uniffi_bindings_tests_test_callback_interface +}; +#endif /* MOZ_UNIFFI_FIXTURES */ + +void RegisterCallbackHandler(uint64_t aInterfaceId, UniFFICallbackHandler& aCallbackHandler, ErrorResult& aError) { + switch (aInterfaceId) { + case 1: { - type = &kRelevancyRelevancyStorePointerType; + if (gUniffiCallbackHandlerContextIdCallback) { + aError.ThrowUnknownError("[UniFFI] Callback handler already registered for ContextIdCallback"_ns); + return; + } + + gUniffiCallbackHandlerContextIdCallback = &aCallbackHandler; + uniffi_context_id_fn_init_callback_vtable_contextidcallback(&kUniffiVtableContextIdCallback); break; } case 2: { - type = &kRemoteSettingsRemoteSettingsPointerType; - break; - } - case 3: { - type = &kRemoteSettingsRemoteSettingsClientPointerType; - break; - } - case 4: { - type = &kRemoteSettingsRemoteSettingsServicePointerType; - break; - } - case 5: { - type = &kSearchSearchEngineSelectorPointerType; - break; - } - case 6: { - type = &kSuggestSuggestStorePointerType; - break; - } - case 7: { - type = &kSuggestSuggestStoreBuilderPointerType; - break; - } - case 8: { - type = &kTabsRemoteCommandStorePointerType; - break; - } - case 9: { - type = &kTabsTabsBridgedEnginePointerType; - break; - } - case 10: { - type = &kTabsTabsStorePointerType; - break; - } - case 11: { - type = &kWebextstorageWebExtStorageBridgedEnginePointerType; - break; - } - case 12: { - type = &kWebextstorageWebExtStorageStorePointerType; - break; - } + if (gUniffiCallbackHandlerApplicationErrorReporter) { + aError.ThrowUnknownError("[UniFFI] Callback handler already registered for ApplicationErrorReporter"_ns); + return; + } -#ifdef MOZ_UNIFFI_FIXTURES - case 13: { - type = &kFuturesFutureTesterPointerType; + gUniffiCallbackHandlerApplicationErrorReporter = &aCallbackHandler; + uniffi_error_support_fn_init_callback_vtable_applicationerrorreporter(&kUniffiVtableApplicationErrorReporter); break; } - case 14: { - type = &kFuturesRustTaskPointerType; + + #ifdef MOZ_UNIFFI_FIXTURES + case 3: { + if (gUniffiCallbackHandlerTestCallbackInterface) { + aError.ThrowUnknownError("[UniFFI] Callback handler already registered for TestCallbackInterface"_ns); + return; + } + + gUniffiCallbackHandlerTestCallbackInterface = &aCallbackHandler; + uniffi_uniffi_bindings_tests_fn_init_callback_vtable_testcallbackinterface(&kUniffiVtableTestCallbackInterface); break; } - case 15: { - type = &kFuturesTravellerPointerType; - break; - } - case 16: { - type = &kFuturesWorkerQueuePointerType; - break; - } - case 17: { - type = &kRefcountsSingletonObjectPointerType; - break; - } - case 18: { - type = &kRondpointOptionneurPointerType; - break; - } - case 19: { - type = &kRondpointRetourneurPointerType; - break; - } - case 20: { - type = &kRondpointStringifierPointerType; - break; - } - case 21: { - type = &kSpritesSpritePointerType; - break; - } - case 22: { - type = &kTodolistTodoListPointerType; - break; - } - case 23: { - type = &kUniffiTraitInterfacesCalcPointerType; - break; - } -#endif /* MOZ_UNIFFI_FIXTURES */ + #endif /* MOZ_UNIFFI_FIXTURES */ + default: - return false; + aError.ThrowUnknownError(nsPrintfCString("RegisterCallbackHandler: Unknown callback interface id (%" PRIu64 ")", aInterfaceId)); + return; + } +} + +void DeregisterCallbackHandler(uint64_t aInterfaceId, ErrorResult& aError) { + switch (aInterfaceId) { + + case 1: { + if (!gUniffiCallbackHandlerContextIdCallback) { + aError.ThrowUnknownError("[UniFFI] Callback handler not registered for ContextIdCallback"_ns); + return; + } + + gUniffiCallbackHandlerContextIdCallback = nullptr; + break; + } + case 2: { + if (!gUniffiCallbackHandlerApplicationErrorReporter) { + aError.ThrowUnknownError("[UniFFI] Callback handler not registered for ApplicationErrorReporter"_ns); + return; + } + + gUniffiCallbackHandlerApplicationErrorReporter = nullptr; + break; + } + + #ifdef MOZ_UNIFFI_FIXTURES + case 3: { + if (!gUniffiCallbackHandlerTestCallbackInterface) { + aError.ThrowUnknownError("[UniFFI] Callback handler not registered for TestCallbackInterface"_ns); + return; + } + + gUniffiCallbackHandlerTestCallbackInterface = nullptr; + break; + } + #endif /* MOZ_UNIFFI_FIXTURES */ + + default: + aError.ThrowUnknownError(nsPrintfCString("DeregisterCallbackHandler: Unknown callback interface id (%" PRIu64 ")", aInterfaceId)); + return; } - aPtr.Write(aArrayBuff, aPosition, type, aError); - return true; } } // namespace mozilla::uniffi diff --git a/toolkit/components/uniffi-js/moz.build b/toolkit/components/uniffi-js/moz.build index 8334b1d63db2..ec1c0974fa1c 100644 --- a/toolkit/components/uniffi-js/moz.build +++ b/toolkit/components/uniffi-js/moz.build @@ -34,6 +34,6 @@ EXPORTS.mozilla.uniffi += [ "Rust.h", ] -EXTRA_JS_MODULES += [ +MOZ_SRC_FILES += [ "js/UniFFI.sys.mjs", ] diff --git a/toolkit/library/rust/shared/Cargo.toml b/toolkit/library/rust/shared/Cargo.toml index fb81bf1d2f35..9edf16fa8c6b 100644 --- a/toolkit/library/rust/shared/Cargo.toml +++ b/toolkit/library/rust/shared/Cargo.toml @@ -117,7 +117,7 @@ osclientcerts = { path = "../../../../security/manager/ssl/osclientcerts" } [target.'cfg(not(target_os = "android"))'.dependencies] gkrust-uniffi-components = { path = "../../../components/uniffi-bindgen-gecko-js/components/", features = ["xpcom"] } -gkrust-uniffi-fixtures = { path = "../../../components/uniffi-bindgen-gecko-js/fixtures/", features = ["xpcom"], optional = true } +uniffi-bindgen-gecko-js-test-fixtures = { path = "../../../components/uniffi-bindgen-gecko-js/test-fixtures/", optional = true } viaduct = "0.1" webext-storage = "0.1" @@ -145,7 +145,7 @@ oxidized_breakpad = ["rust_minidump_writer_linux"] crashreporter = ["crash_helper_client", "mozannotation_client"] with_dbus = ["audio_thread_priority/with_dbus"] thread_sanitizer = ["xpcom/thread_sanitizer"] -uniffi_fixtures = ["gkrust-uniffi-fixtures"] +uniffi_fixtures = ["uniffi-bindgen-gecko-js-test-fixtures"] webmidi_midir_impl = ["midir_impl"] icu4x = ["jsrust_shared/icu4x"] diff --git a/toolkit/library/rust/shared/lib.rs b/toolkit/library/rust/shared/lib.rs index 0034fc82e01b..e80408d932c7 100644 --- a/toolkit/library/rust/shared/lib.rs +++ b/toolkit/library/rust/shared/lib.rs @@ -100,7 +100,7 @@ extern crate osclientcerts; extern crate gkrust_uniffi_components; #[cfg(feature = "uniffi_fixtures")] -extern crate gkrust_uniffi_fixtures; +extern crate uniffi_bindgen_gecko_js_test_fixtures; #[cfg(not(target_os = "android"))] extern crate viaduct; diff --git a/tools/@types/generated/tspaths.json b/tools/@types/generated/tspaths.json index 82129581a25e..512d3ce13d89 100644 --- a/tools/@types/generated/tspaths.json +++ b/tools/@types/generated/tspaths.json @@ -6392,9 +6392,6 @@ "resource://gre/modules/Troubleshoot.sys.mjs": [ "toolkit/modules/Troubleshoot.sys.mjs" ], - "resource://gre/modules/UniFFI.sys.mjs": [ - "toolkit/components/uniffi-js/js/UniFFI.sys.mjs" - ], "resource://gre/modules/UninstallPing.sys.mjs": [ "toolkit/components/telemetry/pings/UninstallPing.sys.mjs" ], diff --git a/tools/lint/trojan-source.yml b/tools/lint/trojan-source.yml index fdcca4d6065b..523a839f90af 100644 --- a/tools/lint/trojan-source.yml +++ b/tools/lint/trojan-source.yml @@ -28,7 +28,6 @@ trojan-source: - security/nss/gtests/mozpkix_gtest/pkixnames_tests.cpp - testing/web-platform/tests/webdriver/tests/bidi/input/perform_actions/key_tentative.py - testing/web-platform/tests/webdriver/tests/classic/perform_actions/key_tentative.py - - toolkit/components/uniffi-bindgen-gecko-js/fixtures/rondpoint/tests/bindings/test_rondpoint.py extensions: - .c - .cc diff --git a/tools/rewriting/Generated.txt b/tools/rewriting/Generated.txt index e8c299807205..c1e647445ccb 100644 --- a/tools/rewriting/Generated.txt +++ b/tools/rewriting/Generated.txt @@ -219,7 +219,7 @@ toolkit/components/nimbus/schemas/NimbusExperiment.schema.json toolkit/components/pdfjs/PdfJsDefaultPrefs.js toolkit/components/pdfjs/PdfJsOverridePrefs.js toolkit/components/uniffi-js/GeneratedScaffolding.cpp -toolkit/components/uniffi-bindgen-gecko-js/fixtures/generated +toolkit/components/uniffi-bindgen-gecko-js/tests/generated tools/@types/generated/ tools/@types/subs/ tools/browsertime/package.json