1use std::{collections::BTreeMap, fmt};
8
9const TAG_NIL: u8 = 0;
10const TAG_FALSE: u8 = 1;
11const TAG_TRUE: u8 = 2;
12const TAG_INT: u8 = 3;
13const TAG_FLOAT: u8 = 4;
14const TAG_STRING: u8 = 5;
15const TAG_BYTES: u8 = 6;
16const TAG_ARRAY: u8 = 7;
17const TAG_MAP: u8 = 8;
18const TAG_USERDATA: u8 = 9;
19const MAX_DEPTH: usize = 64;
20
21#[derive(Clone, Copy, Debug, PartialEq)]
23pub enum Number {
24 Int(i64),
25 Float(f64),
26}
27
28impl Number {
29 pub fn as_i64(self) -> i64 {
31 match self {
32 Number::Int(i) => i,
33 Number::Float(f) => f as i64,
34 }
35 }
36
37 pub fn as_i32(self) -> i32 {
38 self.as_i64().clamp(i32::MIN as i64, i32::MAX as i64) as i32
39 }
40
41 pub fn as_u32(self) -> u32 {
42 self.as_i64().clamp(0, u32::MAX as i64) as u32
43 }
44
45 pub fn as_f64(self) -> f64 {
46 match self {
47 Number::Int(i) => i as f64,
48 Number::Float(f) => f,
49 }
50 }
51}
52
53macro_rules! number_from_int {
54 ($($t:ty),*) => {$(
55 impl From<$t> for Number {
56 fn from(v: $t) -> Self { Number::Int(v as i64) }
57 }
58 )*};
59}
60number_from_int!(i8, i16, i32, i64, u8, u16, u32, usize, isize);
61
62impl From<f64> for Number {
63 fn from(v: f64) -> Self {
64 Number::Float(v)
65 }
66}
67
68impl fmt::Display for Number {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 match self {
71 Number::Int(i) => i.fmt(f),
72 Number::Float(x) => x.fmt(f),
73 }
74 }
75}
76
77#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
80pub struct OcString(pub Vec<u8>);
81
82impl OcString {
83 pub fn as_bytes(&self) -> &[u8] {
84 &self.0
85 }
86
87 pub fn into_bytes(self) -> Vec<u8> {
88 self.0
89 }
90
91 pub fn as_str(&self) -> Option<&str> {
92 std::str::from_utf8(&self.0).ok()
93 }
94
95 pub fn to_string_lossy(&self) -> String {
97 String::from_utf8_lossy(&self.0).into_owned()
98 }
99}
100
101impl std::ops::Deref for OcString {
102 type Target = [u8];
103 fn deref(&self) -> &[u8] {
104 &self.0
105 }
106}
107
108impl fmt::Display for OcString {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 f.write_str(&String::from_utf8_lossy(&self.0))
111 }
112}
113
114impl fmt::Debug for OcString {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 match self.as_str() {
117 Some(s) => s.fmt(f),
118 None => write!(f, "b{:?}", self.0),
119 }
120 }
121}
122
123impl PartialEq<str> for OcString {
124 fn eq(&self, other: &str) -> bool {
125 self.0 == other.as_bytes()
126 }
127}
128
129impl PartialEq<&str> for OcString {
130 fn eq(&self, other: &&str) -> bool {
131 self.0 == other.as_bytes()
132 }
133}
134
135impl From<OcString> for String {
136 fn from(s: OcString) -> Self {
137 String::from_utf8(s.0).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
138 }
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
144pub struct Handle(pub u32);
145
146#[derive(Clone, Debug, PartialEq, Default)]
148pub enum Value {
149 #[default]
150 Nil,
151 Bool(bool),
152 Number(Number),
153 String(OcString),
154 Array(Vec<Value>),
155 Map(Vec<(Value, Value)>),
157 Handle(Handle),
158}
159
160impl Value {
161 pub fn text(bytes: &[u8]) -> Value {
163 Value::String(OcString(bytes.to_vec()))
164 }
165
166 pub fn is_nil(&self) -> bool {
167 matches!(self, Value::Nil)
168 }
169
170 pub fn as_bool(&self) -> Option<bool> {
171 match self {
172 Value::Bool(b) => Some(*b),
173 _ => None,
174 }
175 }
176
177 pub fn as_number(&self) -> Option<Number> {
178 match self {
179 Value::Number(n) => Some(*n),
180 _ => None,
181 }
182 }
183
184 pub fn as_i64(&self) -> Option<i64> {
185 self.as_number().map(Number::as_i64)
186 }
187
188 pub fn as_str(&self) -> Option<&str> {
189 match self {
190 Value::String(s) => s.as_str(),
191 _ => None,
192 }
193 }
194
195 pub fn as_bytes(&self) -> Option<&[u8]> {
196 match self {
197 Value::String(s) => Some(s),
198 _ => None,
199 }
200 }
201
202 pub fn as_handle(&self) -> Option<Handle> {
203 match self {
204 Value::Handle(h) => Some(*h),
205 _ => None,
206 }
207 }
208
209 pub fn as_array(&self) -> Option<Vec<&Value>> {
212 match self {
213 Value::Array(items) => Some(items.iter().collect()),
214 Value::Map(entries) => {
215 let mut indexed: Vec<(i64, &Value)> =
216 entries.iter().filter_map(|(k, v)| Some((k.as_i64()?, v))).collect();
217 if indexed.len() != entries.len() {
218 return None;
219 }
220 indexed.sort_by_key(|(k, _)| *k);
221 Some(indexed.into_iter().map(|(_, v)| v).collect())
222 }
223 _ => None,
224 }
225 }
226
227 pub fn as_map(&self) -> Option<&[(Value, Value)]> {
228 match self {
229 Value::Map(entries) => Some(entries),
230 _ => None,
231 }
232 }
233
234 pub fn get(&self, key: &str) -> Option<&Value> {
236 self.as_map()?.iter().find(|(k, _)| k.as_str() == Some(key)).map(|(_, v)| v)
237 }
238
239 pub fn to_string_map(&self) -> BTreeMap<String, Value> {
241 self.as_map()
242 .unwrap_or_default()
243 .iter()
244 .filter_map(|(k, v)| Some((k.as_str()?.to_owned(), v.clone())))
245 .collect()
246 }
247
248 pub fn encode(&self) -> Vec<u8> {
249 let mut out = Vec::new();
250 self.encode_into(&mut out);
251 out
252 }
253
254 fn encode_into(&self, out: &mut Vec<u8>) {
255 fn len(out: &mut Vec<u8>, n: usize) {
256 out.extend_from_slice(&(n as u32).to_le_bytes());
257 }
258 match self {
259 Value::Nil => out.push(TAG_NIL),
260 Value::Bool(false) => out.push(TAG_FALSE),
261 Value::Bool(true) => out.push(TAG_TRUE),
262 Value::Number(Number::Int(i)) => {
263 out.push(TAG_INT);
264 out.extend_from_slice(&i.to_le_bytes());
265 }
266 Value::Number(Number::Float(f)) => {
267 out.push(TAG_FLOAT);
268 out.extend_from_slice(&f.to_bits().to_le_bytes());
269 }
270 Value::String(s) => {
271 out.push(if s.as_str().is_some() { TAG_STRING } else { TAG_BYTES });
272 len(out, s.len());
273 out.extend_from_slice(s);
274 }
275 Value::Array(items) => {
276 out.push(TAG_ARRAY);
277 len(out, items.len());
278 items.iter().for_each(|v| v.encode_into(out));
279 }
280 Value::Map(entries) => {
281 out.push(TAG_MAP);
282 len(out, entries.len());
283 for (k, v) in entries {
284 k.encode_into(out);
285 v.encode_into(out);
286 }
287 }
288 Value::Handle(Handle(id)) => {
289 out.push(TAG_USERDATA);
290 out.extend_from_slice(&id.to_le_bytes());
291 }
292 }
293 }
294
295 pub fn decode(bytes: &[u8]) -> Option<Value> {
297 let mut r = Reader { bytes, pos: 0 };
298 let v = r.value(0)?;
299 (r.pos == bytes.len()).then_some(v)
300 }
301}
302
303struct Reader<'a> {
304 bytes: &'a [u8],
305 pos: usize,
306}
307
308impl Reader<'_> {
309 fn take(&mut self, n: usize) -> Option<&[u8]> {
310 let end = self.pos.checked_add(n)?;
311 let s = self.bytes.get(self.pos..end)?;
312 self.pos = end;
313 Some(s)
314 }
315
316 fn u32(&mut self) -> Option<u32> {
317 Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
318 }
319
320 fn u64(&mut self) -> Option<u64> {
321 Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?))
322 }
323
324 fn count(&mut self, min_each: usize) -> Option<usize> {
325 let n = self.u32()? as usize;
326 (n.saturating_mul(min_each) <= self.bytes.len() - self.pos).then_some(n)
327 }
328
329 fn value(&mut self, depth: usize) -> Option<Value> {
330 if depth > MAX_DEPTH {
331 return None;
332 }
333 Some(match *self.take(1)?.first()? {
334 TAG_NIL => Value::Nil,
335 TAG_FALSE => Value::Bool(false),
336 TAG_TRUE => Value::Bool(true),
337 TAG_INT => Value::Number(Number::Int(self.u64()? as i64)),
338 TAG_FLOAT => Value::Number(Number::Float(f64::from_bits(self.u64()?))),
339 TAG_STRING | TAG_BYTES => {
340 let n = self.u32()? as usize;
341 Value::String(OcString(self.take(n)?.to_vec()))
342 }
343 TAG_ARRAY => {
344 let n = self.count(1)?;
345 Value::Array((0..n).map(|_| self.value(depth + 1)).collect::<Option<_>>()?)
346 }
347 TAG_MAP => {
348 let n = self.count(2)?;
349 Value::Map((0..n).map(|_| Some((self.value(depth + 1)?, self.value(depth + 1)?))).collect::<Option<_>>()?)
350 }
351 TAG_USERDATA => Value::Handle(Handle(self.u32()?)),
352 _ => return None,
353 })
354 }
355}
356
357impl From<bool> for Value {
360 fn from(v: bool) -> Self {
361 Value::Bool(v)
362 }
363}
364impl<T: Into<Number>> From<T> for Value {
365 fn from(v: T) -> Self {
366 Value::Number(v.into())
367 }
368}
369impl From<&str> for Value {
370 fn from(v: &str) -> Self {
371 Value::text(v.as_bytes())
372 }
373}
374impl From<String> for Value {
375 fn from(v: String) -> Self {
376 Value::String(OcString(v.into_bytes()))
377 }
378}
379impl From<&[u8]> for Value {
380 fn from(v: &[u8]) -> Self {
381 Value::text(v)
382 }
383}
384impl From<OcString> for Value {
385 fn from(v: OcString) -> Self {
386 Value::String(v)
387 }
388}
389impl From<Handle> for Value {
390 fn from(v: Handle) -> Self {
391 Value::Handle(v)
392 }
393}
394impl From<&Handle> for Value {
395 fn from(v: &Handle) -> Self {
396 Value::Handle(*v)
397 }
398}
399impl<T: Into<Value>> From<Option<T>> for Value {
400 fn from(v: Option<T>) -> Self {
401 v.map_or(Value::Nil, Into::into)
402 }
403}
404impl<T: Into<Value>> From<Vec<T>> for Value {
405 fn from(v: Vec<T>) -> Self {
406 Value::Array(v.into_iter().map(Into::into).collect())
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 #[test]
415 fn matches_the_shared_vector() {
416 let vector: &[u8] = &[7, 5, 0, 0, 0, 0, 2, 3, 7, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, b'h', b'i', 9, 1, 0, 0, 0];
418 let value = Value::Array(vec![Value::Nil, true.into(), 7.into(), "hi".into(), Value::Handle(Handle(1))]);
419 assert_eq!(value.encode(), vector);
420 assert_eq!(Value::decode(vector), Some(value));
421 }
422
423 #[test]
424 fn binary_strings_round_trip_as_bytes() {
425 let v = Value::text(&[0xff, 0x00]);
426 assert_eq!(v.encode()[0], TAG_BYTES);
427 assert_eq!(Value::decode(&v.encode()), Some(v));
428 }
429
430 #[test]
431 fn sequences_sent_as_maps() {
432 let m = Value::Map(vec![(2.into(), "b".into()), (1.into(), "a".into())]);
433 let items: Vec<_> = m.as_array().unwrap().into_iter().map(|v| v.as_str().unwrap()).collect();
434 assert_eq!(items, ["a", "b"]);
435 }
436
437 #[test]
438 fn rejects_malformed() {
439 assert_eq!(Value::decode(&[]), None);
440 assert_eq!(Value::decode(&[TAG_INT, 1]), None);
441 assert_eq!(Value::decode(&[TAG_ARRAY, 255, 255, 255, 127]), None);
442 }
443}