| 1 | use crate::encoding::read::{Error, Read}; |
| 2 | use crate::encoding::write::Write; |
| 3 | use std::cmp::PartialEq; |
| 4 | use std::collections::HashMap; |
| 5 | use std::convert::TryFrom; |
| 6 | use std::sync::Arc; |
| 7 | |
| 8 | pub const F64_MAX_SAFE_INTEGER: f64 = (i64::pow(2, 53) - 1) as f64; |
| 9 | pub const F64_MIN_SAFE_INTEGER: f64 = -F64_MAX_SAFE_INTEGER; |
| 10 | |
| 11 | /// Any is an enum with a potentially associated value that is used to represent JSON values |
| 12 | /// and supports efficient encoding of those values. |
| 13 | #[derive(Debug, Clone, PartialEq)] |
| 14 | pub enum Any { |
| 15 | Null, |
| 16 | Undefined, |
| 17 | Bool(bool), |
| 18 | Number(f64), |
| 19 | BigInt(i64), |
| 20 | String(Arc<str>), |
| 21 | Buffer(Arc<[u8]>), |
| 22 | Array(Arc<[Any]>), |
| 23 | Map(Arc<HashMap<String, Any>>), |
| 24 | } |
| 25 | |
| 26 | impl Any { |
| 27 | #[inline] |
| 28 | pub fn cast<T>(self) -> Result<T, Self> |
| 29 | where |
| 30 | T: TryFrom<Any, Error = Any>, |
| 31 | { |
| 32 | // we create dedicated cast, so that we can parametrize it in a fluent fashion |
| 33 | // ie. `any.cast::<u32>().unwrap_or_default()`. |
| 34 | T::try_from(self) |
| 35 | } |
| 36 | |
| 37 | pub fn decode<R: Read>(decoder: &mut R) -> Result<Self, Error> { |
| 38 | Ok(match decoder.read_u8()? { |
| 39 | // CASE 127: undefined |
| 40 | 127 => Any::Undefined, |
| 41 | // CASE 126: null |
| 42 | 126 => Any::Null, |
| 43 | // CASE 125: integer |
| 44 | 125 => Any::Number(decoder.read_var::<i64>()? as f64), |
| 45 | // CASE 124: float32 |
| 46 | 124 => Any::Number(decoder.read_f32()? as f64), |
| 47 | // CASE 123: float64 |
| 48 | 123 => Any::Number(decoder.read_f64()?), |
| 49 | // CASE 122: bigint |
| 50 | 122 => Any::BigInt(decoder.read_i64()?), |
| 51 | // CASE 121: boolean (false) |
| 52 | 121 => Any::Bool(false), |
| 53 | // CASE 120: boolean (true) |
| 54 | 120 => Any::Bool(true), |
| 55 | // CASE 119: string |
| 56 | 119 => { |
| 57 | let str = decoder.read_string()?; |
| 58 | Any::String(Arc::from(str)) |
| 59 | } |
| 60 | // CASE 118: Map<string,Any> |
| 61 | 118 => { |
| 62 | let len: usize = decoder.read_var()?; |
| 63 | let mut map = HashMap::with_capacity(len); |
| 64 | for _ in 0..len { |
| 65 | let key = decoder.read_string()?; |
| 66 | map.insert(key.to_owned(), Any::decode(decoder)?); |
| 67 | } |
| 68 | Any::Map(Arc::new(map)) |
| 69 | } |
| 70 | // CASE 117: Array<Any> |
| 71 | 117 => { |
| 72 | let len: usize = decoder.read_var()?; |
| 73 | let mut arr = Vec::with_capacity(len); |
| 74 | for _ in 0..len { |
| 75 | arr.push(Any::decode(decoder)?); |
| 76 | } |
| 77 | Any::Array(Arc::from(arr)) |
| 78 | } |
| 79 | // CASE 116: buffer |
| 80 | 116 => Any::Buffer(Arc::from(decoder.read_buf()?)), |
| 81 | _ => return Err(Error::UnexpectedValue), |
| 82 | }) |
| 83 | } |
| 84 | |
| 85 | // Encode data with efficient binary format. |
| 86 | // |
| 87 | // Differences to JSON: |
| 88 | // • Transforms data to a binary format (not to a string) |
| 89 | // • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON) |
| 90 | // • Numbers are efficiently encoded either as a variable length integer, as a |
| 91 | // 32 bit float, as a 64 bit float, or as a 64 bit bigint. |
| 92 | // |
| 93 | // Encoding table: |
| 94 | // |
| 95 | // | Data Type | Prefix | Encoding Method | Comment | |
| 96 | // | ------------------- | -------- | ------------------ | ------- | |
| 97 | // | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined | |
| 98 | // | null | 126 | | | |
| 99 | // | integer | 125 | writeVarInt | Only encodes 32 bit signed integers | |
| 100 | // | float32 | 124 | writeFloat32 | | |
| 101 | // | float64 | 123 | writeFloat64 | | |
| 102 | // | bigint | 122 | writeBigInt64 | | |
| 103 | // | boolean (false) | 121 | | True and false are different data types so we save the following byte | |
| 104 | // | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false | |
| 105 | // | string | 119 | writeVarString | | |
| 106 | // | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs | |
| 107 | // | array<any> | 117 | custom | Writes {length} then {length} json values | |
| 108 | // | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data | |
| 109 | // |
| 110 | // Reasons for the decreasing prefix: |
| 111 | // We need the first bit for extendability (later we may want to encode the |
| 112 | // prefix with writeVarUint). The remaining 7 bits are divided as follows: |
| 113 | // [0-30] the beginning of the data range is used for custom purposes |
| 114 | // (defined by the function that uses this library) |
| 115 | // [31-127] the end of the data range is used for data encoding by |
| 116 | // lib0/encoding.js |
| 117 | pub fn encode<W: Write>(&self, encoder: &mut W) { |
| 118 | match self { |
| 119 | Any::Undefined => { |
| 120 | // TYPE 127: undefined |
| 121 | encoder.write_u8(127) |
| 122 | } |
| 123 | Any::Null => { |
| 124 | // TYPE 126: null |
| 125 | encoder.write_u8(126) |
| 126 | } |
| 127 | Any::Bool(bool) => { |
| 128 | // TYPE 120/121: boolean (true/false) |
| 129 | encoder.write_u8(if *bool { 120 } else { 121 }) |
| 130 | } |
| 131 | Any::String(str) => { |
| 132 | // TYPE 119: String |
| 133 | encoder.write_u8(119); |
| 134 | encoder.write_string(&str) |
| 135 | } |
| 136 | Any::Number(num) => { |
| 137 | let num_truncated = num.trunc(); |
| 138 | if num_truncated == *num |
| 139 | && num_truncated <= F64_MAX_SAFE_INTEGER |
| 140 | && num_truncated >= F64_MIN_SAFE_INTEGER |
| 141 | { |
| 142 | // TYPE 125: INTEGER |
| 143 | encoder.write_u8(125); |
| 144 | encoder.write_var(num_truncated as i64) |
| 145 | } else if ((*num as f32) as f64) == *num { |
| 146 | // TYPE 124: FLOAT32 |
| 147 | encoder.write_u8(124); |
| 148 | encoder.write_f32(*num as f32) |
| 149 | } else { |
| 150 | // TYPE 123: FLOAT64 |
| 151 | encoder.write_u8(123); |
| 152 | encoder.write_f64(*num) |
| 153 | } |
| 154 | } |
| 155 | Any::BigInt(num) => { |
| 156 | // TYPE 122: BigInt |
| 157 | encoder.write_u8(122); |
| 158 | encoder.write_i64(*num) |
| 159 | } |
| 160 | Any::Array(arr) => { |
| 161 | // TYPE 117: Array |
| 162 | encoder.write_u8(117); |
| 163 | encoder.write_var(arr.len() as u64); |
| 164 | for el in arr.iter() { |
| 165 | el.encode(encoder); |
| 166 | } |
| 167 | } |
| 168 | Any::Map(map) => { |
| 169 | // TYPE 118: Map |
| 170 | encoder.write_u8(118); |
| 171 | encoder.write_var(map.len() as u64); |
| 172 | for (key, value) in map.as_ref() { |
| 173 | encoder.write_string(&key); |
| 174 | value.encode(encoder); |
| 175 | } |
| 176 | } |
| 177 | Any::Buffer(buf) => { |
| 178 | // TYPE 116: Buffer |
| 179 | encoder.write_u8(116); |
| 180 | encoder.write_buf(&buf) |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | pub fn from_json(src: &str) -> Result<Self, Error> { |
| 186 | Ok(serde_json::from_str(src)?) |
| 187 | } |
| 188 | |
| 189 | pub fn to_json(&self, buf: &mut String) { |
| 190 | use serde::Serialize; |
| 191 | use serde_json::Serializer; |
| 192 | |
| 193 | let buf = unsafe { buf.as_mut_vec() }; |
| 194 | let cursor = std::io::Cursor::new(buf); |
| 195 | |
| 196 | let mut s = Serializer::new(cursor); |
| 197 | self.serialize(&mut s).unwrap(); |
| 198 | } |
| 199 | |
| 200 | /// Returns an iterator over an inner values of an array or a map, current reference represents. |
| 201 | pub fn try_iter(&self) -> Option<AnyIter<'_>> { |
| 202 | match self { |
| 203 | Any::Array(values) => Some(AnyIter::Array(values.iter())), |
| 204 | Any::Map(entries) => Some(AnyIter::Map(entries.iter())), |
| 205 | _ => None, |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | pub fn try_into_iter(self) -> Option<AnyIntoIter> { |
| 210 | match self { |
| 211 | Any::Array(values) => Some(AnyIntoIter::from(values.clone())), |
| 212 | Any::Map(entries) => Some(AnyIntoIter::from(entries.clone())), |
| 213 | _ => None, |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl std::fmt::Display for Any { |
| 219 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 220 | match self { |
| 221 | Any::Null => f.write_str("null"), |
| 222 | Any::Undefined => f.write_str("undefined"), |
| 223 | Any::Bool(value) => write!(f, "{}", value), |
| 224 | Any::Number(value) => write!(f, "{}", value), |
| 225 | Any::BigInt(value) => write!(f, "{}", value), |
| 226 | Any::String(value) => f.write_str(value.as_ref()), |
| 227 | Any::Array(values) => { |
| 228 | write!(f, "[")?; |
| 229 | let mut i = values.iter(); |
| 230 | if let Some(value) = i.next() { |
| 231 | value.fmt(f)?; |
| 232 | } |
| 233 | while let Some(value) = i.next() { |
| 234 | write!(f, ", ")?; |
| 235 | value.fmt(f)?; |
| 236 | } |
| 237 | write!(f, "]") |
| 238 | } |
| 239 | Any::Map(entries) => { |
| 240 | write!(f, "{{")?; |
| 241 | let mut i = entries.iter(); |
| 242 | if let Some((key, value)) = i.next() { |
| 243 | write!(f, "{}: {}", key, value)?; |
| 244 | } |
| 245 | while let Some((key, value)) = i.next() { |
| 246 | write!(f, ", {}: {}", key, value)?; |
| 247 | } |
| 248 | write!(f, "}}") |
| 249 | } |
| 250 | Any::Buffer(value) => { |
| 251 | f.write_str("0x")?; |
| 252 | for &byte in value.iter() { |
| 253 | write!(f, "{:02x}", byte)?; |
| 254 | } |
| 255 | Ok(()) |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | pub enum AnyIter<'a> { |
| 262 | Array(std::slice::Iter<'a, Any>), |
| 263 | Map(std::collections::hash_map::Iter<'a, String, Any>), |
| 264 | } |
| 265 | |
| 266 | impl<'a> Iterator for AnyIter<'a> { |
| 267 | type Item = (Option<&'a str>, &'a Any); |
| 268 | |
| 269 | fn next(&mut self) -> Option<Self::Item> { |
| 270 | match self { |
| 271 | AnyIter::Array(iter) => { |
| 272 | let value = iter.next()?; |
| 273 | Some((None, value)) |
| 274 | } |
| 275 | AnyIter::Map(iter) => { |
| 276 | let (key, value) = iter.next()?; |
| 277 | Some((Some(key), value)) |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | pub struct AnyArrayIter { |
| 284 | source: Arc<[Any]>, |
| 285 | index: usize, |
| 286 | } |
| 287 | |
| 288 | impl AnyArrayIter { |
| 289 | pub fn new(source: Arc<[Any]>) -> Self { |
| 290 | Self { source, index: 0 } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | impl Iterator for AnyArrayIter { |
| 295 | type Item = Any; |
| 296 | |
| 297 | fn next(&mut self) -> Option<Self::Item> { |
| 298 | if self.index < self.source.len() { |
| 299 | let value = self.source[self.index].clone(); |
| 300 | self.index += 1; |
| 301 | Some(value) |
| 302 | } else { |
| 303 | None |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | pub enum AnyIntoIter { |
| 309 | Array(AnyArrayIter), |
| 310 | //TODO: we need to clone the map, because we need to consume its iterator |
| 311 | // try to figure out something better |
| 312 | Map(std::collections::hash_map::IntoIter<String, Any>), |
| 313 | } |
| 314 | |
| 315 | impl From<Arc<[Any]>> for AnyIntoIter { |
| 316 | fn from(value: Arc<[Any]>) -> Self { |
| 317 | Self::Array(AnyArrayIter::new(value)) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | impl From<Arc<HashMap<String, Any>>> for AnyIntoIter { |
| 322 | fn from(value: Arc<HashMap<String, Any>>) -> Self { |
| 323 | Self::Map((&*value).clone().into_iter()) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | impl Iterator for AnyIntoIter { |
| 328 | type Item = (Option<String>, Any); |
| 329 | |
| 330 | fn next(&mut self) -> Option<Self::Item> { |
| 331 | match self { |
| 332 | AnyIntoIter::Array(iter) => { |
| 333 | let n = iter.next()?; |
| 334 | Some((None, n)) |
| 335 | } |
| 336 | AnyIntoIter::Map(iter) => { |
| 337 | let (key, value) = iter.next()?; |
| 338 | Some((Some(key.clone()), value.clone())) |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | macro_rules! impl_from_num { |
| 345 | ($t:ty) => { |
| 346 | impl From<$t> for Any { |
| 347 | #[inline] |
| 348 | fn from(v: $t) -> Self { |
| 349 | Self::Number(v as f64) |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | impl TryFrom<Any> for $t { |
| 354 | type Error = Any; |
| 355 | |
| 356 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 357 | match v { |
| 358 | Any::Number(num) => Ok(num as Self), |
| 359 | Any::BigInt(num) => Ok(num as Self), |
| 360 | other => Err(other), |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | }; |
| 365 | } |
| 366 | macro_rules! impl_from_bigint { |
| 367 | ($t:ty) => { |
| 368 | impl From<$t> for Any { |
| 369 | fn from(value: $t) -> Self { |
| 370 | let v = value as f64; |
| 371 | if v <= F64_MAX_SAFE_INTEGER && v >= F64_MIN_SAFE_INTEGER { |
| 372 | Self::Number(v) |
| 373 | } else { |
| 374 | Self::BigInt(value as i64) |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | impl TryFrom<Any> for $t { |
| 380 | type Error = Any; |
| 381 | |
| 382 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 383 | match v { |
| 384 | Any::Number(num) => Ok(num as Self), |
| 385 | Any::BigInt(num) => Ok(num as Self), |
| 386 | other => Err(other), |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | }; |
| 391 | } |
| 392 | |
| 393 | impl_from_num!(f32); |
| 394 | impl_from_num!(f64); |
| 395 | impl_from_num!(i16); |
| 396 | impl_from_num!(i32); |
| 397 | impl_from_num!(u16); |
| 398 | impl_from_num!(u32); |
| 399 | impl_from_bigint!(i64); |
| 400 | impl_from_bigint!(isize); |
| 401 | |
| 402 | impl TryFrom<u64> for Any { |
| 403 | type Error = u64; |
| 404 | |
| 405 | fn try_from(value: u64) -> Result<Self, Self::Error> { |
| 406 | if value > i64::MAX.abs() as u64 { |
| 407 | Err(value) |
| 408 | } else { |
| 409 | let v = value as f64; |
| 410 | if v <= F64_MAX_SAFE_INTEGER && v >= F64_MIN_SAFE_INTEGER { |
| 411 | Ok(Any::Number(v)) |
| 412 | } else { |
| 413 | Ok(Any::BigInt(v as i64)) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | impl TryFrom<Any> for u64 { |
| 420 | type Error = Any; |
| 421 | |
| 422 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 423 | match v { |
| 424 | Any::Number(num) => Ok(num as Self), |
| 425 | Any::BigInt(num) => Ok(num as Self), |
| 426 | other => Err(other), |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | impl TryFrom<usize> for Any { |
| 432 | type Error = usize; |
| 433 | |
| 434 | #[cfg(target_pointer_width = "32")] |
| 435 | fn try_from(value: usize) -> Result<Self, Self::Error> { |
| 436 | // for 32-bit architectures we know that usize will always fit, |
| 437 | // so there's no need to check for length, but we stick to TryInto |
| 438 | // trait to keep API compatibility |
| 439 | Ok(Any::Number(value as f64)) |
| 440 | } |
| 441 | |
| 442 | #[cfg(target_pointer_width = "64")] |
| 443 | fn try_from(value: usize) -> Result<Self, Self::Error> { |
| 444 | use std::convert::TryInto; |
| 445 | if let Ok(v) = (value as u64).try_into() { |
| 446 | Ok(v) |
| 447 | } else { |
| 448 | Err(value) |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | impl TryFrom<Any> for usize { |
| 454 | type Error = Any; |
| 455 | |
| 456 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 457 | match v { |
| 458 | Any::Number(num) => Ok(num as Self), |
| 459 | Any::BigInt(num) => Ok(num as Self), |
| 460 | other => Err(other), |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | impl From<bool> for Any { |
| 466 | #[inline] |
| 467 | fn from(value: bool) -> Self { |
| 468 | Any::Bool(value) |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | impl TryFrom<Any> for bool { |
| 473 | type Error = Any; |
| 474 | |
| 475 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 476 | match v { |
| 477 | Any::Bool(num) => Ok(num), |
| 478 | other => Err(other), |
| 479 | } |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | impl From<String> for Any { |
| 484 | #[inline] |
| 485 | fn from(value: String) -> Self { |
| 486 | Any::String(value.into()) |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | impl TryFrom<Any> for String { |
| 491 | type Error = Any; |
| 492 | |
| 493 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 494 | match v { |
| 495 | Any::String(value) => Ok(String::from(value.as_ref())), |
| 496 | other => Err(other), |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | impl From<&str> for Any { |
| 502 | #[inline] |
| 503 | fn from(value: &str) -> Self { |
| 504 | Any::String(value.into()) |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | impl From<Arc<str>> for Any { |
| 509 | #[inline] |
| 510 | fn from(value: Arc<str>) -> Self { |
| 511 | Any::String(value.clone()) |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | impl TryFrom<Any> for Arc<str> { |
| 516 | type Error = Any; |
| 517 | |
| 518 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 519 | match v { |
| 520 | Any::String(value) => Ok(value), |
| 521 | other => Err(other), |
| 522 | } |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | impl From<Vec<u8>> for Any { |
| 527 | #[inline] |
| 528 | fn from(value: Vec<u8>) -> Self { |
| 529 | Any::Buffer(Arc::from(value)) |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | impl TryFrom<Any> for Vec<u8> { |
| 534 | type Error = Any; |
| 535 | |
| 536 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 537 | match v { |
| 538 | Any::Buffer(value) => Ok(Vec::from(value.as_ref())), |
| 539 | other => Err(other), |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | impl From<Arc<[u8]>> for Any { |
| 545 | #[inline] |
| 546 | fn from(value: Arc<[u8]>) -> Self { |
| 547 | Any::Buffer(value) |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | impl TryFrom<Any> for Arc<[u8]> { |
| 552 | type Error = Any; |
| 553 | |
| 554 | fn try_from(v: Any) -> Result<Self, Self::Error> { |
| 555 | match v { |
| 556 | Any::Buffer(value) => Ok(value), |
| 557 | other => Err(other), |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | impl From<&[u8]> for Any { |
| 563 | #[inline] |
| 564 | fn from(value: &[u8]) -> Self { |
| 565 | Any::Buffer(Arc::from(value)) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | impl<T> From<Option<T>> for Any |
| 570 | where |
| 571 | T: Into<Any>, |
| 572 | { |
| 573 | fn from(v: Option<T>) -> Any { |
| 574 | match v { |
| 575 | None => Any::Null, |
| 576 | Some(value) => value.into(), |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | impl<T> From<Vec<T>> for Any |
| 582 | where |
| 583 | T: Into<Any>, |
| 584 | { |
| 585 | fn from(v: Vec<T>) -> Any { |
| 586 | let mut array = Vec::with_capacity(v.len()); |
| 587 | for value in v { |
| 588 | array.push(value.into()) |
| 589 | } |
| 590 | Any::Array(Arc::from(array)) |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | impl<T> From<HashMap<String, T>> for Any |
| 595 | where |
| 596 | T: Into<Any>, |
| 597 | { |
| 598 | fn from(v: HashMap<String, T>) -> Any { |
| 599 | let mut map = HashMap::with_capacity(v.len()); |
| 600 | for (key, value) in v { |
| 601 | map.insert(key, value.into()); |
| 602 | } |
| 603 | Any::Map(Arc::new(map)) |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | // This code is based on serde_json::json! macro (see: https://docs.rs/serde_json/latest/src/serde_json/macros.rs.html#53-58). |
| 608 | // Kudos to the original authors. |
| 609 | |
| 610 | /// Construct a lib0 [Any] value literal. |
| 611 | /// |
| 612 | /// # Examples |
| 613 | /// |
| 614 | /// ```rust |
| 615 | /// |
| 616 | /// use yrs::any; |
| 617 | /// |
| 618 | /// let value = any!({ |
| 619 | /// "code": 200, |
| 620 | /// "success": true, |
| 621 | /// "payload": { |
| 622 | /// "features": [ |
| 623 | /// "lib0", |
| 624 | /// true |
| 625 | /// ] |
| 626 | /// } |
| 627 | /// }); |
| 628 | /// ``` |
| 629 | #[macro_export(local_inner_macros)] |
| 630 | macro_rules! any { |
| 631 | // Hide distracting implementation details from the generated rustdoc. |
| 632 | ($($any:tt)+) => { |
| 633 | any_internal!($($any)+) |
| 634 | }; |
| 635 | } |
| 636 | |
| 637 | #[macro_export(local_inner_macros)] |
| 638 | #[doc(hidden)] |
| 639 | macro_rules! any_internal { |
| 640 | (@array [$($items:expr,)*]) => { |
| 641 | any_internal_array![$($items,)*] |
| 642 | }; |
| 643 | |
| 644 | // Done without trailing comma. |
| 645 | (@array [$($items:expr),*]) => { |
| 646 | any_internal_array![$($items),*] |
| 647 | }; |
| 648 | |
| 649 | // Next item is `null`. |
| 650 | (@array [$($items:expr,)*] null $($rest:tt)*) => { |
| 651 | any_internal!(@array [$($items,)* any_internal!(null)] $($rest)*) |
| 652 | }; |
| 653 | |
| 654 | // Next item is `true`. |
| 655 | (@array [$($items:expr,)*] true $($rest:tt)*) => { |
| 656 | any_internal!(@array [$($items,)* any_internal!(true)] $($rest)*) |
| 657 | }; |
| 658 | |
| 659 | // Next item is `false`. |
| 660 | (@array [$($items:expr,)*] false $($rest:tt)*) => { |
| 661 | any_internal!(@array [$($items,)* any_internal!(false)] $($rest)*) |
| 662 | }; |
| 663 | |
| 664 | // Next item is an array. |
| 665 | (@array [$($items:expr,)*] [$($array:tt)*] $($rest:tt)*) => { |
| 666 | any_internal!(@array [$($items,)* any_internal!([$($array)*])] $($rest)*) |
| 667 | }; |
| 668 | |
| 669 | // Next item is a map. |
| 670 | (@array [$($items:expr,)*] {$($map:tt)*} $($rest:tt)*) => { |
| 671 | any_internal!(@array [$($items,)* any_internal!({$($map)*})] $($rest)*) |
| 672 | }; |
| 673 | |
| 674 | // Next item is an expression followed by comma. |
| 675 | (@array [$($items:expr,)*] $next:expr, $($rest:tt)*) => { |
| 676 | any_internal!(@array [$($items,)* any_internal!($next),] $($rest)*) |
| 677 | }; |
| 678 | |
| 679 | // Last item is an expression with no trailing comma. |
| 680 | (@array [$($items:expr,)*] $last:expr) => { |
| 681 | any_internal!(@array [$($items,)* any_internal!($last)]) |
| 682 | }; |
| 683 | |
| 684 | // Comma after the most recent item. |
| 685 | (@array [$($items:expr),*] , $($rest:tt)*) => { |
| 686 | any_internal!(@array [$($items,)*] $($rest)*) |
| 687 | }; |
| 688 | |
| 689 | // Unexpected token after most recent item. |
| 690 | (@array [$($items:expr),*] $unexpected:tt $($rest:tt)*) => { |
| 691 | any_unexpected!($unexpected) |
| 692 | }; |
| 693 | |
| 694 | (@object $object:ident () () ()) => {}; |
| 695 | |
| 696 | // Insert the current entry followed by trailing comma. |
| 697 | (@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => { |
| 698 | let _ = $object.insert(($($key)+).into(), $value); |
| 699 | any_internal!(@object $object () ($($rest)*) ($($rest)*)); |
| 700 | }; |
| 701 | |
| 702 | // Current entry followed by unexpected token. |
| 703 | (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($rest:tt)*) => { |
| 704 | any_unexpected!($unexpected); |
| 705 | }; |
| 706 | |
| 707 | // Insert the last entry without trailing comma. |
| 708 | (@object $object:ident [$($key:tt)+] ($value:expr)) => { |
| 709 | let _ = $object.insert(($($key)+).into(), $value); |
| 710 | }; |
| 711 | |
| 712 | // Next value is `null`. |
| 713 | (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => { |
| 714 | any_internal!(@object $object [$($key)+] (any_internal!(null)) $($rest)*); |
| 715 | }; |
| 716 | |
| 717 | // Next value is `true`. |
| 718 | (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => { |
| 719 | any_internal!(@object $object [$($key)+] (any_internal!(true)) $($rest)*); |
| 720 | }; |
| 721 | |
| 722 | // Next value is `false`. |
| 723 | (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => { |
| 724 | any_internal!(@object $object [$($key)+] (any_internal!(false)) $($rest)*); |
| 725 | }; |
| 726 | |
| 727 | // Next value is an array. |
| 728 | (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => { |
| 729 | any_internal!(@object $object [$($key)+] (any_internal!([$($array)*])) $($rest)*); |
| 730 | }; |
| 731 | |
| 732 | // Next value is a map. |
| 733 | (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => { |
| 734 | any_internal!(@object $object [$($key)+] (any_internal!({$($map)*})) $($rest)*); |
| 735 | }; |
| 736 | |
| 737 | // Next value is an expression followed by comma. |
| 738 | (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => { |
| 739 | any_internal!(@object $object [$($key)+] (any_internal!($value)) , $($rest)*); |
| 740 | }; |
| 741 | |
| 742 | // Last value is an expression with no trailing comma. |
| 743 | (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { |
| 744 | any_internal!(@object $object [$($key)+] (any_internal!($value))); |
| 745 | }; |
| 746 | |
| 747 | // Missing value for last entry. Trigger a reasonable error message. |
| 748 | (@object $object:ident ($($key:tt)+) (:) $copy:tt) => { |
| 749 | // "unexpected end of macro invocation" |
| 750 | any_internal!(); |
| 751 | }; |
| 752 | |
| 753 | // Missing colon and value for last entry. Trigger a reasonable error |
| 754 | // message. |
| 755 | (@object $object:ident ($($key:tt)+) () $copy:tt) => { |
| 756 | // "unexpected end of macro invocation" |
| 757 | any_internal!(); |
| 758 | }; |
| 759 | |
| 760 | // Misplaced colon. Trigger a reasonable error message. |
| 761 | (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => { |
| 762 | // Takes no arguments so "no rules expected the token `:`". |
| 763 | any_unexpected!($colon); |
| 764 | }; |
| 765 | |
| 766 | // Found a comma inside a key. Trigger a reasonable error message. |
| 767 | (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => { |
| 768 | // Takes no arguments so "no rules expected the token `,`". |
| 769 | any_unexpected!($comma); |
| 770 | }; |
| 771 | |
| 772 | // Key is fully parenthesized. This avoids clippy double_parens false |
| 773 | // positives because the parenthesization may be necessary here. |
| 774 | (@object $object:ident () (($key:expr) : $($rest:tt)*) $copy:tt) => { |
| 775 | any_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*)); |
| 776 | }; |
| 777 | |
| 778 | // Refuse to absorb colon token into key expression. |
| 779 | (@object $object:ident ($($key:tt)*) (: $($unexpected:tt)+) $copy:tt) => { |
| 780 | json_expect_expr_comma!($($unexpected)+); |
| 781 | }; |
| 782 | |
| 783 | // Munch a token into the current key. |
| 784 | (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) $copy:tt) => { |
| 785 | any_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*)); |
| 786 | }; |
| 787 | |
| 788 | ////////////////////////////////////////////////////////////////////////// |
| 789 | // The main implementation. |
| 790 | // |
| 791 | // Must be invoked as: any_internal!($($json)+) |
| 792 | ////////////////////////////////////////////////////////////////////////// |
| 793 | |
| 794 | (null) => { |
| 795 | $crate::any::Any::Null |
| 796 | }; |
| 797 | |
| 798 | (true) => { |
| 799 | $crate::any::Any::Bool(true) |
| 800 | }; |
| 801 | |
| 802 | (false) => { |
| 803 | $crate::any::Any::Bool(false) |
| 804 | }; |
| 805 | |
| 806 | ([]) => { |
| 807 | $crate::any::Any::Array(any_internal_array![]) |
| 808 | }; |
| 809 | |
| 810 | ([ $($tt:tt)+ ]) => { |
| 811 | $crate::any::Any::Array(any_internal!(@array [] $($tt)+)) |
| 812 | }; |
| 813 | |
| 814 | ({}) => { |
| 815 | $crate::any::Any::Map(std::sync::Arc::new(std::collections::HashMap::new())) |
| 816 | }; |
| 817 | |
| 818 | ({ $($tt:tt)+ }) => { |
| 819 | $crate::any::Any::Map({ |
| 820 | let mut object = std::collections::HashMap::new(); |
| 821 | any_internal!(@object object () ($($tt)+) ($($tt)+)); |
| 822 | std::sync::Arc::new(object) |
| 823 | }) |
| 824 | }; |
| 825 | |
| 826 | // Any Serialize type: numbers, strings, struct literals, variables etc. |
| 827 | // Must be below every other rule. |
| 828 | ($other:expr) => { |
| 829 | ($other).into() |
| 830 | }; |
| 831 | } |
| 832 | |
| 833 | #[macro_export] |
| 834 | #[doc(hidden)] |
| 835 | macro_rules! any_internal_array { |
| 836 | ($($content:tt)*) => { |
| 837 | std::sync::Arc::from([$($content)*]) |
| 838 | }; |
| 839 | } |
| 840 | |
| 841 | #[macro_export] |
| 842 | #[doc(hidden)] |
| 843 | macro_rules! any_unexpected { |
| 844 | () => {}; |
| 845 | } |
| 846 | |
| 847 | #[macro_export] |
| 848 | #[doc(hidden)] |
| 849 | macro_rules! any_expect_expr_comma { |
| 850 | ($e:expr , $($tt:tt)*) => {}; |
| 851 | } |
| 852 | |