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_list<T: Into<Self> + Clone>(items: &[T]) -> Self {
97 Self::List(items.iter().cloned().map(Into::into).collect())
98 }
99
100 pub fn from_enum<E: EnumValue>(value: E) -> Self {
102 Self::Enum(value.to_value_enum())
103 }
104
105 #[must_use]
107 pub fn enum_strict<E: Path>(variant: &str) -> Self {
108 Self::Enum(ValueEnum::strict::<E>(variant))
109 }
110
111 #[must_use]
118 pub const fn is_numeric(&self) -> bool {
119 matches!(
120 self,
121 Self::Decimal(_)
122 | Self::Duration(_)
123 | Self::E8s(_)
124 | Self::E18s(_)
125 | Self::Float32(_)
126 | Self::Float64(_)
127 | Self::Int(_)
128 | Self::Int128(_)
129 | Self::Timestamp(_)
130 | Self::Uint(_)
131 | Self::Uint128(_)
132 )
133 }
134
135 #[must_use]
137 pub const fn is_text(&self) -> bool {
138 matches!(self, Self::Text(_))
139 }
140
141 #[must_use]
143 pub const fn is_unit(&self) -> bool {
144 matches!(self, Self::Unit)
145 }
146
147 #[must_use]
148 pub const fn is_scalar(&self) -> bool {
149 match self {
150 Self::List(_) | Self::Unit => false,
152 _ => true,
153 }
154 }
155
156 fn numeric_repr(&self) -> NumericRepr {
157 if let Some(d) = self.to_decimal() {
158 return NumericRepr::Decimal(d);
159 }
160 if let Some(f) = self.to_f64_lossless() {
161 return NumericRepr::F64(f);
162 }
163 NumericRepr::None
164 }
165
166 #[must_use]
175 pub const fn as_storage_key(&self) -> Option<StorageKey> {
176 match self {
177 Self::Account(v) => Some(StorageKey::Account(*v)),
178 Self::Int(v) => Some(StorageKey::Int(*v)),
179 Self::Uint(v) => Some(StorageKey::Uint(*v)),
180 Self::Principal(v) => Some(StorageKey::Principal(*v)),
181 Self::Subaccount(v) => Some(StorageKey::Subaccount(*v)),
182 Self::Timestamp(v) => Some(StorageKey::Timestamp(*v)),
183 Self::Ulid(v) => Some(StorageKey::Ulid(*v)),
184 Self::Unit => Some(StorageKey::Unit),
185 _ => None,
186 }
187 }
188
189 #[must_use]
190 pub const fn as_text(&self) -> Option<&str> {
191 if let Self::Text(s) = self {
192 Some(s.as_str())
193 } else {
194 None
195 }
196 }
197
198 #[must_use]
199 pub const fn as_list(&self) -> Option<&[Self]> {
200 if let Self::List(xs) = self {
201 Some(xs.as_slice())
202 } else {
203 None
204 }
205 }
206
207 fn to_decimal(&self) -> Option<Decimal> {
208 match self {
209 Self::Decimal(d) => Some(*d),
210 Self::Duration(d) => Decimal::from_u64(d.get()),
211 Self::E8s(v) => Some(v.to_decimal()),
212 Self::E18s(v) => v.to_decimal(),
213 Self::Float64(f) => Decimal::from_f64(f.get()),
214 Self::Float32(f) => Decimal::from_f32(f.get()),
215 Self::Int(i) => Decimal::from_i64(*i),
216 Self::Int128(i) => Decimal::from_i128(i.get()),
217 Self::IntBig(i) => i.to_i128().and_then(Decimal::from_i128),
218 Self::Timestamp(t) => Decimal::from_u64(t.get()),
219 Self::Uint(u) => Decimal::from_u64(*u),
220 Self::Uint128(u) => Decimal::from_u128(u.get()),
221 Self::UintBig(u) => u.to_u128().and_then(Decimal::from_u128),
222
223 _ => None,
224 }
225 }
226
227 #[allow(clippy::cast_precision_loss)]
229 fn to_f64_lossless(&self) -> Option<f64> {
230 match self {
231 Self::Duration(d) if d.get() <= F64_SAFE_U64 => Some(d.get() as f64),
232 Self::Float64(f) => Some(f.get()),
233 Self::Float32(f) => Some(f64::from(f.get())),
234 Self::Int(i) if (-F64_SAFE_I64..=F64_SAFE_I64).contains(i) => Some(*i as f64),
235 Self::Int128(i) if (-F64_SAFE_I128..=F64_SAFE_I128).contains(&i.get()) => {
236 Some(i.get() as f64)
237 }
238 Self::IntBig(i) => i.to_i128().and_then(|v| {
239 (-F64_SAFE_I128..=F64_SAFE_I128)
240 .contains(&v)
241 .then_some(v as f64)
242 }),
243 Self::Timestamp(t) if t.get() <= F64_SAFE_U64 => Some(t.get() as f64),
244 Self::Uint(u) if *u <= F64_SAFE_U64 => Some(*u as f64),
245 Self::Uint128(u) if u.get() <= F64_SAFE_U128 => Some(u.get() as f64),
246 Self::UintBig(u) => u
247 .to_u128()
248 .and_then(|v| (v <= F64_SAFE_U128).then_some(v as f64)),
249
250 _ => None,
251 }
252 }
253
254 #[must_use]
256 pub fn cmp_numeric(&self, other: &Self) -> Option<Ordering> {
257 match (self.numeric_repr(), other.numeric_repr()) {
258 (NumericRepr::Decimal(a), NumericRepr::Decimal(b)) => a.partial_cmp(&b),
259 (NumericRepr::F64(a), NumericRepr::F64(b)) => a.partial_cmp(&b),
260 _ => None,
261 }
262 }
263
264 fn fold_ci(s: &str) -> std::borrow::Cow<'_, str> {
269 if s.is_ascii() {
270 return std::borrow::Cow::Owned(s.to_ascii_lowercase());
271 }
272 std::borrow::Cow::Owned(s.to_lowercase())
275 }
276
277 fn text_with_mode(s: &'_ str, mode: TextMode) -> std::borrow::Cow<'_, str> {
278 match mode {
279 TextMode::Cs => std::borrow::Cow::Borrowed(s),
280 TextMode::Ci => Self::fold_ci(s),
281 }
282 }
283
284 fn text_op(
285 &self,
286 other: &Self,
287 mode: TextMode,
288 f: impl Fn(&str, &str) -> bool,
289 ) -> Option<bool> {
290 let (a, b) = (self.as_text()?, other.as_text()?);
291 let a = Self::text_with_mode(a, mode);
292 let b = Self::text_with_mode(b, mode);
293 Some(f(&a, &b))
294 }
295
296 fn ci_key(&self) -> Option<String> {
297 match self {
298 Self::Text(s) => Some(Self::fold_ci(s).into_owned()),
299 Self::Ulid(u) => Some(u.to_string().to_ascii_lowercase()),
300 Self::Principal(p) => Some(p.to_string().to_ascii_lowercase()),
301 Self::Account(a) => Some(a.to_string().to_ascii_lowercase()),
302 _ => None,
303 }
304 }
305
306 fn eq_ci(a: &Self, b: &Self) -> bool {
307 if let (Some(ak), Some(bk)) = (a.ci_key(), b.ci_key()) {
308 return ak == bk;
309 }
310
311 a == b
312 }
313
314 fn normalize_list_ref(v: &Self) -> Vec<&Self> {
315 match v {
316 Self::List(vs) => vs.iter().collect(),
317 v => vec![v],
318 }
319 }
320
321 fn contains_by<F>(&self, needle: &Self, eq: F) -> Option<bool>
322 where
323 F: Fn(&Self, &Self) -> bool,
324 {
325 self.as_list()
326 .map(|items| items.iter().any(|v| eq(v, needle)))
327 }
328
329 #[allow(clippy::unnecessary_wraps)]
330 fn contains_any_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
331 where
332 F: Fn(&Self, &Self) -> bool,
333 {
334 let needles = Self::normalize_list_ref(needles);
335 match self {
336 Self::List(items) => Some(needles.iter().any(|n| items.iter().any(|v| eq(v, n)))),
337 scalar => Some(needles.iter().any(|n| eq(scalar, n))),
338 }
339 }
340
341 #[allow(clippy::unnecessary_wraps)]
342 fn contains_all_by<F>(&self, needles: &Self, eq: F) -> Option<bool>
343 where
344 F: Fn(&Self, &Self) -> bool,
345 {
346 let needles = Self::normalize_list_ref(needles);
347 match self {
348 Self::List(items) => Some(needles.iter().all(|n| items.iter().any(|v| eq(v, n)))),
349 scalar => Some(needles.len() == 1 && eq(scalar, needles[0])),
350 }
351 }
352
353 fn in_list_by<F>(&self, haystack: &Self, eq: F) -> Option<bool>
354 where
355 F: Fn(&Self, &Self) -> bool,
356 {
357 if let Self::List(items) = haystack {
358 Some(items.iter().any(|h| eq(h, self)))
359 } else {
360 None
361 }
362 }
363
364 #[must_use]
365 pub fn text_eq(&self, other: &Self, mode: TextMode) -> Option<bool> {
367 self.text_op(other, mode, |a, b| a == b)
368 }
369
370 #[must_use]
371 pub fn text_contains(&self, needle: &Self, mode: TextMode) -> Option<bool> {
373 self.text_op(needle, mode, |a, b| a.contains(b))
374 }
375
376 #[must_use]
377 pub fn text_starts_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
379 self.text_op(needle, mode, |a, b| a.starts_with(b))
380 }
381
382 #[must_use]
383 pub fn text_ends_with(&self, needle: &Self, mode: TextMode) -> Option<bool> {
385 self.text_op(needle, mode, |a, b| a.ends_with(b))
386 }
387
388 #[must_use]
393 pub const fn is_empty(&self) -> Option<bool> {
394 match self {
395 Self::List(xs) => Some(xs.is_empty()),
396 Self::Text(s) => Some(s.is_empty()),
397 Self::Blob(b) => Some(b.is_empty()),
398
399 Self::None => Some(true),
401
402 _ => None,
403 }
404 }
405
406 #[must_use]
407 pub fn is_not_empty(&self) -> Option<bool> {
409 self.is_empty().map(|b| !b)
410 }
411
412 #[must_use]
417 pub fn contains(&self, needle: &Self) -> Option<bool> {
419 self.contains_by(needle, |a, b| a == b)
420 }
421
422 #[must_use]
423 pub fn contains_any(&self, needles: &Self) -> Option<bool> {
425 self.contains_any_by(needles, |a, b| a == b)
426 }
427
428 #[must_use]
429 pub fn contains_all(&self, needles: &Self) -> Option<bool> {
431 self.contains_all_by(needles, |a, b| a == b)
432 }
433
434 #[must_use]
435 pub fn in_list(&self, haystack: &Self) -> Option<bool> {
437 self.in_list_by(haystack, |a, b| a == b)
438 }
439
440 #[must_use]
441 pub fn contains_ci(&self, needle: &Self) -> Option<bool> {
443 match self {
444 Self::List(_) => self.contains_by(needle, Self::eq_ci),
445 _ => Some(Self::eq_ci(self, needle)),
446 }
447 }
448
449 #[must_use]
450 pub fn contains_any_ci(&self, needles: &Self) -> Option<bool> {
452 self.contains_any_by(needles, Self::eq_ci)
453 }
454
455 #[must_use]
456 pub fn contains_all_ci(&self, needles: &Self) -> Option<bool> {
458 self.contains_all_by(needles, Self::eq_ci)
459 }
460
461 #[must_use]
462 pub fn in_list_ci(&self, haystack: &Self) -> Option<bool> {
464 self.in_list_by(haystack, Self::eq_ci)
465 }
466}
467
468#[macro_export]
469macro_rules! impl_from_for {
470 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
471 $(
472 impl From<$type> for Value {
473 fn from(v: $type) -> Self {
474 Self::$variant(v.into())
475 }
476 }
477 )*
478 };
479}
480
481impl_from_for! {
482 Account => Account,
483 Date => Date,
484 Decimal => Decimal,
485 Duration => Duration,
486 E8s => E8s,
487 E18s => E18s,
488 bool => Bool,
489 i8 => Int,
490 i16 => Int,
491 i32 => Int,
492 i64 => Int,
493 i128 => Int128,
494 Int => IntBig,
495 Principal => Principal,
496 Subaccount => Subaccount,
497 &str => Text,
498 String => Text,
499 Timestamp => Timestamp,
500 u8 => Uint,
501 u16 => Uint,
502 u32 => Uint,
503 u64 => Uint,
504 u128 => Uint128,
505 Nat => UintBig,
506 Ulid => Ulid,
507}
508
509impl ValueFamilyExt for Value {
510 fn family(&self) -> ValueFamily {
511 match self {
512 Self::Date(_)
514 | Self::Decimal(_)
515 | Self::Duration(_)
516 | Self::E8s(_)
517 | Self::E18s(_)
518 | Self::Float32(_)
519 | Self::Float64(_)
520 | Self::Int(_)
521 | Self::Int128(_)
522 | Self::Timestamp(_)
523 | Self::Uint(_)
524 | Self::Uint128(_)
525 | Self::IntBig(_)
526 | Self::UintBig(_) => ValueFamily::Numeric,
527
528 Self::Text(_) => ValueFamily::Textual,
530
531 Self::Ulid(_) | Self::Principal(_) | Self::Account(_) => ValueFamily::Identifier,
533
534 Self::Enum(_) => ValueFamily::Enum,
536
537 Self::List(_) => ValueFamily::Collection,
539
540 Self::Blob(_) | Self::Subaccount(_) => ValueFamily::Blob,
542
543 Self::Bool(_) => ValueFamily::Bool,
545
546 Self::None => ValueFamily::Null,
548 Self::Unit => ValueFamily::Unit,
549
550 Self::Unsupported => ValueFamily::Unsupported,
552 }
553 }
554}
555
556impl FieldValue for Value {
557 fn to_value(&self) -> Value {
558 self.clone()
559 }
560}
561
562impl From<Vec<Self>> for Value {
563 fn from(vec: Vec<Self>) -> Self {
564 Self::List(vec)
565 }
566}
567
568impl From<()> for Value {
569 fn from((): ()) -> Self {
570 Self::Unit
571 }
572}
573
574impl PartialOrd for Value {
575 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
576 match (self, other) {
577 (Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
578 (Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
579 (Self::Decimal(a), Self::Decimal(b)) => a.partial_cmp(b),
580 (Self::Duration(a), Self::Duration(b)) => a.partial_cmp(b),
581 (Self::E8s(a), Self::E8s(b)) => a.partial_cmp(b),
582 (Self::E18s(a), Self::E18s(b)) => a.partial_cmp(b),
583 (Self::Enum(a), Self::Enum(b)) => a.partial_cmp(b),
584 (Self::Float32(a), Self::Float32(b)) => a.partial_cmp(b),
585 (Self::Float64(a), Self::Float64(b)) => a.partial_cmp(b),
586 (Self::Int(a), Self::Int(b)) => a.partial_cmp(b),
587 (Self::Int128(a), Self::Int128(b)) => a.partial_cmp(b),
588 (Self::IntBig(a), Self::IntBig(b)) => a.partial_cmp(b),
589 (Self::Principal(a), Self::Principal(b)) => a.partial_cmp(b),
590 (Self::Subaccount(a), Self::Subaccount(b)) => a.partial_cmp(b),
591 (Self::Text(a), Self::Text(b)) => a.partial_cmp(b),
592 (Self::Timestamp(a), Self::Timestamp(b)) => a.partial_cmp(b),
593 (Self::Uint(a), Self::Uint(b)) => a.partial_cmp(b),
594 (Self::Uint128(a), Self::Uint128(b)) => a.partial_cmp(b),
595 (Self::UintBig(a), Self::UintBig(b)) => a.partial_cmp(b),
596 (Self::Ulid(a), Self::Ulid(b)) => a.partial_cmp(b),
597
598 _ => None,
600 }
601 }
602}
603
604#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd, Serialize)]
610pub struct ValueEnum {
611 pub variant: String,
612 pub path: Option<String>,
613 pub payload: Option<Box<Value>>,
614}
615
616impl ValueEnum {
617 #[must_use]
618 pub fn new(variant: &str, path: Option<&str>) -> Self {
620 Self {
621 variant: variant.to_string(),
622 path: path.map(ToString::to_string),
623 payload: None,
624 }
625 }
626
627 #[must_use]
628 pub fn strict<E: Path>(variant: &str) -> Self {
630 Self::new(variant, Some(E::PATH))
631 }
632
633 #[must_use]
634 pub fn from_enum<E: EnumValue>(value: E) -> Self {
636 value.to_value_enum()
637 }
638
639 #[must_use]
640 pub fn loose(variant: &str) -> Self {
642 Self::new(variant, None)
643 }
644
645 #[must_use]
646 pub fn with_payload(mut self, payload: Value) -> Self {
648 self.payload = Some(Box::new(payload));
649 self
650 }
651}