Skip to main content

ephemeris_documents/json/cst/
scalar.rs

1//! Literal tokens of the JSON syntax tree.
2
3use super::quote::Quote;
4use crate::annotation::StringStyle;
5use crate::json::Dialect;
6use crate::scalar::Scalar as Leaf;
7
8/// A literal token: the source text of a string, number, or keyword.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub(crate) struct Scalar {
11    text: String,
12    /// The byte offset of the token in the parsed source, zero for a built
13    /// scalar.
14    offset: usize,
15}
16
17impl Scalar {
18    /// Wrap the source text of one literal token that starts at `offset`.
19    pub(in crate::json) const fn from_source(text: String, offset: usize) -> Self {
20        Self { text, offset }
21    }
22
23    pub(in crate::json) const fn offset(&self) -> usize {
24        self.offset
25    }
26
27    pub(in crate::json) fn text(&self) -> &str {
28        &self.text
29    }
30
31    pub(super) fn build(leaf: &Leaf, dialect: Dialect) -> Self {
32        let text = match leaf {
33            Leaf::Null => "null".to_owned(),
34            Leaf::Bool(value) => value.to_string(),
35            Leaf::Integer(value) => value.to_string(),
36            Leaf::Unsigned(value) => value.to_string(),
37            Leaf::Float(value) => value.to_string(),
38            Leaf::String { text, style } => match (dialect, style) {
39                (Dialect::Json5, StringStyle::Literal) => Quote::Single.wrap(text),
40                _ => Quote::Double.wrap(text),
41            },
42        };
43        Self { text, offset: 0 }
44    }
45}