wit_component_update/encoding/wit/mod.rs
1use anyhow::Result;
2use wasm_encoder::{ComponentBuilder, ComponentType};
3use wit_parser::{PackageId, Resolve, WorldId};
4
5mod v1;
6mod v2;
7
8const ENCODE_V2_BY_DEFAULT: bool = true;
9
10fn use_v2_encoding() -> bool {
11 match std::env::var("WIT_COMPONENT_ENCODING_V2") {
12 Ok(s) => s == "1",
13 Err(_) => ENCODE_V2_BY_DEFAULT,
14 }
15}
16
17/// Encodes the given `package` within `resolve` to a binary WebAssembly
18/// representation.
19///
20/// This function is the root of the implementation of serializing a WIT package
21/// into a WebAssembly representation. The wasm representation serves two
22/// purposes:
23///
24/// * One is to be a binary encoding of a WIT document which is ideally more
25/// stable than the WIT textual format itself.
26/// * Another is to provide a clear mapping of all WIT features into the
27/// component model through use of its binary representation.
28///
29/// The `resolve` provided is a set of packages and types and such and the
30/// `package` argument is an ID within the world provided. The documents within
31/// `package` will all be encoded into the binary returned.
32///
33/// The binary returned can be [`decode`d](crate::decode) to recover the WIT
34/// package provided.
35pub fn encode(use_v2: Option<bool>, resolve: &Resolve, package: PackageId) -> Result<Vec<u8>> {
36 let mut component = encode_component(use_v2, resolve, package)?;
37 component.raw_custom_section(&crate::base_producers().raw_custom_section());
38 Ok(component.finish())
39}
40
41/// Exactly like `encode`, except gives an unfinished `ComponentBuilder` in case you need
42/// to append anything else before finishing.
43pub fn encode_component(
44 use_v2: Option<bool>,
45 resolve: &Resolve,
46 package: PackageId,
47) -> Result<ComponentBuilder> {
48 if use_v2.unwrap_or_else(use_v2_encoding) {
49 v2::encode_component(resolve, package)
50 } else {
51 v1::encode_component(resolve, package)
52 }
53}
54
55/// Encodes a `world` as a component type.
56pub fn encode_world(resolve: &Resolve, world_id: WorldId) -> Result<ComponentType> {
57 v1::encode_world(resolve, world_id)
58}