1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
use super::*; use crate::Fields; use std::borrow::Cow; use std::{error, fmt}; /// The value of a [`Kserd`]. /// /// `Value` captures primitive types (units, booleans, numbers, strings, byte arrays), which /// act as leaves, along with nested structures (tuples, containers, sequences, and maps). /// /// _Sequences_ and _maps_ are simply aliases for vectors/lists, and hashmaps/dictionaries /// respectively. Keyed structures are backed by [`BTreeMap`] so keys are lexiographically sorted. /// _Tuples_ and _containers_ are aliases for tuples/newtype structures and enums, and structures /// respectively. /// /// `Value` tries to avoid owning data, especially larger data such as strings and byte arrays. /// The use of clone-on-write smart pointers are used to facilitate borrowing until mutation is /// required. /// `Value` has numerous convenience methods to facilitate constructing, reading, and mutating an /// object. /// /// # Examples /// Use the methods to quickly see the data if the type is known. Mutating can be done directly. /// ```rust /// # use kserd::*; /// let mut val = Value::new_str("Hi"); /// val.str_mut().map(|s| { /// s.pop(); /// s.push_str("ello, world!"); /// }); /// assert_eq!(val.str(), Some("Hello, world!")); /// ``` /// /// [`BTreeMap`]: std::collections::BTreeMap /// [`Kserd`]: crate::Kserd #[derive(PartialEq, Eq, PartialOrd, Ord)] pub enum Value<'a> { /// A unit value `()`. Unit, /// A boolean value. Bool(bool), /// A numerical value. See [`Number`]. /// /// [`Number`]: crate::Number Num(Number), /// A string value. /// Can be borrowed or owned. /// See [`Kstr`]. /// /// [`Kstr`]: crate::Kstr Str(Kstr<'a>), /// A byte array value. /// Can be borrowed or owned. /// See [`Barr`]. /// /// [`Barr`]: crate::Barr Barr(Barr<'a>), /// A tuple value. /// /// A tuple is a _hetrogeneous sequence of unnamed objects_. /// It shares the same in-memory representation as a sequence but has different formatting /// syntax. Tuples represent not only anonymous tuples (`(u32, u32, u32)`) but also newtype structs and /// enums (ie `Point3d(u32, u32, u32)`). Tuple(Vec<Kserd<'a>>), /// A container value. /// /// A container is a _hetrogeneous collection of named objects_. /// Containers are akin to structs. Cntr(Fields<'a>), /// A sequence of values. /// /// A sequence is a _homogeneous sequence of unnamed objects_. Seq(Vec<Kserd<'a>>), /// A map of values. /// /// A map is a _homogeneous mapping of keys to values_. Map(BTreeMap<Kserd<'a>, Kserd<'a>>), } /// The field name in a container contains invalid characters. #[derive(PartialEq, Debug, Eq, Clone)] pub struct InvalidFieldName(pub Cow<'static, str>); impl InvalidFieldName { fn validate(s: &str) -> Result<(), Self> { let invalid = " /\\\"\t'"; if s.is_empty() { Err(InvalidFieldName(Cow::Borrowed("name is empty"))) } else if s.chars().next().unwrap().is_ascii_digit() { Err(InvalidFieldName(Cow::Borrowed( "name can not begin with digit", ))) } else { for c in s.chars() { if invalid.contains(c) { return Err(InvalidFieldName(Cow::Owned(format!( "invalid character '{}' exists in name '{}'", c, s )))); } } Ok(()) } } } impl error::Error for InvalidFieldName {} impl fmt::Display for InvalidFieldName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "invalid field name: {}", self.0) } } /// Static lifetime constructors. impl Value<'static> { /// A new number value. The trait [`NumberType`] is implemented on all Rust primitive /// numbers so number literals can be used. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_num(123456); /// assert_eq!(value.uint(), Some(123456)); /// /// let value = Value::new_num(-123456); /// assert_eq!(value.int(), Some(-123456)); /// /// let value = Value::new_num(3.14); /// assert_eq!(value.float(), Some(3.14)); /// ``` /// /// [`NumberType`]: crate::ds::num::NumberType pub fn new_num<T: NumberType>(value: T) -> Self { Value::Num(value.into()) } /// A new string value. The ownership of the string is transferred and as such /// the `Value` has a _static_ lifetime. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_string(String::from("Hello, world!")); /// assert_eq!(value.str(), Some("Hello, world!")); /// ``` pub const fn new_string(string: String) -> Self { Value::Str(Kstr::owned(string)) } /// A new byte array value. The ownership of the vector is transferred and as such the `Value` /// has a _static_ lifetime. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_barrv(vec![0,1,2,3]); /// assert_eq!(value.barr(), Some([0,1,2,3].as_ref())); /// ``` pub const fn new_barrv(byte_array: Vec<u8>) -> Self { Value::Barr(Barr::owned(byte_array)) } } /// General lifetime constructors. impl<'a> Value<'a> { /// A new string value. The `Value` borrows the string and has the same lifetime. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_str("Hello, world!"); /// assert_eq!(value.str(), Some("Hello, world!")); /// ``` pub const fn new_str(string: &'a str) -> Self { Value::Str(Kstr::brwed(string)) } /// A new byte array value. The `Value` borrows the array and has the same lifetime. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_barr([0,1,2,5,10].as_ref()); /// assert_eq!(value.barr(), Some([0,1,2,5,10].as_ref())); /// ``` pub const fn new_barr(byte_array: &'a [u8]) -> Self { Value::Barr(Barr::brwed(byte_array)) } /// Construct a new container value from a list of field-value pairs. /// /// # Example /// ```rust /// # use kserd::*; /// let pass = Value::new_cntr(vec![ /// ("a", Kserd::new_num(0)) /// ]).unwrap(); /// /// let fail = Value::new_cntr(vec![ /// ("1 wrong/name", Kserd::new_num(0)) /// ]); /// assert_eq!(fail.is_err(), true); /// ``` pub fn new_cntr<I, S>(iter: I) -> Result<Self, InvalidFieldName> where S: Into<Kstr<'a>>, I: IntoIterator<Item = (S, Kserd<'a>)>, { use std::iter::FromIterator; let map = BTreeMap::from_iter(iter.into_iter().map(|(k, v)| (k.into(), v))); for (k, _) in map.iter() { InvalidFieldName::validate(k)?; } Ok(Value::Cntr(map)) } /// Construct a new map value from a list of key-value pairs. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_map(vec![ /// (Kserd::new_unit(), Kserd::new_num(0)) /// ]); /// ``` pub fn new_map<I>(iter: I) -> Self where I: IntoIterator<Item = (Kserd<'a>, Kserd<'a>)>, { use std::iter::FromIterator; let map = BTreeMap::from_iter(iter); Value::Map(map) } } /// Convenience methods for accessing values straight from the [`Value`] enum. /// /// [`Value`]: crate::Value impl<'a> Value<'a> { /// `Value` is a unit value (`Value::Unit`). /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::Unit; /// assert_eq!(value.unit(), true); /// ``` pub fn unit(&self) -> bool { match &self { Value::Unit => true, _ => false, } } /// `Value` is a boolean value. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::Bool(true); /// assert_eq!(value.bool(), Some(true)); /// ``` pub fn bool(&self) -> Option<bool> { match &self { Value::Bool(val) => Some(*val), _ => None, } } /// `Value` is a boolean value. Can be altered. /// /// # Example /// ```rust /// # use kserd::*; /// let mut value = Value::Bool(false); /// value.bool_mut().map(|x| *x = true); /// assert_eq!(value.bool(), Some(true)); /// ``` pub fn bool_mut(&mut self) -> Option<&mut bool> { match self { Value::Bool(val) => Some(val), _ => None, } } /// `Value` is a string with a _single_ character. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_str("A"); /// assert_eq!(value.ch(), Some('A')); /// /// let value = Value::new_str("Hello, world!"); /// assert_eq!(value.ch(), None); /// ``` pub fn ch(&self) -> Option<char> { match &self { Value::Str(val) if val.chars().count() == 1 => val.chars().next(), _ => None, } } /// `Value` is an unsigned integer. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_num(123456); /// assert_eq!(value.uint(), Some(123456)); /// ``` pub fn uint(&self) -> Option<u128> { match &self { Value::Num(val) => val.as_u128().ok(), _ => None, } } /// `Value` is a signed integer. A positive integer can be both signed and unsigned /// up to `i128::max_value()`. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_num(-123456); /// assert_eq!(value.int(), Some(-123456)); /// ``` pub fn int(&self) -> Option<i128> { match &self { Value::Num(val) => val.as_i128().ok(), _ => None, } } /// `Value` is a floating point number. Both signed and unsigned integers can be represented /// as floats. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_num(-3.14); /// assert_eq!(value.float(), Some(-3.14)); /// ``` pub fn float(&self) -> Option<f64> { match &self { Value::Num(val) => Some(val.as_f64()), _ => None, } } /// `Value` is a numerical value, and can be altered. /// /// # Example /// ```rust /// # use kserd::*; /// let mut value = Value::new_num(123456); /// value.num_mut().map(|x| *x = Number::from(100)); /// assert_eq!(value.uint(), Some(100)); /// ``` pub fn num_mut(&mut self) -> Option<&mut Number> { match self { Value::Num(val) => Some(val), _ => None, } } /// `Value` is a string. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_str("Hello, world!"); /// assert_eq!(value.str(), Some("Hello, world!")); /// ``` pub fn str(&self) -> Option<&str> { match &self { Value::Str(val) => Some(val.as_str()), _ => None, } } /// `Value` is a string. Can be altered. /// /// **Clones string value if not owned.** /// /// # Example /// ```rust /// # use kserd::*; /// let mut value = Value::new_str("Hello"); /// value.str_mut().map(|x| { x.push_str(", world!"); }); /// assert_eq!(value.str(), Some("Hello, world!")); /// ``` pub fn str_mut(&mut self) -> Option<&mut String> { match self { Value::Str(val) => Some(val.to_mut()), _ => None, } } /// `Value` is a byte array. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_barr([0,1,2,5,10].as_ref()); /// assert_eq!(value.barr(), Some([0,1,2,5,10].as_ref())); /// ``` pub fn barr(&self) -> Option<&[u8]> { match &self { Value::Barr(barr) => Some(barr.as_bytes()), _ => None, } } /// `Value` is a byte array. Can be altered. /// /// **Clones data if not already owned.** /// /// # Example /// ```rust /// # use kserd::*; /// let mut value = Value::new_barr([0,1,2].as_ref()); /// value.barr_mut().map(|x| { x.push(3); }); /// assert_eq!(value.barr(), Some([0,1,2,3].as_ref())); /// ``` pub fn barr_mut(&mut self) -> Option<&mut Vec<u8>> { match self { Value::Barr(val) => Some(val.to_mut()), _ => None, } } } /// Conversions. impl<'a> Value<'a> { /// Clones all data to make a static `Value`. pub fn into_owned(self) -> Value<'static> { match self { Value::Unit => Value::Unit, Value::Bool(v) => Value::Bool(v), Value::Num(v) => Value::Num(v), Value::Str(s) => Value::Str(s.into_owned()), Value::Barr(b) => Value::Barr(b.into_owned()), Value::Tuple(seq) => Value::Tuple({ let mut v = Vec::with_capacity(seq.len()); for i in seq { v.push(i.into_owned()) } v }), Value::Cntr(map) => Value::Cntr({ let mut m = BTreeMap::new(); for (k, v) in map { m.insert(k.into_owned(), v.into_owned()); } m }), Value::Seq(seq) => Value::Seq({ let mut v = Vec::with_capacity(seq.len()); for i in seq { v.push(i.into_owned()) } v }), Value::Map(map) => Value::Map({ let mut m = BTreeMap::new(); for (k, v) in map { m.insert(k.into_owned(), v.into_owned()); } m }), } } /// Makes a copy of this `Value` that references data in the this `Value`. /// /// This is particularly useful if you want to gaurantee that _all_ data is of the borrowed /// variety when decoding back to a data structure (see [`Decoder`] for explanation). /// /// There is a performance penalty as nested structures have to be rebuilt. /// /// # Example /// ```rust /// # use kserd::*; /// let value = Value::new_string("Hello, world!".to_owned()); /// let brwed = value.mk_brw(); /// assert_eq!(value, brwed); /// ``` /// /// [`Decoder`]: crate::encode::Decoder pub fn mk_brw(&self) -> Value { match &self { Value::Unit => Value::Unit, Value::Bool(v) => Value::Bool(*v), Value::Num(v) => Value::Num(*v), Value::Str(v) => Value::Str(Kstr::brwed(v.as_str())), Value::Barr(v) => Value::Barr(Barr::brwed(v.as_bytes())), Value::Tuple(seq) => Value::Tuple({ let mut v = Vec::with_capacity(seq.len()); for i in seq { v.push(i.mk_brw()); } v }), Value::Cntr(map) => Value::Cntr({ let mut m = BTreeMap::new(); for (k, v) in map { m.insert(Kstr::brwed(k.as_str()), v.mk_brw()); } m }), Value::Seq(seq) => Value::Seq({ let mut v = Vec::with_capacity(seq.len()); for i in seq { v.push(i.mk_brw()); } v }), Value::Map(map) => Value::Map({ let mut m = BTreeMap::new(); for (k, v) in map { m.insert(k.mk_brw(), v.mk_brw()); } m }), } } } impl<'a> Clone for Value<'a> { fn clone(&self) -> Self { match &self { Value::Unit => Value::Unit, Value::Bool(v) => Value::Bool(*v), Value::Num(v) => Value::Num(*v), Value::Str(s) => Value::Str(s.clone()), Value::Barr(b) => Value::Barr(b.clone()), Value::Tuple(seq) => Value::Tuple(seq.clone()), Value::Cntr(map) => Value::Cntr(map.clone()), Value::Seq(seq) => Value::Seq(seq.clone()), Value::Map(map) => Value::Map(map.clone()), } } } impl<'a> fmt::Debug for Value<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Value::Unit => write!(f, "Unit"), Value::Bool(v) => write!(f, "Bool({})", v), Value::Num(v) => write!(f, "Num({:?})", v), Value::Str(v) => write!(f, "Str({:?})", v), Value::Barr(v) => write!(f, "Barr({:?})", v), Value::Tuple(v) => { let mut d = f.debug_tuple(""); for i in v { d.field(i); } d.finish() } Value::Cntr(v) => { let mut d = f.debug_struct(""); for (k, v) in v { d.field(k.as_str(), v); } d.finish() } Value::Seq(v) => f.debug_list().entries(v.iter()).finish(), Value::Map(v) => f.debug_map().entries(v.iter()).finish(), } } } #[cfg(test)] mod tests { use super::*; #[test] fn invalid_field_test() { fn f(s: &str) -> String { InvalidFieldName::validate(s).unwrap_err().to_string() }; assert_eq!(&f(""), "invalid field name: name is empty"); assert_eq!( &f("9name"), "invalid field name: name can not begin with digit" ); assert_eq!( &f("na\tme"), "invalid field name: invalid character '\t' exists in name 'na\tme'" ); } #[test] fn mutable_testing() { let mut x = Value::Bool(true); x.bool_mut().map(|x| *x = false); assert_eq!(x.bool(), Some(false)); assert_eq!(x.num_mut(), None); let mut x = Value::new_num(123); x.num_mut().map(|x| *x = 3.14.into()); assert_eq!(x.float(), Some(3.14)); assert_eq!(x.bool_mut(), None); assert_eq!(x.str_mut(), None); assert_eq!(x.barr_mut(), None); let mut x = Value::new_str("Hello"); x.str_mut().map(|x| x.push_str(", world!")); assert_eq!(x.str(), Some("Hello, world!")); let mut x = Value::new_barr([0, 1, 2].as_ref()); x.barr_mut().map(|x| x.push(3)); assert_eq!(x.barr(), Some([0, 1, 2, 3].as_ref())); } #[test] fn conversion_testing() { let unit = Value::Unit.to_owned(); assert_eq!(unit, Value::Unit); let b = Value::Bool(true).to_owned(); assert_eq!(b, Value::Bool(true)); let n = Value::new_num(3.14).to_owned(); assert_eq!(n, Value::new_num(3.14)); let s = Value::new_str("What!?").to_owned(); assert_eq!(s, Value::new_str("What!?")); let barr = Value::new_barr([0, 1].as_ref()).to_owned(); assert_eq!(barr, Value::new_barr([0, 1].as_ref())); let b = Value::Bool(true); assert_eq!(b, b.clone()); let barr = Value::new_barr([0, 1].as_ref()).to_owned(); assert_eq!(barr, barr.clone()); fn test(v: Kserd) { let vclone = v.clone(); assert_eq!(v.to_owned(), vclone); }; test(Kserd::new(Value::Tuple(vec![ Kserd::new_str("Hello"), Kserd::new_num(3.14), ]))); test(Kserd::new_cntr(vec![("a", Kserd::new_unit())]).unwrap()); test(Kserd::new(Value::Seq(vec![ Kserd::new_str("Hello"), Kserd::new_num(3.14), ]))); test(Kserd::new_map(vec![(Kserd::new_unit(), Kserd::new_num(0))])); let unit = Value::Unit; assert_eq!(unit, unit.mk_brw()); let b = Value::Bool(true); assert_eq!(b, b.mk_brw()); let n = Value::new_num(3.14); assert_eq!(n, n.mk_brw()); let s = Value::new_str("What!?"); assert_eq!(s, s.mk_brw()); let barr = Value::new_barr([0, 1].as_ref()); assert_eq!(barr, barr.mk_brw()); fn test2(v: Kserd) { assert_eq!(v.mk_brw(), v); }; test2(Kserd::new(Value::Tuple(vec![ Kserd::new_str("Hello"), Kserd::new_num(3.14), ]))); test2(Kserd::new_cntr(vec![("a", Kserd::new_unit())]).unwrap()); test2(Kserd::new(Value::Seq(vec![ Kserd::new_str("Hello"), Kserd::new_num(3.14), ]))); test2(Kserd::new_map(vec![(Kserd::new_unit(), Kserd::new_num(0))])); } #[test] fn into_owned_test() { use crate::to_kserd::ToKserd; let prims = Kserd::new_cntr(vec![ ("unit", Kserd::new_unit()), ("bool", Kserd::new_bool(true)), ("num", Kserd::new_num(1.01234)), ("str", Kserd::new_str("Hello, world!")), ("barr", Kserd::new_barr([0, 1, 2, 4, 8].as_ref())), ]) .unwrap(); let nested = Kserd::new_cntr(vec![ ("prims", prims.clone()), ( "tuple", Kserd::new(Value::Tuple(vec![prims.clone(), prims.clone()])), ), ( "seq", Kserd::new(Value::Seq(vec![ prims.clone(), prims.clone(), prims.clone(), prims.clone(), ])), ), ( "map", Kserd::new_map(vec![ ("first".into_kserd().unwrap(), prims.clone()), ("second".into_kserd().unwrap(), prims.clone()), ]), ), ]) .unwrap(); let nested_owned = nested.clone().into_owned(); assert_eq!(nested, nested_owned); } }