1use std::convert::{TryFrom, TryInto};
2use std::fmt;
3use std::hash::Hash;
4use std::iter::FromIterator;
5use std::mem::size_of;
6use std::ops::{Bound, Deref};
7use std::str::FromStr;
8use std::sync::Arc;
9
10use async_hash::generic_array::GenericArray;
11use async_hash::{Digest, Hash as Sha256Hash, Output};
12use async_trait::async_trait;
13use base64::engine::general_purpose::STANDARD_NO_PAD;
14use base64::Engine;
15use bytes::Bytes;
16use destream::de::Error as DestreamError;
17use destream::{de, en};
18use email_address_parser::EmailAddress;
19use get_size::GetSize;
20use safecast::{as_type, CastFrom, CastInto, TryCastFrom, TryCastInto};
21use serde::de::{Deserialize, Deserializer, Error as SerdeError};
22use serde::ser::{Serialize, SerializeMap, Serializer};
23use smallvec::SmallVec;
24use uuid::Uuid;
25
26use tc_error::*;
27use tcgeneric::*;
28
29use super::class::ValueType;
30use super::link::{Host, Link};
31use super::number::{Complex, Float, Number, NumberClass, NumberInstance};
32use super::string::TCString;
33use super::version::Version;
34
35const EMPTY_SEQ: [u8; 0] = [];
36const EXPECTING: &'static str = "a TinyChain value, e.g. 1 or \"two\" or [3]";
37
38#[derive(Clone, Hash)]
40pub enum Value {
41 Bytes(Arc<[u8]>),
42 Email(Arc<EmailAddress>),
43 Link(Link),
44 Id(Id),
45 None,
46 Number(Number),
47 String(TCString),
48 Tuple(Tuple<Self>),
49 Version(Version),
50}
51
52impl GetSize for Value {
53 fn get_size(&self) -> usize {
54 match self {
55 Self::Bytes(bytes) => bytes.get_size(),
56 Self::Email(email) => {
57 size_of::<Arc<EmailAddress>>()
58 + email.get_local_part().get_size()
59 + email.get_domain().get_size()
60 }
61 Self::Link(link) => link.get_size(),
62 Self::Id(id) => id.get_size(),
63 Self::None => 0,
64 Self::Number(n) => n.get_size(),
65 Self::String(s) => s.get_size(),
66 Self::Tuple(t) => t.get_size(),
67 Self::Version(v) => v.get_size(),
68 }
69 }
70}
71
72impl Value {
73 #[inline]
75 pub fn expect_none(&self) -> TCResult<()> {
76 if self.is_none() {
77 Ok(())
78 } else {
79 Err(TCError::unexpected(self, "none"))
80 }
81 }
82
83 pub fn is_none(&self) -> bool {
85 match self {
86 Self::Link(link) => link.host().is_none() && link.path() == &TCPathBuf::default(),
87 Self::None => true,
88 Self::Tuple(tuple) => tuple.is_empty(),
89 _ => false,
90 }
91 }
92
93 pub fn is_some(&self) -> bool {
95 !self.is_none()
96 }
97
98 pub fn is_tuple(&self) -> bool {
100 match self {
101 Self::Tuple(_) => true,
102 _ => false,
103 }
104 }
105
106 pub fn into_type(self, class: ValueType) -> Option<Self> {
107 if self.class() == class {
108 return Some(self);
109 }
110
111 use ValueType as VT;
112
113 match class {
114 VT::Bytes => self.opt_cast_into().map(Self::Bytes),
115 VT::Email => self.opt_cast_into().map(Self::Email),
116 VT::Id => self.opt_cast_into().map(Self::Id),
117 VT::Link => self.opt_cast_into().map(Self::Link),
118 VT::None => Some(Self::None),
119 VT::Number(nt) => Number::opt_cast_from(self)
120 .map(|n| n.into_type(nt))
121 .map(Self::Number),
122 VT::String => self.opt_cast_into().map(Self::String),
123 VT::Tuple => match self {
124 Self::Tuple(tuple) => Some(Self::Tuple(tuple)),
125 _ => None,
126 },
127 VT::Value => Some(self),
128 VT::Version => self.opt_cast_into().map(Self::Version),
129 }
130 }
131}
132
133impl Default for Value {
134 fn default() -> Self {
135 Self::None
136 }
137}
138
139as_type!(Value, Bytes, Arc<[u8]>);
140as_type!(Value, Email, Arc<EmailAddress>);
141as_type!(Value, Id, Id);
142as_type!(Value, Link, Link);
143as_type!(Value, Number, Number);
144as_type!(Value, String, TCString);
145as_type!(Value, Tuple, Tuple<Value>);
146as_type!(Value, Version, Version);
147
148impl PartialEq<Value> for Value {
149 fn eq(&self, other: &Value) -> bool {
150 match (self, other) {
151 (Self::None, Self::None) => true,
152
153 (Self::Bytes(this), Self::Bytes(that)) => this == that,
154 (Self::Email(this), Self::Email(that)) => this == that,
155 (Self::Id(this), Self::Id(that)) => this == that,
156 (Self::Link(this), Self::Link(that)) => this == that,
157 (Self::Number(this), Self::Number(that)) => this == that,
158 (Self::String(this), Self::String(that)) => this == that,
159 (Self::Tuple(this), Self::Tuple(that)) => this == that,
160 (Self::Version(this), Self::Version(that)) => this == that,
161
162 (Self::String(this), that) => match that {
163 Self::Email(that) => this == &that.to_string(),
164 Self::Link(that) => that == this.as_str(),
165 Self::Number(that) => {
166 if let Ok(this) = Number::from_str(this.as_str()) {
167 &this == that
168 } else {
169 false
170 }
171 }
172 Self::Version(that) => that == this.as_str(),
173 _ => false,
174 },
175
176 (this, Self::String(that)) => match this {
177 Self::Email(this) => that == &this.to_string(),
178 Self::Link(this) => this == that.as_str(),
179 Self::Number(this) => {
180 if let Ok(that) = Number::from_str(that.as_str()) {
181 this == &that
182 } else {
183 false
184 }
185 }
186 Self::Version(this) => that == &this.to_string(),
187 _ => false,
188 },
189
190 _ => false,
191 }
192 }
193}
194
195impl Eq for Value {}
196
197impl Instance for Value {
198 type Class = ValueType;
199
200 fn class(&self) -> ValueType {
201 use ValueType as VT;
202 match self {
203 Self::Bytes(_) => VT::Bytes,
204 Self::Email(_) => VT::Email,
205 Self::Id(_) => VT::Id,
206 Self::Link(_) => VT::Link,
207 Self::None => VT::None,
208 Self::Number(n) => VT::Number(n.class()),
209 Self::String(_) => VT::String,
210 Self::Tuple(_) => VT::Tuple,
211 Self::Version(_) => VT::Version,
212 }
213 }
214}
215
216impl<D: Digest> Sha256Hash<D> for Value {
217 fn hash(self) -> Output<D> {
218 Sha256Hash::<D>::hash(&self)
219 }
220}
221
222impl<'a, D: Digest> Sha256Hash<D> for &'a Value {
223 fn hash(self) -> Output<D> {
224 match self {
225 Value::Bytes(bytes) => D::digest(bytes),
226 Value::Email(email) => Sha256Hash::<D>::hash(email.to_string()),
227 Value::Id(id) => Sha256Hash::<D>::hash(id),
228 Value::Link(link) => Sha256Hash::<D>::hash(link),
229 Value::None => GenericArray::default(),
230 Value::Number(n) => Sha256Hash::<D>::hash(*n),
231 Value::String(s) => Sha256Hash::<D>::hash(s.as_str()),
232 Value::Tuple(tuple) => Sha256Hash::<D>::hash(tuple.deref()),
233 Value::Version(v) => Sha256Hash::<D>::hash(*v),
234 }
235 }
236}
237
238impl<'de> Deserialize<'de> for Value {
239 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
240 deserializer.deserialize_any(ValueVisitor)
241 }
242}
243
244impl Serialize for Value {
245 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
246 match self {
247 Self::Bytes(bytes) => {
248 let mut map = serializer.serialize_map(Some(1))?;
249
250 map.serialize_entry(
251 &self.class().path().to_string(),
252 &STANDARD_NO_PAD.encode(&bytes),
253 )?;
254
255 map.end()
256 }
257 Self::Email(email) => {
258 let mut map = serializer.serialize_map(Some(1))?;
259 map.serialize_entry(&self.class().path().to_string(), &email.to_string())?;
260 map.end()
261 }
262 Self::Id(id) => {
263 let mut map = serializer.serialize_map(Some(1))?;
264 map.serialize_entry(id.as_str(), &EMPTY_SEQ)?;
265 map.end()
266 }
267 Self::Link(link) => {
268 let mut map = serializer.serialize_map(Some(1))?;
269 map.serialize_entry(link, &EMPTY_SEQ)?;
270 map.end()
271 }
272 Self::None => serializer.serialize_unit(),
273 Self::Number(n) => match n {
274 Number::Complex(c) => {
275 let mut map = serializer.serialize_map(Some(1))?;
276 map.serialize_entry(&self.class().path().to_string(), &Number::Complex(*c))?;
277 map.end()
278 }
279 n => n.serialize(serializer),
280 },
281 Self::String(s) => s.serialize(serializer),
282 Self::Tuple(t) => t.as_slice().serialize(serializer),
283 Self::Version(v) => v.serialize(serializer),
284 }
285 }
286}
287
288impl<T> FromIterator<T> for Value
289where
290 Value: From<T>,
291{
292 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
293 let tuple = Tuple::<Value>::from_iter(iter.into_iter().map(Value::from));
294 Self::Tuple(tuple)
295 }
296}
297
298#[async_trait]
299impl de::FromStream for Value {
300 type Context = ();
301
302 async fn from_stream<D: de::Decoder>(_context: (), decoder: &mut D) -> Result<Self, D::Error> {
303 decoder.decode_any(ValueVisitor).await
304 }
305}
306
307impl<'en> en::ToStream<'en> for Value {
308 fn to_stream<E: en::Encoder<'en>>(&'en self, encoder: E) -> Result<E::Ok, E::Error> {
309 use en::EncodeMap;
310
311 match self {
312 Self::Bytes(bytes) => encoder.collect_bytes(bytes.iter().copied()),
313 Self::Email(email) => {
314 let mut map = encoder.encode_map(Some(1))?;
315 map.encode_entry(self.class().path().to_string(), email.to_string())?;
316 map.end()
317 }
318 Self::Id(id) => {
319 let mut map = encoder.encode_map(Some(1))?;
320 map.encode_entry(id, &EMPTY_SEQ)?;
321 map.end()
322 }
323 Self::Link(link) => {
324 let mut map = encoder.encode_map(Some(1))?;
325 map.encode_entry(link, &EMPTY_SEQ)?;
326 map.end()
327 }
328 Self::None => encoder.encode_unit(),
329 Self::Number(n) => match n {
330 Number::Complex(c) => {
331 let mut map = encoder.encode_map(Some(1))?;
332 map.encode_entry(self.class().path().to_string(), Number::Complex(*c))?;
333 map.end()
334 }
335 n => n.to_stream(encoder),
336 },
337 Self::String(s) => s.to_stream(encoder),
338 Self::Tuple(t) => t.to_stream(encoder),
339 Self::Version(v) => v.to_stream(encoder),
340 }
341 }
342}
343
344impl<'en> en::IntoStream<'en> for Value {
345 fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
346 use en::EncodeMap;
347
348 match self {
349 Self::Bytes(bytes) => encoder.encode_bytes(bytes.to_vec()),
350 Self::Email(ref email) => {
351 let mut map = encoder.encode_map(Some(1))?;
352 map.encode_entry(self.class().path().to_string(), email.to_string())?;
353 map.end()
354 }
355 Self::Id(id) => {
356 let mut map = encoder.encode_map(Some(1))?;
357 map.encode_entry(id, &EMPTY_SEQ)?;
358 map.end()
359 }
360 Self::Link(link) => {
361 let mut map = encoder.encode_map(Some(1))?;
362 map.encode_entry(link, &EMPTY_SEQ)?;
363 map.end()
364 }
365 Self::None => encoder.encode_unit(),
366 Self::Number(n) => match n {
367 Number::Complex(c) => {
368 let mut map = encoder.encode_map(Some(1))?;
369 map.encode_entry(self.class().path().to_string(), Number::Complex(c))?;
370 map.end()
371 }
372 n => n.into_stream(encoder),
373 },
374 Self::String(s) => s.into_stream(encoder),
375 Self::Tuple(t) => t.into_inner().into_stream(encoder),
376 Self::Version(v) => v.into_stream(encoder),
377 }
378 }
379}
380
381impl From<()> for Value {
382 fn from(_: ()) -> Value {
383 Value::None
384 }
385}
386
387impl From<bool> for Value {
388 fn from(b: bool) -> Self {
389 Self::Number(Number::from(b))
390 }
391}
392
393impl From<Bytes> for Value {
394 fn from(bytes: Bytes) -> Self {
395 Self::Bytes(Vec::from(bytes).into())
396 }
397}
398
399impl<const N: usize> From<[u8; N]> for Value {
400 fn from(bytes: [u8; N]) -> Self {
401 Self::Bytes(bytes.into())
402 }
403}
404
405impl From<Host> for Value {
406 fn from(host: Host) -> Self {
407 Self::Link(host.into())
408 }
409}
410
411impl<T: Into<Value>> From<Option<T>> for Value {
412 fn from(opt: Option<T>) -> Self {
413 match opt {
414 Some(value) => value.into(),
415 None => Self::None,
416 }
417 }
418}
419
420impl From<TCPathBuf> for Value {
421 fn from(path: TCPathBuf) -> Value {
422 Value::Link(path.into())
423 }
424}
425
426impl From<Vec<Value>> for Value {
427 fn from(tuple: Vec<Value>) -> Self {
428 Self::Tuple(tuple.into())
429 }
430}
431
432impl From<String> for Value {
433 fn from(s: String) -> Self {
434 Self::String(s.into())
435 }
436}
437
438impl From<i64> for Value {
439 fn from(n: i64) -> Self {
440 Self::Number(n.into())
441 }
442}
443
444impl From<usize> for Value {
445 fn from(n: usize) -> Self {
446 Self::Number((n as u64).into())
447 }
448}
449
450impl From<u64> for Value {
451 fn from(n: u64) -> Self {
452 Self::Number(n.into())
453 }
454}
455
456impl<T1: CastInto<Value>, T2: CastInto<Value>> CastFrom<(T1, T2)> for Value {
457 fn cast_from(value: (T1, T2)) -> Self {
458 Value::Tuple(vec![value.0.cast_into(), value.1.cast_into()].into())
459 }
460}
461
462impl TryFrom<Value> for bool {
463 type Error = TCError;
464
465 fn try_from(value: Value) -> Result<Self, Self::Error> {
466 match value {
467 Value::Number(number) => match number {
468 Number::Bool(b) => Ok(b.into()),
469 number => Ok(number == number.class().zero()),
470 },
471 Value::Id(id) if &id == "true" => Ok(true),
472 Value::Id(id) if &id == "false" => Ok(false),
473 Value::String(s) if &s == "true" => Ok(true),
474 Value::String(s) if &s == "false" => Ok(false),
475 other => Err(TCError::unexpected(other, "a boolean")),
476 }
477 }
478}
479
480impl TryFrom<Value> for Arc<[u8]> {
481 type Error = TCError;
482
483 fn try_from(value: Value) -> Result<Self, Self::Error> {
484 match value {
485 Value::Bytes(bytes) => Ok(bytes),
486 Value::Id(id) => Ok(id.as_str().as_bytes().into()),
487 Value::None => Ok(Arc::new([])),
488 Value::Number(_n) => Err(not_implemented!("cast a number to a bitstring")),
489 Value::String(string) => Ok(string.as_str().as_bytes().into()),
490 other => Err(TCError::unexpected(other, "a bitstring")),
491 }
492 }
493}
494
495impl TryFrom<Value> for Id {
496 type Error = TCError;
497
498 fn try_from(value: Value) -> TCResult<Self> {
499 match value {
500 Value::Number(number) => number.to_string().parse().map_err(TCError::from),
501 Value::Id(id) => Ok(id),
502 Value::String(string) => string.as_str().parse().map_err(TCError::from),
503 other => Err(TCError::unexpected(other, "an Id")),
504 }
505 }
506}
507
508impl TryFrom<Value> for Map<Value> {
509 type Error = TCError;
510
511 fn try_from(value: Value) -> Result<Self, Self::Error> {
512 match value {
513 Value::Tuple(tuple) => tuple
514 .into_iter()
515 .map(|item| -> TCResult<(Id, Value)> { item.try_into() })
516 .collect(),
517
518 other => Err(TCError::unexpected(other, "a Map")),
519 }
520 }
521}
522
523impl TryFrom<Value> for Number {
524 type Error = TCError;
525
526 fn try_from(value: Value) -> TCResult<Self> {
527 match value {
528 Value::Number(number) => Ok(number),
529
530 Value::Id(id) => id
531 .as_str()
532 .parse()
533 .map_err(|cause| TCError::unexpected(id, " a Number").consume(cause)),
534
535 Value::String(s) => s
536 .as_str()
537 .parse()
538 .map_err(|cause| TCError::unexpected(s, " a Number").consume(cause)),
539
540 other => Err(TCError::unexpected(other, "a Number")),
541 }
542 }
543}
544
545impl TryFrom<Value> for Tuple<Value> {
546 type Error = TCError;
547
548 fn try_from(value: Value) -> TCResult<Self> {
549 match value {
550 Value::Tuple(tuple) => Ok(tuple),
551 other => Err(TCError::unexpected(other, "a Tuple")),
552 }
553 }
554}
555
556impl<T: TryFrom<Value>> TryFrom<Value> for (Id, T)
557where
558 TCError: From<T::Error>,
559{
560 type Error = TCError;
561
562 fn try_from(value: Value) -> TCResult<Self> {
563 match value {
564 Value::Tuple(mut tuple) if tuple.len() == 2 => {
565 let value = tuple.pop().expect("value");
566 let key = tuple.pop().expect("key");
567 Ok((Id::try_from(key)?, value.try_into()?))
568 }
569 other => Err(TCError::unexpected(other, "a map item")),
570 }
571 }
572}
573
574impl TryCastFrom<Value> for Bound<Value> {
575 fn can_cast_from(value: &Value) -> bool {
576 match value {
577 Value::None => true,
578 Value::Tuple(tuple) if tuple.len() == 2 => match &tuple[0] {
579 Value::String(bound) => bound == "in" || bound == "ex",
580 _ => false,
581 },
582 _ => false,
583 }
584 }
585
586 fn opt_cast_from(value: Value) -> Option<Bound<Value>> {
587 match value {
588 Value::None => Some(Bound::Unbounded),
589 Value::Tuple(mut tuple) if tuple.len() == 2 => {
590 let value = tuple.pop().expect("value");
591 let bound = tuple.pop().expect("bound");
592 match &bound {
593 Value::String(bound) => {
594 if bound == "in" {
595 Some(Bound::Included(value))
596 } else if bound == "ex" {
597 Some(Bound::Excluded(value))
598 } else {
599 None
600 }
601 }
602 _ => None,
603 }
604 }
605 _ => None,
606 }
607 }
608}
609
610impl TryCastFrom<Value> for Arc<[u8]> {
611 fn can_cast_from(value: &Value) -> bool {
612 match value {
613 Value::Bytes(_) => true,
614 Value::Tuple(tuple) => SmallVec::<[u8; 32]>::can_cast_from(tuple),
615 Value::String(_) => true,
616 Value::None => true,
617 _ => false,
618 }
619 }
620
621 fn opt_cast_from(value: Value) -> Option<Self> {
622 match value {
623 Value::Bytes(bytes) => Some(bytes),
624 Value::Tuple(tuple) => Vec::opt_cast_from(tuple).map(Arc::from),
625 Value::String(s) => Some(s.as_str().as_bytes().to_vec().into()),
626 Value::None => Some(Arc::new([])),
627 _ => None,
628 }
629 }
630}
631
632impl TryCastFrom<Value> for Bytes {
633 fn can_cast_from(value: &Value) -> bool {
634 match value {
635 Value::Bytes(_) => true,
636 Value::Tuple(tuple) => Vec::<u8>::can_cast_from(tuple),
637 Value::String(s) => Self::can_cast_from(s),
638 Value::None => true,
639 _ => false,
640 }
641 }
642
643 fn opt_cast_from(value: Value) -> Option<Bytes> {
644 match value {
645 Value::Bytes(bytes) => Some(bytes.to_vec().into()),
646 Value::Tuple(tuple) => Vec::<u8>::opt_cast_from(tuple).map(Bytes::from),
647 Value::String(s) => Self::opt_cast_from(s),
648 Value::None => Some(Bytes::new()),
649 _ => None,
650 }
651 }
652}
653
654impl TryCastFrom<Value> for Arc<EmailAddress> {
655 fn can_cast_from(value: &Value) -> bool {
656 match value {
657 Value::Email(_) => true,
658 Value::Id(id) => parse_email(id.as_str()).is_some(),
659 Value::String(s) => parse_email(s.as_str()).is_some(),
660 _ => false,
661 }
662 }
663
664 fn opt_cast_from(value: Value) -> Option<Self> {
665 match value {
666 Value::Email(email) => Some(email),
667 Value::Id(id) => parse_email(id.as_str()).map(Arc::new),
668 Value::String(s) => parse_email(s.as_str()).map(Arc::new),
669 _ => None,
670 }
671 }
672}
673
674impl TryCastFrom<Value> for Id {
675 fn can_cast_from(value: &Value) -> bool {
676 match value {
677 Value::Id(_) => true,
678 Value::Number(n) => match n {
679 Number::Float(_) | Number::Complex(_) => false,
680 n => Self::can_cast_from(&n.to_string()),
681 },
682 Value::String(s) => s.as_str().parse::<Id>().is_ok(),
683 Value::Version(_) => true,
684 _ => false,
685 }
686 }
687
688 fn opt_cast_from(value: Value) -> Option<Self> {
689 match value {
690 Value::Id(id) => Some(id),
691 Value::Number(n) => match n {
692 Number::Float(_) | Number::Complex(_) => None,
693 n => Self::opt_cast_from(n.to_string()),
694 },
695 Value::String(s) => s.as_str().parse().ok(),
696 Value::Version(version) => Self::opt_cast_from(version.to_string()),
697 _ => None,
698 }
699 }
700}
701
702impl TryCastFrom<Value> for Host {
703 fn can_cast_from(value: &Value) -> bool {
704 match value {
705 Value::Link(link) => link.host().is_some() && link.path().is_empty(),
706 Value::String(s) => s.as_str().parse::<Host>().is_ok(),
707 _ => false,
708 }
709 }
710
711 fn opt_cast_from(value: Value) -> Option<Self> {
712 match value {
713 Value::Link(link) if link.path().is_empty() => link.into_host(),
714 Value::String(s) => s.as_str().parse().ok(),
715 _ => None,
716 }
717 }
718}
719
720impl TryCastFrom<Value> for Link {
721 fn can_cast_from(value: &Value) -> bool {
722 match value {
723 Value::Link(_) => true,
724 Value::String(s) => s.as_str().parse::<Link>().is_ok(),
725 _ => false,
726 }
727 }
728
729 fn opt_cast_from(value: Value) -> Option<Self> {
730 match value {
731 Value::Link(link) => Some(link),
732 Value::String(s) => s.as_str().parse().ok(),
733 _ => None,
734 }
735 }
736}
737
738impl TryCastFrom<Value> for Number {
739 fn can_cast_from(value: &Value) -> bool {
740 match value {
741 Value::Bytes(_) => false,
742 Value::Email(_) => false,
743 Value::Id(id) => f64::from_str(id.as_str()).is_ok(),
744 Value::Link(_) => false,
745 Value::None => false,
746 Value::Number(_) => true,
747 Value::Tuple(t) if t.len() == 1 => Self::can_cast_from(&t[0]),
748 Value::Tuple(t) if t.len() == 2 => {
749 Self::can_cast_from(&t[0]) && Self::can_cast_from(&t[1])
750 }
751 Value::Tuple(_) => false,
752 Value::String(s) => f64::from_str(s.as_str()).is_ok(),
753 Value::Version(_) => false,
754 }
755 }
756
757 fn opt_cast_from(value: Value) -> Option<Self> {
758 match value {
759 Value::Bytes(_) => None,
760 Value::Email(_) => None,
761 Value::Id(id) => f64::from_str(id.as_str())
762 .map(Float::F64)
763 .map(Self::Float)
764 .ok(),
765 Value::Link(_) => None,
766 Value::None => None,
767 Value::Number(n) => Some(n),
768 Value::Tuple(mut t) if t.len() == 1 => Self::opt_cast_from(t.pop().unwrap()),
769 Value::Tuple(mut t) if t.len() == 2 => {
770 let im = Self::opt_cast_from(t.pop().unwrap());
771 let re = Self::opt_cast_from(t.pop().unwrap());
772 match (re, im) {
773 (Some(Number::Float(Float::F32(re))), Some(Number::Float(Float::F32(im)))) => {
774 let c = Complex::from([re, im]);
775 Some(Self::Complex(c))
776 }
777 (Some(re), Some(im)) => {
778 let re = f64::cast_from(re);
779 let im = f64::cast_from(im);
780 let c = Complex::from([re, im]);
781 Some(Self::Complex(c))
782 }
783 _ => None,
784 }
785 }
786 Value::Tuple(_) => None,
787 Value::String(s) => Number::from_str(s.as_str()).ok(),
788 Value::Version(_) => None,
789 }
790 }
791}
792
793impl TryCastFrom<Value> for String {
794 fn can_cast_from(value: &Value) -> bool {
795 match value {
796 Value::Link(_) => true,
797 Value::Id(_) => true,
798 Value::Number(_) => true,
799 Value::String(_) => true,
800 _ => false,
801 }
802 }
803
804 fn opt_cast_from(value: Value) -> Option<Self> {
805 match value {
806 Value::Link(link) => Some(link.to_string()),
807 Value::Id(id) => Some(id.to_string()),
808 Value::Number(n) => Some(n.to_string()),
809 Value::String(s) => Some(s.to_string()),
810 _ => None,
811 }
812 }
813}
814
815impl TryCastFrom<Value> for TCString {
816 fn can_cast_from(value: &Value) -> bool {
817 match value {
818 Value::Link(_) => true,
819 Value::Id(_) => true,
820 Value::Number(_) => true,
821 Value::String(_) => true,
822 _ => false,
823 }
824 }
825
826 fn opt_cast_from(value: Value) -> Option<Self> {
827 match value {
828 Value::Link(link) => Self::opt_cast_from(link),
829 Value::Id(id) => Self::opt_cast_from(id),
830 Value::Number(n) => Self::opt_cast_from(n),
831 Value::String(s) => Some(s),
832 _ => None,
833 }
834 }
835}
836
837impl TryCastFrom<Value> for Uuid {
838 fn can_cast_from(value: &Value) -> bool {
839 match value {
840 Value::Bytes(bytes) => bytes.len() == 16,
841 Value::Id(id) => Uuid::from_str(id.as_str()).is_ok(),
842 Value::String(s) => Uuid::from_str(s.as_str()).is_ok(),
843 _ => false,
844 }
845 }
846
847 fn opt_cast_from(value: Value) -> Option<Self> {
848 match value {
849 Value::Bytes(bytes) if bytes.len() == 16 => {
850 let bytes = bytes.to_vec().try_into().expect("16-byte UUID");
851 Some(Uuid::from_bytes(bytes))
852 }
853 Value::Id(id) => id.as_str().parse().ok(),
854 Value::String(s) => s.as_str().parse().ok(),
855 _ => None,
856 }
857 }
858}
859
860impl TryCastFrom<Value> for Version {
861 fn can_cast_from(value: &Value) -> bool {
862 match value {
863 Value::Id(id) => Self::can_cast_from(id),
864 Value::String(s) => Version::from_str(s.as_str()).is_ok(),
865 Value::Tuple(t) => <(u32, u32, u32) as TryCastFrom<Tuple<Value>>>::can_cast_from(t),
866 Value::Version(_) => true,
867 _ => false,
868 }
869 }
870
871 fn opt_cast_from(value: Value) -> Option<Self> {
872 match value {
873 Value::Id(id) => Self::opt_cast_from(id),
874
875 Value::String(s) => Version::from_str(s.as_str()).ok(),
876
877 Value::Tuple(t) => t
878 .opt_cast_into()
879 .map(|tuple: (u32, u32, u32)| Version::from(tuple)),
880
881 Value::Version(version) => Some(version),
882
883 _ => None,
884 }
885 }
886}
887
888macro_rules! cast_real {
889 ($n:ty) => {
890 impl TryCastFrom<Value> for $n {
891 fn can_cast_from(value: &Value) -> bool {
892 match value {
893 Value::Number(_) => true,
894 Value::String(s) => Self::from_str(s.as_str()).is_ok(),
895 _ => false,
896 }
897 }
898
899 fn opt_cast_from(value: Value) -> Option<Self> {
900 match value {
901 Value::Number(n) => n.opt_cast_into(),
902 Value::String(s) => Self::from_str(s.as_str()).ok(),
903 _ => None,
904 }
905 }
906 }
907 };
908}
909
910cast_real!(Float);
911cast_real!(bool);
912cast_real!(f32);
913cast_real!(f64);
914cast_real!(u8);
915cast_real!(u16);
916cast_real!(u32);
917cast_real!(u64);
918cast_real!(usize);
919cast_real!(i16);
920cast_real!(i32);
921cast_real!(i64);
922
923impl TryCastFrom<Value> for TCPathBuf {
924 fn can_cast_from(value: &Value) -> bool {
925 match value {
926 Value::Id(_) => true,
927 Value::Link(link) => link.host().is_none(),
928 Value::String(s) => Self::from_str(s.as_str()).is_ok(),
929 _ => false,
930 }
931 }
932
933 fn opt_cast_from(value: Value) -> Option<Self> {
934 match value {
935 Value::Id(id) => Some(Self::from(id)),
936 Value::Link(link) if link.host().is_none() => Some(link.into_path()),
937 Value::String(s) => Self::from_str(s.as_str()).ok(),
938 _ => None,
939 }
940 }
941}
942
943impl<T: TryCastFrom<Value>> TryCastFrom<Value> for (T,) {
944 fn can_cast_from(value: &Value) -> bool {
945 match value {
946 Value::Tuple(tuple) => Self::can_cast_from(tuple),
947 _ => false,
948 }
949 }
950
951 fn opt_cast_from(value: Value) -> Option<Self> {
952 match value {
953 Value::Tuple(tuple) => Self::opt_cast_from(tuple),
954 _ => None,
955 }
956 }
957}
958
959impl<T1: TryCastFrom<Value>, T2: TryCastFrom<Value>> TryCastFrom<Value> for (T1, T2) {
960 fn can_cast_from(value: &Value) -> bool {
961 match value {
962 Value::Tuple(tuple) => Self::can_cast_from(tuple),
963 _ => false,
964 }
965 }
966
967 fn opt_cast_from(value: Value) -> Option<Self> {
968 match value {
969 Value::Tuple(tuple) => Self::opt_cast_from(tuple),
970 _ => None,
971 }
972 }
973}
974
975impl<T1: TryCastFrom<Value>, T2: TryCastFrom<Value>, T3: TryCastFrom<Value>> TryCastFrom<Value>
976 for (T1, T2, T3)
977{
978 fn can_cast_from(value: &Value) -> bool {
979 match value {
980 Value::Tuple(tuple) => Self::can_cast_from(tuple),
981 _ => false,
982 }
983 }
984
985 fn opt_cast_from(value: Value) -> Option<Self> {
986 match value {
987 Value::Tuple(tuple) => Self::opt_cast_from(tuple),
988 _ => None,
989 }
990 }
991}
992
993impl<T: Clone + TryCastFrom<Value>> TryCastFrom<Value> for Map<T> {
994 fn can_cast_from(value: &Value) -> bool {
995 SmallVec::<[(Id, T); 32]>::can_cast_from(value)
996 }
997
998 fn opt_cast_from(value: Value) -> Option<Self> {
999 SmallVec::<[(Id, T); 32]>::opt_cast_from(value).map(|entries| entries.into_iter().collect())
1000 }
1001}
1002
1003impl<const N: usize, T> TryCastFrom<Value> for SmallVec<[T; N]>
1004where
1005 T: TryCastFrom<Value>,
1006 [T; N]: smallvec::Array<Item = T>,
1007{
1008 fn can_cast_from(value: &Value) -> bool {
1009 match value {
1010 Value::Tuple(tuple) => Self::can_cast_from(tuple),
1011 _ => false,
1012 }
1013 }
1014
1015 fn opt_cast_from(value: Value) -> Option<Self> {
1016 match value {
1017 Value::Tuple(tuple) => Self::opt_cast_from(tuple),
1018 _ => None,
1019 }
1020 }
1021}
1022
1023impl<T: TryCastFrom<Value>> TryCastFrom<Value> for Vec<T> {
1024 fn can_cast_from(value: &Value) -> bool {
1025 match value {
1026 Value::Tuple(tuple) => Self::can_cast_from(tuple),
1027 _ => false,
1028 }
1029 }
1030
1031 fn opt_cast_from(value: Value) -> Option<Self> {
1032 match value {
1033 Value::Tuple(tuple) => Self::opt_cast_from(tuple),
1034 _ => None,
1035 }
1036 }
1037}
1038
1039impl<T: Clone + TryCastFrom<Value>> TryCastFrom<Value> for Tuple<T> {
1040 fn can_cast_from(value: &Value) -> bool {
1041 Vec::<T>::can_cast_from(value)
1042 }
1043
1044 fn opt_cast_from(value: Value) -> Option<Self> {
1045 Vec::<T>::opt_cast_from(value).map(Tuple::from)
1046 }
1047}
1048
1049impl fmt::Debug for Value {
1050 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1051 match self {
1052 Self::Bytes(bytes) => write!(f, "0x{}", hex::encode(bytes)),
1053 Self::Id(id) => write!(f, "{:?} ({})", id.as_str(), ValueType::Id),
1054 Self::Email(email) => write!(f, "{:?} ({})", email, ValueType::Email),
1055 Self::Link(link) => write!(f, "{:?} ({})", link, ValueType::Link),
1056 Self::None => f.write_str("None"),
1057 Self::Number(n) => fmt::Debug::fmt(n, f),
1058 Self::String(s) => write!(f, "{} ({})", s, ValueType::String),
1059 Self::Tuple(t) => {
1060 f.write_str("(")?;
1061
1062 for i in 0..t.len() {
1063 write!(f, "{:?}", t[i])?;
1064
1065 if i < t.len() - 1 {
1066 f.write_str(", ")?;
1067 }
1068 }
1069
1070 f.write_str(")")
1071 }
1072 Self::Version(v) => fmt::Debug::fmt(v, f),
1073 }
1074 }
1075}
1076
1077impl fmt::Display for Value {
1078 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1079 match self {
1080 Self::Bytes(bytes) => write!(f, "0x{}", hex::encode(bytes)),
1081 Self::Email(email) => fmt::Display::fmt(email, f),
1082 Self::Id(id) => f.write_str(id.as_str()),
1083 Self::Link(link) => fmt::Display::fmt(link, f),
1084 Self::None => f.write_str("None"),
1085 Self::Number(n) => fmt::Display::fmt(n, f),
1086 Self::String(s) => f.write_str(s.as_str()),
1087 Self::Tuple(t) => write!(
1088 f,
1089 "({})",
1090 t.iter()
1091 .map(|v| v.to_string())
1092 .collect::<Vec<String>>()
1093 .join(", ")
1094 ),
1095 Self::Version(v) => fmt::Display::fmt(v, f),
1096 }
1097 }
1098}
1099
1100#[derive(Default)]
1103pub struct ValueVisitor;
1104
1105impl ValueVisitor {
1106 fn visit_number<E, N>(self, n: N) -> Result<Value, E>
1107 where
1108 Number: CastFrom<N>,
1109 {
1110 Ok(Value::Number(Number::cast_from(n)))
1111 }
1112
1113 pub fn visit_map_value<'de, A: serde::de::MapAccess<'de>>(
1114 class: ValueType,
1115 mut map: A,
1116 ) -> Result<Value, A::Error> {
1117 use ValueType as VT;
1118
1119 return match class {
1120 VT::Bytes => {
1121 let encoded = map.next_value::<&str>()?;
1122
1123 STANDARD_NO_PAD
1124 .decode(encoded)
1125 .map(Arc::from)
1126 .map(Value::Bytes)
1127 .map_err(serde::de::Error::custom)
1128 }
1129 VT::Email => {
1130 let email: &str = map.next_value()?;
1131
1132 parse_email(email)
1133 .map(Arc::new)
1134 .map(Value::Email)
1135 .ok_or_else(|| {
1136 serde::de::Error::custom(format!(
1137 "invalid value: {}, expected an email address",
1138 email
1139 ))
1140 })
1141 }
1142 VT::Id => {
1143 let id: &str = map.next_value()?;
1144 Id::from_str(id).map(Value::Id).map_err(A::Error::custom)
1145 }
1146 VT::Link => {
1147 let link = map.next_value()?;
1148 Ok(Value::Link(link))
1149 }
1150 VT::None => {
1151 let _ = map.next_value::<()>()?;
1152 Ok(Value::None)
1153 }
1154 VT::Number(nt) => {
1155 let n = map.next_value::<Number>()?;
1156 Ok(Value::Number(n.into_type(nt)))
1157 }
1158 VT::String => {
1159 let s = map.next_value()?;
1160 Ok(Value::String(s))
1161 }
1162 VT::Tuple => {
1163 let t = map.next_value::<Vec<Value>>()?;
1164 Ok(Value::Tuple(t.into()))
1165 }
1166 VT::Value => {
1167 let v = map.next_value()?;
1168 Ok(v)
1169 }
1170 VT::Version => {
1171 let v = map.next_value()?;
1172 Ok(Value::Version(v))
1173 }
1174 };
1175 }
1176
1177 pub async fn visit_map_value_async<A: destream::MapAccess>(
1178 class: ValueType,
1179 map: &mut A,
1180 ) -> Result<Value, A::Error> {
1181 use ValueType as VT;
1182
1183 if let Ok(map) = map.next_value::<Map<Value>>(()).await {
1184 return if map.is_empty() {
1185 Ok(Value::Link(class.path().into()))
1186 } else {
1187 Err(de::Error::invalid_value(
1188 format!("{:?}", map),
1189 "a Value class",
1190 ))
1191 };
1192 }
1193
1194 return match class {
1195 VT::Bytes => {
1196 let bytes: Vec<u8> = map.next_value(()).await?;
1197 Ok(Value::Bytes(bytes.into()))
1198 }
1199 VT::Email => {
1200 let email: String = map.next_value(()).await?;
1201 parse_email(&email)
1202 .map(Arc::new)
1203 .map(Value::Email)
1204 .ok_or_else(|| de::Error::invalid_value(email, "an email address"))
1205 }
1206 VT::Id => {
1207 let id = map.next_value(()).await?;
1208 Ok(Value::Id(id))
1209 }
1210 VT::Link => {
1211 let link = map.next_value(()).await?;
1212 Ok(Value::Link(link))
1213 }
1214 VT::None => {
1215 let _ = map.next_value::<()>(()).await?;
1216 Ok(Value::None)
1217 }
1218 VT::Number(nt) => {
1219 let n = map.next_value::<Number>(()).await?;
1220 Ok(Value::Number(n.into_type(nt)))
1221 }
1222 VT::String => {
1223 let s = map.next_value(()).await?;
1224 Ok(Value::String(s))
1225 }
1226 VT::Tuple => {
1227 let t = map.next_value::<Vec<Value>>(()).await?;
1228 Ok(Value::Tuple(t.into()))
1229 }
1230 VT::Value => {
1231 let v = map.next_value(()).await?;
1232 Ok(v)
1233 }
1234 VT::Version => {
1235 let v = map.next_value(()).await?;
1236 Ok(Value::Version(v))
1237 }
1238 };
1239 }
1240}
1241
1242impl<'de> serde::de::Visitor<'de> for ValueVisitor {
1243 type Value = Value;
1244
1245 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
1246 f.write_str(EXPECTING)
1247 }
1248
1249 fn visit_bool<E: SerdeError>(self, b: bool) -> Result<Self::Value, E> {
1250 self.visit_number(b)
1251 }
1252
1253 fn visit_i8<E: SerdeError>(self, i: i8) -> Result<Self::Value, E> {
1254 self.visit_number(i as i16)
1255 }
1256
1257 fn visit_i16<E: SerdeError>(self, i: i16) -> Result<Self::Value, E> {
1258 self.visit_number(i)
1259 }
1260
1261 fn visit_i32<E: SerdeError>(self, i: i32) -> Result<Self::Value, E> {
1262 self.visit_number(i)
1263 }
1264
1265 fn visit_i64<E: SerdeError>(self, i: i64) -> Result<Self::Value, E> {
1266 self.visit_number(i)
1267 }
1268
1269 fn visit_u8<E: SerdeError>(self, u: u8) -> Result<Self::Value, E> {
1270 self.visit_number(u)
1271 }
1272
1273 fn visit_u16<E: SerdeError>(self, u: u16) -> Result<Self::Value, E> {
1274 self.visit_number(u)
1275 }
1276
1277 fn visit_u32<E: SerdeError>(self, u: u32) -> Result<Self::Value, E> {
1278 self.visit_number(u)
1279 }
1280
1281 fn visit_u64<E: SerdeError>(self, u: u64) -> Result<Self::Value, E> {
1282 self.visit_number(u)
1283 }
1284
1285 fn visit_f32<E: SerdeError>(self, f: f32) -> Result<Self::Value, E> {
1286 self.visit_number(f)
1287 }
1288
1289 fn visit_f64<E: SerdeError>(self, f: f64) -> Result<Self::Value, E> {
1290 self.visit_number(f)
1291 }
1292
1293 fn visit_str<E: SerdeError>(self, s: &str) -> Result<Self::Value, E> {
1294 Ok(Value::String(s.to_string().into()))
1295 }
1296
1297 fn visit_borrowed_str<E: SerdeError>(self, s: &'de str) -> Result<Self::Value, E> {
1298 Ok(Value::String(s.to_string().into()))
1299 }
1300
1301 fn visit_string<E: SerdeError>(self, s: String) -> Result<Self::Value, E> {
1302 Ok(Value::String(s.into()))
1303 }
1304
1305 fn visit_byte_buf<E: SerdeError>(self, buf: Vec<u8>) -> Result<Self::Value, E> {
1306 Ok(Value::Bytes(buf.into()))
1307 }
1308
1309 fn visit_unit<E: SerdeError>(self) -> Result<Self::Value, E> {
1310 Ok(Value::None)
1311 }
1312
1313 fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
1314 let mut value = if let Some(len) = seq.size_hint() {
1315 Vec::with_capacity(len)
1316 } else {
1317 Vec::new()
1318 };
1319
1320 while let Some(element) = seq.next_element()? {
1321 value.push(element)
1322 }
1323
1324 Ok(Value::Tuple(value.into()))
1325 }
1326
1327 fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
1328 if let Some(key) = map.next_key::<String>()? {
1329 if let Ok(link) = Link::from_str(&key) {
1330 if link.host().is_none() {
1331 use ValueType as VT;
1332 if let Some(class) = VT::from_path(link.path()) {
1333 return Self::visit_map_value(class, map);
1334 }
1335 }
1336
1337 let value = map.next_value::<Vec<Value>>()?;
1338 if value.is_empty() {
1339 Ok(Value::Link(link))
1340 } else {
1341 Err(A::Error::invalid_length(value.len(), &"an empty list"))
1342 }
1343 } else if let Ok(id) = Id::from_str(&key) {
1344 let value = map.next_value::<Vec<Value>>()?;
1345 if value.is_empty() {
1346 Ok(Value::Id(id))
1347 } else {
1348 Err(A::Error::invalid_length(value.len(), &"an empty list"))
1349 }
1350 } else {
1351 Err(A::Error::custom(format!(
1352 "expected a Link but found {}",
1353 key
1354 )))
1355 }
1356 } else {
1357 Err(A::Error::custom("expected a Link but found an empty map"))
1358 }
1359 }
1360}
1361
1362#[async_trait]
1363impl destream::de::Visitor for ValueVisitor {
1364 type Value = Value;
1365
1366 fn expecting() -> &'static str {
1367 EXPECTING
1368 }
1369
1370 async fn visit_array_u8<A: de::ArrayAccess<u8>>(
1371 self,
1372 mut array: A,
1373 ) -> Result<Self::Value, A::Error> {
1374 let mut bytes = Vec::new();
1375 let mut buf = [0u8; 4_096];
1376
1377 loop {
1378 let read = array.buffer(&mut buf).await?;
1379 if read == 0 {
1380 break;
1381 } else {
1382 bytes.extend_from_slice(&buf[..read]);
1383 }
1384 }
1385
1386 Ok(Value::Bytes(bytes.into()))
1387 }
1388
1389 fn visit_bool<E: DestreamError>(self, b: bool) -> Result<Self::Value, E> {
1390 self.visit_number(b)
1391 }
1392
1393 fn visit_i8<E: DestreamError>(self, i: i8) -> Result<Self::Value, E> {
1394 self.visit_number(i as i16)
1395 }
1396
1397 fn visit_i16<E: DestreamError>(self, i: i16) -> Result<Self::Value, E> {
1398 self.visit_number(i)
1399 }
1400
1401 fn visit_i32<E: DestreamError>(self, i: i32) -> Result<Self::Value, E> {
1402 self.visit_number(i)
1403 }
1404
1405 fn visit_i64<E: DestreamError>(self, i: i64) -> Result<Self::Value, E> {
1406 self.visit_number(i)
1407 }
1408
1409 fn visit_u8<E: DestreamError>(self, u: u8) -> Result<Self::Value, E> {
1410 self.visit_number(u)
1411 }
1412
1413 fn visit_u16<E: DestreamError>(self, u: u16) -> Result<Self::Value, E> {
1414 self.visit_number(u)
1415 }
1416
1417 fn visit_u32<E: DestreamError>(self, u: u32) -> Result<Self::Value, E> {
1418 self.visit_number(u)
1419 }
1420
1421 fn visit_u64<E: DestreamError>(self, u: u64) -> Result<Self::Value, E> {
1422 self.visit_number(u)
1423 }
1424
1425 fn visit_f32<E: DestreamError>(self, f: f32) -> Result<Self::Value, E> {
1426 self.visit_number(f)
1427 }
1428
1429 fn visit_f64<E: DestreamError>(self, f: f64) -> Result<Self::Value, E> {
1430 self.visit_number(f)
1431 }
1432
1433 fn visit_string<E: DestreamError>(self, s: String) -> Result<Self::Value, E> {
1434 Ok(Value::String(s.into()))
1435 }
1436
1437 fn visit_unit<E: DestreamError>(self) -> Result<Self::Value, E> {
1438 Ok(Value::None)
1439 }
1440
1441 fn visit_none<E: DestreamError>(self) -> Result<Self::Value, E> {
1442 Ok(Value::None)
1443 }
1444
1445 async fn visit_map<A: destream::MapAccess>(self, mut map: A) -> Result<Self::Value, A::Error> {
1446 use ValueType as VT;
1447
1448 if let Some(key) = map.next_key::<String>(()).await? {
1449 if let Ok(link) = Link::from_str(&key) {
1450 if link.host().is_none() {
1451 if let Some(class) = VT::from_path(link.path()) {
1452 return Self::visit_map_value_async(class, &mut map).await;
1453 }
1454 }
1455
1456 let value = map.next_value::<Vec<Value>>(()).await?;
1457 if value.is_empty() {
1458 Ok(Value::Link(link))
1459 } else {
1460 Err(A::Error::invalid_length(value.len(), "empty sequence"))
1461 }
1462 } else if let Ok(id) = Id::from_str(&key) {
1463 let value = map.next_value::<Vec<Value>>(()).await?;
1464 if value.is_empty() {
1465 Ok(Value::Id(id))
1466 } else {
1467 Err(A::Error::invalid_length(value.len(), "empty sequence"))
1468 }
1469 } else {
1470 Err(DestreamError::invalid_value(key, "a Link"))
1471 }
1472 } else {
1473 Err(DestreamError::invalid_value("empty map", "a Link"))
1474 }
1475 }
1476
1477 async fn visit_seq<A: destream::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {
1478 let mut value = if let Some(len) = seq.size_hint() {
1479 Vec::with_capacity(len)
1480 } else {
1481 Vec::new()
1482 };
1483
1484 while let Some(element) = seq.next_element(()).await? {
1485 value.push(element)
1486 }
1487
1488 Ok(Value::Tuple(value.into()))
1489 }
1490}
1491
1492fn parse_email(s: &str) -> Option<EmailAddress> {
1493 EmailAddress::parse(s.as_ref(), None)
1494}