Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_jdat/src/string/js.rs

7.2 KiB, 12 runs

created by r1870400018:67305, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A jdat file read for a browser (U0, D-20261005-12). The settings file of an app is jdat, with
2//! its comments, and a browser has `JSON.parse` and no jdat reader, so the Rust decoder, the one
3//! parser, is compiled to wasm and exports `jdat_to_json`.
4
5use crate::{
6 prelude::*,
7 bdat::limits::DecodeLimits,
8 string::{
9 dec::DecoderConfig,
10 enc::escape_json_string,
11 },
12 usr::{
13 UsrKind,
14 UsrKindCode,
15 UsrKindId,
16 },
17};
18
19use oxedyne_fe2o3_core::prelude::*;
20use oxedyne_fe2o3_num::float::Float64;
21
22use std::collections::BTreeMap;
23
24
25// The largest whole number a browser's `Number` holds exactly, 2^53 - 1.
26const JS_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
27
28impl Dat {
29
30 /// Reads jdat text with `decode_string`'s rules and writes it as plain JSON, members in the
31 /// order written and every comment dropped, for a browser's `JSON.parse`.
32 ///
33 /// A comment is a note on a value to the decoder (a `Dat::ABox`), and a note standing alone is
34 /// an entry with an empty key and value; both go. With `js_safe`, a whole number past 2^53 - 1
35 /// in size and a float that is not finite are refused too, since `JSON.parse` would round them
36 /// silently. A refusal by the decoder names the line and column, as `[1,,2]` does. One found
37 /// here, after the text is read, names the position in the data, such as `{0}[2]{3}`, the
38 /// fourth member of the third item of the first member, and a refusal holds no key and no
39 /// value, since either may be personal data.
40 pub fn jdat_to_json(
41 s: &str,
42 limits: &DecodeLimits,
43 js_safe: bool,
44 )
45 -> Outcome<String>
46 {
47 let mut cfg = DecoderConfig::<
48 BTreeMap<UsrKindCode, UsrKind>,
49 BTreeMap<String, UsrKindId>,
50 >::default().with_limits(*limits);
51 cfg.use_ordmaps = true;
52 let dat = res!(Self::decode_string_with_config(s, &cfg));
53 let mut out = String::with_capacity(s.len());
54 let mut path = Vec::new();
55 res!(write_json(&dat, js_safe, &mut path, &mut out));
56 Ok(out)
57 }
58}
59
60// The position of what is being written, outermost first: `[2]` the third item of a list, `{3}`
61// the fourth member of a map. It holds no key.
62fn at(path: &[String]) -> String {
63 path.concat()
64}
65
66// Where a refusal happened, in words: the position, or the top level when there is none.
67fn place(path: &[String]) -> String {
68 if path.is_empty() {
69 return fmt!("the top level");
70 }
71 fmt!("the position {}", at(path))
72}
73
74// The name of the `n`th member, counting from 0.
75fn key_text(key: &Dat, path: &[String], n: usize) -> Outcome<String> {
76 match key.bare() {
77 Dat::Str(s) => Ok(s.clone()),
78 Dat::Empty => Err(err!(
79 "A member has no name, in {}{}.", place(path),
80 if n == 0 { String::new() } else { fmt!(", after member {}", n - 1) };
81 Invalid, Input, Decode, Missing)),
82 other => Err(err!(
83 "A name must be a string in JSON, found a {:?} in {}.", other.kind(), place(path);
84 Invalid, Input, Decode)),
85 }
86}
87
88fn write_number(dat: &Dat, js_safe: bool, path: &[String], out: &mut String) -> Outcome<()> {
89 let integer = matches!(dat,
90 Dat::U8(_) | Dat::U16(_) | Dat::U32(_) | Dat::U64(_) | Dat::U128(_) |
91 Dat::I8(_) | Dat::I16(_) | Dat::I32(_) | Dat::I64(_) | Dat::I128(_) | Dat::Aint(_));
92 if integer {
93 match (dat.get_i64(), dat.get_u64()) {
94 (Some(n), _) => {
95 if js_safe && n.unsigned_abs() > JS_SAFE_INTEGER as u64 {
96 return Err(err!(
97 "The whole number at {} is past 2^53 - 1 in size, which a browser \
98 cannot hold exactly.", place(path); Invalid, Input, Decode, Excessive));
99 }
100 out.push_str(&fmt!("{}", n));
101 },
102 (None, Some(n)) if !js_safe => out.push_str(&fmt!("{}", n)),
103 _ => return Err(err!(
104 "The whole number at {} is past 2^53 - 1 in size, which a browser cannot \
105 hold exactly.", place(path); Invalid, Input, Decode, Excessive)),
106 }
107 return Ok(());
108 }
109 match dat.get_float64() {
110 Some(Float64(f)) if f.is_finite() => out.push_str(&fmt!("{}", f)),
111 _ => return Err(err!(
112 "The number at {} is not a finite float64, which JSON cannot hold.", place(path);
113 Invalid, Input, Decode, Excessive)),
114 }
115 Ok(())
116}
117
118fn write_members<'a, I: Iterator<Item = (&'a Dat, &'a Dat)>>(
119 members: I,
120 js_safe: bool,
121 path: &mut Vec<String>,
122 out: &mut String,
123)
124 -> Outcome<()>
125{
126 out.push('{');
127 let mut n = 0;
128 for (k, v) in members {
129 if Dat::is_note_entry(k, v) {
130 continue;
131 }
132 let key = res!(key_text(k, path, n));
133 if n > 0 {
134 out.push(',');
135 }
136 out.push('"');
137 out.push_str(&escape_json_string(&key));
138 out.push_str("\":");
139 path.push(fmt!("{{{}}}", n));
140 if matches!(v.bare(), Dat::Empty) {
141 return Err(err!(
142 "The member at {} has no value.", at(path); Invalid, Input, Decode, Missing));
143 }
144 res!(write_json(v, js_safe, path, out));
145 path.pop();
146 n += 1;
147 }
148 out.push('}');
149 Ok(())
150}
151
152// A daticle as plain JSON, members in the order held.
153fn write_json(dat: &Dat, js_safe: bool, path: &mut Vec<String>, out: &mut String) -> Outcome<()> {
154 match dat {
155 Dat::ABox(_, inner, _) => return write_json(inner, js_safe, path, out),
156 Dat::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
157 Dat::Opt(o) if o.is_none() => out.push_str("null"),
158 Dat::Str(s) => {
159 out.push('"');
160 out.push_str(&escape_json_string(s));
161 out.push('"');
162 },
163 Dat::U8(_) | Dat::U16(_) | Dat::U32(_) | Dat::U64(_) | Dat::U128(_) |
164 Dat::I8(_) | Dat::I16(_) | Dat::I32(_) | Dat::I64(_) | Dat::I128(_) |
165 Dat::F32(_) | Dat::F64(_) | Dat::Aint(_) | Dat::Adec(_) =>
166 res!(write_number(dat, js_safe, path, out)),
167 Dat::List(items) => {
168 out.push('[');
169 let mut n = 0;
170 for item in items {
171 if item.is_lone_note() {
172 continue; // A comment standing alone.
173 }
174 if matches!(item.bare(), Dat::Empty) {
175 return Err(err!(
176 "A list item is missing after item {} in {}.", n, place(path);
177 Invalid, Input, Decode, Missing));
178 }
179 if n > 0 {
180 out.push(',');
181 }
182 path.push(fmt!("[{}]", n));
183 res!(write_json(item, js_safe, path, out));
184 path.pop();
185 n += 1;
186 }
187 out.push(']');
188 },
189 Dat::OrdMap(m) => res!(write_members(m.iter().map(|(k, v)| (k.dat(), v)), js_safe, path, out)),
190 Dat::Map(m) => res!(write_members(m.iter(), js_safe, path, out)),
191 other => return Err(err!(
192 "A daticle of kind {:?} at {} has no plain JSON form.", other.kind(), place(path);
193 Invalid, Input, Unimplemented)),
194 }
195 Ok(())
196}