1mod family;
2
3#[cfg(test)]
4mod tests;
5
6use crate::{
7 db::store::StorageKey,
8 prelude::*,
9 traits::{EnumValue, FieldValue, NumFromPrimitive},
10 types::*,
11};
12use candid::CandidType;
13use serde::{Deserialize, Serialize};
14use std::cmp::Ordering;
15
16pub use family::{ValueFamily, ValueFamilyExt};
18
19const F64_SAFE_I64: i64 = 1i64 << 53;
24const F64_SAFE_U64: u64 = 1u64 << 53;
25const F64_SAFE_I128: i128 = 1i128 << 53;
26const F64_SAFE_U128: u128 = 1u128 << 53;
27
28enum NumericRepr {
33 Decimal(Decimal),
34 F64(f64),
35 None,
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum TextMode {
44 Cs, Ci, }
47
48#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
58pub enum Value {
59 Account(Account),
60 Blob(Vec<u8>),
61 Bool(bool),
62 Date(Date),
63 Decimal(Decimal),
64 Duration(Duration),
65 Enum(ValueEnum),
66 E8s(E8s),
67 E18s(E18s),
68 Float32(Float32),
69 Float64(Float64),
70 Int(i64),
71 Int128(Int128),
72 IntBig(Int),
73 List(Vec<Self>),
77 None,
78 Principal(Principal),
79 Subaccount(Subaccount),
80 Text(String),
81 Timestamp(Timestamp),
82 Uint(u64),
83 Uint128(Nat128),
84 UintBig(Nat),
85 Ulid(Ulid),
86 Unit,
87 Unsupported,
88}
89
90impl Value {
91 pub fn from_slice<T>(items: &[T]) -> Self
100 where
101 T: Into<Self> + Clone,
102 {
103 Self::List(items.iter().cloned().map(Into::into).collect())
104 }
105
106 pub fn from_list<T>(items: Vec<T>) -> Self
110 where
111 T: Into<Self>,
112 {
113 Self::List(items.into_iter().map(Into::into).collect())
114 }
115
116 pub fn from_enum<E: EnumValue>(value: E) -> Self {
118 Self::Enum(value.to_value_enum())
119 }
120
121 #[must_use]
123 pub fn enum_strict<E: Path>(variant: &str) -> Self {
124 Self::Enum(ValueEnum::strict::<E>(variant))
125 }
126
127 #[must_use]
134 pub const fn is_numeric(&self) -> bool {
135 matches!(
136 self,
137 Self::Decimal(_)
138 | Self::Duration(_)
139 | Self::E8s(_)
140 | Self::E18s(_)
141 | Self::Float32(_)
142 | Self::Float64(_)
143 | Self::Int(_)
144 | Self::Int128(_)
145 | Self::Timestamp(_)
146 | Self::Uint(_)
147 | Self::Uint128(_)
148 )
149 }
150
151 #[must_use]
153 pub const fn is_text(&self) -> bool {
154 matches!(self, Self::Text(_))
155 }
156
157 #[must_use]
159 pub const fn is_unit(&self) -> bool {
160 matches!(self, Self::Unit)
161 }
162
163 #[must_use]
164 pub const fn is_scalar(&self) -> bool {
165 match self {
166 Self::List(_) | Self::Unit => false,
168 _ => true,
169 }
170 }
171
172 fn numeric_repr(&self) -> NumericRepr {
173 if let Some(d) = self.to_decimal() {
174 return NumericRepr::Decimal(d);
175 }
176 if let Some(f) = self.to_f64_lossless() {
177 return NumericRepr::F64(f);
178 }
179 NumericRepr::None
180 }
181
182 #[must_use]
191 pub const fn as_storage_key(&self) -> Option<StorageKey> {
192 match self {
193 Self::Account(v) => Some(StorageKey::Account(*v)),
194 Self::Int(v) => Some(StorageKey::Int(*v)),
195 Self::Uint(v) => Some(StorageKey::Uint(*v)),
196 Self::Principal(v) => Some(StorageKey::Principal(*v)),
197 Self::Subaccount(v) => Some(StorageKey::Subaccount(*v)),
198 Self::Timestamp(v) => Some(StorageKey::Timestamp(*v)),
199 Self::Ulid(v) => Some(StorageKey::Ulid(*v)),
200 Self::Unit => Some(StorageKey::Unit),
201 _ => None,
202 }
203 }
204
205 #[must_use]
206 pub const fn as_text(&self) -> Option<&str> {
207 if let Self::Text(s) = self {
208 Some(s.as_str())
209 } else {
210 None
211 }
212 }
213
214 #[must_use]
215 pub const fn as_list(&self) -> Option<&[Self]> {
216 if let Self::List(xs) = self {
217 Some(xs.as_slice())
218 } else {
219 None
220 }
221 }
222
223 fn to_decimal(&self) -> Option<Decimal> {
224 match self {
225 Self::Decimal(d) => Some(*d),
226 Self::Duration(d) => Decimal::from_u64(d.get()),
227 Self::E8s(v) => Some(v.to_decimal()),
228 Self::E18s(v) => v.to_decimal(),
229 Self::Float64(f) => Decimal::from_f64(f.get()),
230 Self::Float32(f) => Decimal::from_f32(f.get()),
231 Self::Int(i) => Decimal::from_i64(*i),
232 Self::Int128(i) => Decimal::from_i128(i.get()),
233 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
234 Self::Timestamp(t) => Decimal::from_u64(t.get()),
235 Self::Uint(u) => Decimal::from_u64(*u),
236 Self::Uint128(u) => Decimal::from_u128(u.get()),
237 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
238
239 _ => None,
240 }
241 }
242
243 #[allow(clippy::cast_precision_loss)]
245 fn to_f64_lossless(&self) -> Option<f64> {
246 match self {
247 Self::Duration(d) if d.get() <= F64_SAFE_U64 => Some(d.get() as f64),
248 Self::Float64(f) => Some(f.get()),
249 Self::Float32(f) => Some(f64::from(f.get())),
250 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
251 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
252 Some(i.get() as f64)
253 }
254 Self::IntBig(i) => i.to_i128().and_then(|v| {
255 (-F64_SAFE_I128..=F64_SAFE_I128)
256 .contains(&v)
257 .then_some(v as f64)
258 }),
259 Self::Timestamp(t) if t.get() <= F64_SAFE_U64 => Some(t.get() as f64),
260 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
261 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
262 Self::UintBig(u) => u
263 .to_u128()
264 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
265
266 _ => None,
267 }
268 }
269
270 #[must_use]
272 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
273 match (self.numeric_repr(), other.numeric_repr()) {
274 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
275 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
276 _ => None,
277 }
278 }
279
280 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
285 if s.is_ascii() {
286 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
287 }
288 std::borrow::Cow::Owned(s.to_lowercase())
291 }
292
293 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
294 match mode {
295 TextMode::Cs => std::borrow::Cow::Borrowed(s),
296 TextMode::Ci => Self::fold_ci(s),
297 }
298 }
299
300 fn text_op(
301 &self,
302 other: &Self,
303 mode: TextMode,
304 f: impl Fn(&str, &str) -> bool,
305 ) -> Option<bool> {
306 let (a, b) = (self.as_text()?, other.as_text()?);
307 let a = Self::text_with_mode(a, mode);
308 let b = Self::text_with_mode(b, mode);
309 Some(f(&a, &b))
310 }
311
312 fn ci_key(&self) -> Option<String> {
313 match self {
314 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
315 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
316 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
317 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
318 _ => None,
319 }
320 }
321
322 fn eq_ci(a: &Self, b: &Self) -> bool {
323 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
324 return ak == bk;
325 }
326
327 a == b
328 }
329
330 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
331 match v {
332 Self::List(vs) => vs.iter().collect(),
333 v => vec![v],
334 }
335 }
336
337 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
338 where
339 F: Fn(&Self, &Self) -> bool,
340 {
341 self.as_list()
342 .map(|items| items.iter().any(|v| eq(v, needle)))
343 }
344
345 #[allow(clippy::unnecessary_wraps)]
346 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
347 where
348 F: Fn(&Self, &Self) -> bool,
349 {
350 let needles = Self::normalize_list_ref(needles);
351 match self {
352 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
353 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
354 }
355 }
356
357 #[allow(clippy::unnecessary_wraps)]
358 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
359 where
360 F: Fn(&Self, &Self) -> bool,
361 {
362 let needles = Self::normalize_list_ref(needles);
363 match self {
364 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
365 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
366 }
367 }
368
369 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
370 where
371 F: Fn(&Self, &Self) -> bool,
372 {
373 if let Self::List(items) = haystack {
374 Some(items.iter().any(|h| eq(h, self)))
375 } else {
376 None
377 }
378 }
379
380 #[must_use]
381 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
383 self.text_op(other, mode, |a, b| a == b)
384 }
385
386 #[must_use]
387 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
389 self.text_op(needle, mode, |a, b| a.contains(b))
390 }
391
392 #[must_use]
393 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
395 self.text_op(needle, mode, |a, b| a.starts_with(b))
396 }
397
398 #[must_use]
399 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
401 self.text_op(needle, mode, |a, b| a.ends_with(b))
402 }
403
404 #[must_use]
409 pub const fn is_empty(&self) -> Option<bool> {
410 match self {
411 Self::List(xs) => Some(xs.is_empty()),
412 Self::Text(s) => Some(s.is_empty()),
413 Self::Blob(b) => Some(b.is_empty()),
414
415 Self::None => Some(true),
417
418 _ => None,
419 }
420 }
421
422 #[must_use]
423 pub fn is_not_empty(&self) -> Option<bool> {
425 self.is_empty().map(|b| !b)
426 }
427
428 #[must_use]
433 pub fn contains(&self, needle: &Self) -> Option<bool> {
435 self.contains_by(needle, |a, b| a == b)
436 }
437
438 #[must_use]
439 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
441 self.contains_any_by(needles, |a, b| a == b)
442 }
443
444 #[must_use]
445 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
447 self.contains_all_by(needles, |a, b| a == b)
448 }
449
450 #[must_use]
451 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
453 self.in_list_by(haystack, |a, b| a == b)
454 }
455
456 #[must_use]
457 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
459 match self {
460 Self::List(_) => self.contains_by(needle, Self::eq_ci),
461 _ => Some(Self::eq_ci(self, needle)),
462 }
463 }
464
465 #[must_use]
466 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
468 self.contains_any_by(needles, Self::eq_ci)
469 }
470
471 #[must_use]
472 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
474 self.contains_all_by(needles, Self::eq_ci)
475 }
476
477 #[must_use]
478 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
480 self.in_list_by(haystack, Self::eq_ci)
481 }
482}
483
484impl FieldValue for Value {
485 fn to_value(&self) -> Value {
486 self.clone()
487 }
488}
489
490#[macro_export]
491macro_rules! impl_from_for {
492 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
493 $(
494 impl From<$type> for Value {
495 fn from(v: $type) -> Self {
496 Self::$variant(v.into())
497 }
498 }
499 )*
500 };
501}
502
503impl_from_for! {
504 Account => Account,
505 Date => Date,
506 Decimal => Decimal,
507 Duration => Duration,
508 E8s => E8s,
509 E18s => E18s,
510 bool => Bool,
511 i8 => Int,
512 i16 => Int,
513 i32 => Int,
514 i64 => Int,
515 i128 => Int128,
516 Int => IntBig,
517 Principal => Principal,
518 Subaccount => Subaccount,
519 &str => Text,
520 String => Text,
521 Timestamp => Timestamp,
522 u8 => Uint,
523 u16 => Uint,
524 u32 => Uint,
525 u64 => Uint,
526 u128 => Uint128,
527 Nat => UintBig,
528 Ulid => Ulid,
529}
530
531impl ValueFamilyExt for Value {
532 fn family(&self) -> ValueFamily {
533 match self {
534 Self::Date(_)
536 | Self::Decimal(_)
537 | Self::Duration(_)
538 | Self::E8s(_)
539 | Self::E18s(_)
540 | Self::Float32(_)
541 | Self::Float64(_)
542 | Self::Int(_)
543 | Self::Int128(_)
544 | Self::Timestamp(_)
545 | Self::Uint(_)
546 | Self::Uint128(_)
547 | Self::IntBig(_)
548 | Self::UintBig(_) => ValueFamily::Numeric,
549
550 Self::Text(_) => ValueFamily::Textual,
552
553 Self::Ulid(_) | Self::Principal(_) | Self::Account(_) => ValueFamily::Identifier,
555
556 Self::Enum(_) => ValueFamily::Enum,
558
559 Self::List(_) => ValueFamily::Collection,
561
562 Self::Blob(_) | Self::Subaccount(_) => ValueFamily::Blob,
564
565 Self::Bool(_) => ValueFamily::Bool,
567
568 Self::None => ValueFamily::Null,
570 Self::Unit => ValueFamily::Unit,
571
572 Self::Unsupported => ValueFamily::Unsupported,
574 }
575 }
576}
577
578impl<E: EntityIdentity> From<Ref<E>> for Value {
579 fn from(r: Ref<E>) -> Self {
580 r.to_value() }
582}
583
584impl From<Vec<Self>> for Value {
585 fn from(vec: Vec<Self>) -> Self {
586 Self::List(vec)
587 }
588}
589
590impl From<()> for Value {
591 fn from((): ()) -> Self {
592 Self::Unit
593 }
594}
595
596impl PartialOrd for Value {
597 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
598 match (self, other) {
599 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
600 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
601 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
602 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
603 (Self::E8s(a), Self::E8s(b)) => a.partial_cmp(b),
604 (Self::E18s(a), Self::E18s(b)) => a.partial_cmp(b),
605 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
606 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
607 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
608 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
609 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
610 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
611 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
612 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
613 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
614 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
615 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
616 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
617 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
618 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
619
620 _ => None,
622 }
623 }
624}
625
626#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
632pub struct ValueEnum {
633 pub variant: String,
634 pub path: Option<String>,
635 pub payload: Option<Box<Value>>,
636}
637
638impl ValueEnum {
639 #[must_use]
640 pub fn new(variant: &str, path: Option<&str>) -> Self {
642 Self {
643 variant: variant.to_string(),
644 path: path.map(ToString::to_string),
645 payload: None,
646 }
647 }
648
649 #[must_use]
650 pub fn strict<E: Path>(variant: &str) -> Self {
652 Self::new(variant, Some(E::PATH))
653 }
654
655 #[must_use]
656 pub fn from_enum<E: EnumValue>(value: E) -> Self {
658 value.to_value_enum()
659 }
660
661 #[must_use]
662 pub fn loose(variant: &str) -> Self {
664 Self::new(variant, None)
665 }
666
667 #[must_use]
668 pub fn with_payload(mut self, payload: Value) -> Self {
670 self.payload = Some(Box::new(payload));
671 self
672 }
673}