Skip to content

Improve and document the behaviours of {json,yaml,cbor,toml}.encode #6738

@YDX-2147483647

Description

@YDX-2147483647

Description

In typst 0.13.1, 1.13457pt is strictly longer than 1.13pt.
However, {json,yaml,cbor}.encode implicitly convert 1.13457pt to "1.13pt", and toml.encode refuses to accept 1.13457pt.

These behaviors should be unified and documented.

#set raw(lang: "typc")
#assert(1.13457pt > 1.13pt)

= JSON, YAML, and CBOR think `1.13457pt == "1.13pt"`

#assert.eq(
  json.encode(1.13457pt),
  `"1.13pt"`.text,
)
#assert.eq(
  yaml.encode(1.13457pt),
  "1.13pt\n",
)
#assert.eq(
  cbor(cbor.encode(1.13457pt)),
  "1.13pt",
)

= TOML refuses to encode `1.13457pt`
#toml.encode(1.13457pt)

```log
Failed to encode value as TOML (unsupported rust type)
```
Implementation details

/// Encodes structured data into a JSON string.
#[func(title = "Encode JSON")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
/// Whether to pretty print the JSON with newlines and indentation.
#[named]
#[default(true)]
pretty: bool,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
if pretty {
serde_json::to_string_pretty(&value)
} else {
serde_json::to_string(&value)
}
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as JSON ({err})"))
.at(span)
}

/// Encode structured data into a YAML string.
#[func(title = "Encode YAML")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
serde_yaml::to_string(&value)
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as YAML ({err})"))
.at(span)
}

/// Encode structured data into CBOR bytes.
#[func(title = "Encode CBOR")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
) -> SourceResult<Bytes> {
let Spanned { v: value, span } = value;
let mut res = Vec::new();
ciborium::into_writer(&value, &mut res)
.map(|_| Bytes::new(res))
.map_err(|err| eco_format!("failed to encode value as CBOR ({err})"))
.at(span)
}

/// Encodes structured data into a TOML string.
#[func(title = "Encode TOML")]
pub fn encode(
/// Value to be encoded.
value: Spanned<Value>,
/// Whether to pretty-print the resulting TOML.
#[named]
#[default(true)]
pretty: bool,
) -> SourceResult<Str> {
let Spanned { v: value, span } = value;
if pretty { ::toml::to_string_pretty(&value) } else { ::toml::to_string(&value) }
.map(|v| v.into())
.map_err(|err| eco_format!("failed to encode value as TOML ({err})"))
.at(span)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingneeds-investigationMore investigation is necessary.scriptingAbout Typst's coding capabilities

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions