1#[macro_use]
8mod macros;
9mod numeric_value;
10mod visitor;
11
12use crate::{
13 error::InternalError,
14 model::field::{FieldKind, FieldModel, FieldStorageDecode},
15 prelude::*,
16 types::{EntityTag, Id},
17 value::{StorageKey, StorageKeyEncodeError, Value, ValueEnum},
18 visitor::VisitorContext,
19};
20use std::collections::{BTreeMap, BTreeSet};
21
22pub use numeric_value::*;
23pub use visitor::*;
24
25pub use canic_cdk::structures::storable::Storable;
30pub use serde::{Deserialize, Serialize, de::DeserializeOwned};
31pub use std::{
32 cmp::{Eq, Ordering, PartialEq},
33 convert::From,
34 default::Default,
35 fmt::Debug,
36 hash::Hash,
37 ops::{Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Rem, Sub, SubAssign},
38};
39
40pub trait Path {
54 const PATH: &'static str;
55}
56
57pub trait Kind: Path + 'static {}
63impl<T> Kind for T where T: Path + 'static {}
64
65pub trait CanisterKind: Kind {
71 const COMMIT_MEMORY_ID: u8;
73}
74
75pub trait StoreKind: Kind {
81 type Canister: CanisterKind;
82}
83
84pub trait EntityKey {
106 type Key: Copy
107 + Debug
108 + Eq
109 + Ord
110 + KeyValueCodec
111 + StorageKeyCodec
112 + StorageKeyDecode
113 + EntityKeyBytes
114 + 'static;
115}
116
117pub trait EntityKeyBytes {
122 const BYTE_LEN: usize;
124
125 fn write_bytes(&self, out: &mut [u8]);
127}
128
129macro_rules! impl_entity_key_bytes_numeric {
130 ($($ty:ty),* $(,)?) => {
131 $(
132 impl EntityKeyBytes for $ty {
133 const BYTE_LEN: usize = ::core::mem::size_of::<Self>();
134
135 fn write_bytes(&self, out: &mut [u8]) {
136 assert_eq!(out.len(), Self::BYTE_LEN);
137 out.copy_from_slice(&self.to_be_bytes());
138 }
139 }
140 )*
141 };
142}
143
144impl_entity_key_bytes_numeric!(i8, i16, i32, i64, u8, u16, u32, u64);
145
146impl EntityKeyBytes for () {
147 const BYTE_LEN: usize = 0;
148
149 fn write_bytes(&self, out: &mut [u8]) {
150 assert_eq!(out.len(), Self::BYTE_LEN);
151 }
152}
153
154pub trait KeyValueCodec {
164 fn to_key_value(&self) -> Value;
165
166 #[must_use]
167 fn from_key_value(value: &Value) -> Option<Self>
168 where
169 Self: Sized;
170}
171
172pub trait StorageKeyCodec {
180 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError>;
181}
182
183pub trait StorageKeyDecode: Sized {
192 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError>;
193}
194
195fn storage_key_variant_decode_failed(
196 type_name: &'static str,
197 key: StorageKey,
198 expected: &'static str,
199) -> InternalError {
200 InternalError::store_corruption(format!(
201 "storage key decode failed for `{type_name}`: expected {expected}, found {key:?}",
202 ))
203}
204
205fn storage_key_range_decode_failed(type_name: &'static str, key: StorageKey) -> InternalError {
206 InternalError::store_corruption(format!(
207 "storage key decode failed for `{type_name}`: value out of range for {key:?}",
208 ))
209}
210
211macro_rules! impl_storage_key_codec_signed {
212 ($($ty:ty),* $(,)?) => {
213 $(
214 impl StorageKeyCodec for $ty {
215 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
216 Ok(StorageKey::Int(i64::from(*self)))
217 }
218 }
219 )*
220 };
221}
222
223macro_rules! impl_storage_key_codec_unsigned {
224 ($($ty:ty),* $(,)?) => {
225 $(
226 impl StorageKeyCodec for $ty {
227 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
228 Ok(StorageKey::Uint(u64::from(*self)))
229 }
230 }
231 )*
232 };
233}
234
235impl<T> KeyValueCodec for T
236where
237 T: RuntimeValueDecode + RuntimeValueEncode,
238{
239 fn to_key_value(&self) -> Value {
240 self.to_value()
241 }
242
243 fn from_key_value(value: &Value) -> Option<Self> {
244 Self::from_value(value)
245 }
246}
247
248impl_storage_key_codec_signed!(i8, i16, i32, i64);
249impl_storage_key_codec_unsigned!(u8, u16, u32, u64);
250
251macro_rules! impl_storage_key_decode_signed {
252 ($($ty:ty),* $(,)?) => {
253 $(
254 impl StorageKeyDecode for $ty {
255 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
256 let StorageKey::Int(value) = key else {
257 return Err(storage_key_variant_decode_failed(
258 ::std::any::type_name::<Self>(),
259 key,
260 "StorageKey::Int",
261 ));
262 };
263
264 Self::try_from(value).map_err(|_| {
265 storage_key_range_decode_failed(::std::any::type_name::<Self>(), key)
266 })
267 }
268 }
269 )*
270 };
271}
272
273macro_rules! impl_storage_key_decode_unsigned {
274 ($($ty:ty),* $(,)?) => {
275 $(
276 impl StorageKeyDecode for $ty {
277 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
278 let StorageKey::Uint(value) = key else {
279 return Err(storage_key_variant_decode_failed(
280 ::std::any::type_name::<Self>(),
281 key,
282 "StorageKey::Uint",
283 ));
284 };
285
286 Self::try_from(value).map_err(|_| {
287 storage_key_range_decode_failed(::std::any::type_name::<Self>(), key)
288 })
289 }
290 }
291 )*
292 };
293}
294
295impl_storage_key_decode_signed!(i8, i16, i32, i64);
296impl_storage_key_decode_unsigned!(u8, u16, u32, u64);
297
298impl StorageKeyCodec for crate::types::Principal {
299 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
300 Ok(StorageKey::Principal(*self))
301 }
302}
303
304impl StorageKeyDecode for crate::types::Principal {
305 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
306 match key {
307 StorageKey::Principal(value) => Ok(value),
308 other => Err(storage_key_variant_decode_failed(
309 ::std::any::type_name::<Self>(),
310 other,
311 "StorageKey::Principal",
312 )),
313 }
314 }
315}
316
317impl StorageKeyCodec for crate::types::Subaccount {
318 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
319 Ok(StorageKey::Subaccount(*self))
320 }
321}
322
323impl StorageKeyDecode for crate::types::Subaccount {
324 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
325 match key {
326 StorageKey::Subaccount(value) => Ok(value),
327 other => Err(storage_key_variant_decode_failed(
328 ::std::any::type_name::<Self>(),
329 other,
330 "StorageKey::Subaccount",
331 )),
332 }
333 }
334}
335
336impl StorageKeyCodec for crate::types::Account {
337 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
338 Ok(StorageKey::Account(*self))
339 }
340}
341
342impl StorageKeyDecode for crate::types::Account {
343 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
344 match key {
345 StorageKey::Account(value) => Ok(value),
346 other => Err(storage_key_variant_decode_failed(
347 ::std::any::type_name::<Self>(),
348 other,
349 "StorageKey::Account",
350 )),
351 }
352 }
353}
354
355impl StorageKeyCodec for crate::types::Timestamp {
356 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
357 Ok(StorageKey::Timestamp(*self))
358 }
359}
360
361impl StorageKeyDecode for crate::types::Timestamp {
362 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
363 match key {
364 StorageKey::Timestamp(value) => Ok(value),
365 other => Err(storage_key_variant_decode_failed(
366 ::std::any::type_name::<Self>(),
367 other,
368 "StorageKey::Timestamp",
369 )),
370 }
371 }
372}
373
374impl StorageKeyCodec for crate::types::Ulid {
375 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
376 Ok(StorageKey::Ulid(*self))
377 }
378}
379
380impl StorageKeyDecode for crate::types::Ulid {
381 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
382 match key {
383 StorageKey::Ulid(value) => Ok(value),
384 other => Err(storage_key_variant_decode_failed(
385 ::std::any::type_name::<Self>(),
386 other,
387 "StorageKey::Ulid",
388 )),
389 }
390 }
391}
392
393impl StorageKeyCodec for () {
394 fn to_storage_key(&self) -> Result<StorageKey, StorageKeyEncodeError> {
395 Ok(StorageKey::Unit)
396 }
397}
398
399impl StorageKeyDecode for () {
400 fn from_storage_key(key: StorageKey) -> Result<Self, InternalError> {
401 match key {
402 StorageKey::Unit => Ok(()),
403 other => Err(storage_key_variant_decode_failed(
404 ::std::any::type_name::<Self>(),
405 other,
406 "StorageKey::Unit",
407 )),
408 }
409 }
410}
411
412pub trait RuntimeValueEncode {
424 fn to_value(&self) -> Value;
425}
426
427pub trait RuntimeValueDecode {
438 #[must_use]
439 fn from_value(value: &Value) -> Option<Self>
440 where
441 Self: Sized;
442}
443
444pub fn runtime_value_to_value<T>(value: &T) -> Value
453where
454 T: ?Sized + RuntimeValueEncode,
455{
456 value.to_value()
457}
458
459#[must_use]
468pub fn runtime_value_from_value<T>(value: &Value) -> Option<T>
469where
470 T: RuntimeValueDecode,
471{
472 T::from_value(value)
473}
474
475pub trait PersistedByKindCodec: Sized {
485 fn encode_persisted_slot_payload_by_kind(
487 &self,
488 kind: FieldKind,
489 field_name: &'static str,
490 ) -> Result<Vec<u8>, InternalError>;
491
492 fn decode_persisted_option_slot_payload_by_kind(
496 bytes: &[u8],
497 kind: FieldKind,
498 field_name: &'static str,
499 ) -> Result<Option<Self>, InternalError>;
500}
501
502pub trait PersistedStructuredFieldCodec {
514 fn encode_persisted_structured_payload(&self) -> Result<Vec<u8>, InternalError>;
516
517 fn decode_persisted_structured_payload(bytes: &[u8]) -> Result<Self, InternalError>
519 where
520 Self: Sized;
521}
522
523pub trait EntitySchema: EntityKey {
534 const NAME: &'static str;
535 const MODEL: &'static EntityModel;
536}
537
538pub trait EntityPlacement {
552 type Store: StoreKind;
553 type Canister: CanisterKind;
554}
555
556pub trait EntityKind: EntitySchema + EntityPlacement + Kind + TypeKind {
566 const ENTITY_TAG: EntityTag;
567}
568
569pub trait EntityValue: EntityKey + FieldProjection + Sized {
587 fn id(&self) -> Id<Self>;
588}
589
590pub struct EntityCreateMaterialization<E> {
599 entity: E,
600 authored_slots: Vec<usize>,
601}
602
603impl<E> EntityCreateMaterialization<E> {
604 #[must_use]
606 pub const fn new(entity: E, authored_slots: Vec<usize>) -> Self {
607 Self {
608 entity,
609 authored_slots,
610 }
611 }
612
613 #[must_use]
615 pub fn into_entity(self) -> E {
616 self.entity
617 }
618
619 #[must_use]
621 pub const fn authored_slots(&self) -> &[usize] {
622 self.authored_slots.as_slice()
623 }
624}
625
626pub trait EntityCreateInput: Sized {
635 type Entity: EntityValue + Default;
636
637 fn materialize_create(self) -> EntityCreateMaterialization<Self::Entity>;
639}
640
641pub trait EntityCreateType: EntityValue {
651 type Create: EntityCreateInput<Entity = Self>;
652}
653
654pub trait SingletonEntity: EntityValue {}
656
657pub trait TypeKind:
675 Kind + Clone + Default + DeserializeOwned + Sanitize + Validate + Visitable + PartialEq
676{
677}
678
679impl<T> TypeKind for T where
680 T: Kind + Clone + Default + DeserializeOwned + PartialEq + Sanitize + Validate + Visitable
681{
682}
683
684pub trait FieldTypeMeta {
693 const KIND: FieldKind;
695
696 const STORAGE_DECODE: FieldStorageDecode;
698
699 const NESTED_FIELDS: &'static [FieldModel] = &[];
701}
702
703pub trait PersistedFieldMetaCodec: FieldTypeMeta + Sized {
714 fn encode_persisted_slot_payload_by_meta(
717 &self,
718 field_name: &'static str,
719 ) -> Result<Vec<u8>, InternalError>;
720
721 fn decode_persisted_slot_payload_by_meta(
724 bytes: &[u8],
725 field_name: &'static str,
726 ) -> Result<Self, InternalError>;
727
728 fn encode_persisted_option_slot_payload_by_meta(
731 value: &Option<Self>,
732 field_name: &'static str,
733 ) -> Result<Vec<u8>, InternalError>;
734
735 fn decode_persisted_option_slot_payload_by_meta(
738 bytes: &[u8],
739 field_name: &'static str,
740 ) -> Result<Option<Self>, InternalError>;
741}
742
743impl<T> FieldTypeMeta for Option<T>
744where
745 T: FieldTypeMeta,
746{
747 const KIND: FieldKind = T::KIND;
748 const STORAGE_DECODE: FieldStorageDecode = T::STORAGE_DECODE;
749 const NESTED_FIELDS: &'static [FieldModel] = T::NESTED_FIELDS;
750}
751
752impl<T> FieldTypeMeta for Box<T>
753where
754 T: FieldTypeMeta,
755{
756 const KIND: FieldKind = T::KIND;
757 const STORAGE_DECODE: FieldStorageDecode = T::STORAGE_DECODE;
758 const NESTED_FIELDS: &'static [FieldModel] = T::NESTED_FIELDS;
759}
760
761impl<T> FieldTypeMeta for Vec<T>
765where
766 T: FieldTypeMeta,
767{
768 const KIND: FieldKind = FieldKind::List(&T::KIND);
769 const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
770}
771
772impl<T> FieldTypeMeta for BTreeSet<T>
773where
774 T: FieldTypeMeta,
775{
776 const KIND: FieldKind = FieldKind::Set(&T::KIND);
777 const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
778}
779
780impl<K, V> FieldTypeMeta for BTreeMap<K, V>
781where
782 K: FieldTypeMeta,
783 V: FieldTypeMeta,
784{
785 const KIND: FieldKind = FieldKind::Map {
786 key: &K::KIND,
787 value: &V::KIND,
788 };
789 const STORAGE_DECODE: FieldStorageDecode = FieldStorageDecode::Value;
790}
791
792pub trait Collection {
805 type Item;
806
807 type Iter<'a>: Iterator<Item = &'a Self::Item> + 'a
809 where
810 Self: 'a;
811
812 fn iter(&self) -> Self::Iter<'_>;
814
815 fn len(&self) -> usize;
817
818 fn is_empty(&self) -> bool {
820 self.len() == 0
821 }
822}
823
824pub trait MapCollection {
833 type Key;
834 type Value;
835
836 type Iter<'a>: Iterator<Item = (&'a Self::Key, &'a Self::Value)> + 'a
838 where
839 Self: 'a;
840
841 fn iter(&self) -> Self::Iter<'_>;
843
844 fn len(&self) -> usize;
846
847 fn is_empty(&self) -> bool {
849 self.len() == 0
850 }
851}
852
853impl<T> Collection for Vec<T> {
854 type Item = T;
855 type Iter<'a>
856 = std::slice::Iter<'a, T>
857 where
858 Self: 'a;
859
860 fn iter(&self) -> Self::Iter<'_> {
861 self.as_slice().iter()
862 }
863
864 fn len(&self) -> usize {
865 self.as_slice().len()
866 }
867}
868
869impl<T> Collection for BTreeSet<T> {
870 type Item = T;
871 type Iter<'a>
872 = std::collections::btree_set::Iter<'a, T>
873 where
874 Self: 'a;
875
876 fn iter(&self) -> Self::Iter<'_> {
877 self.iter()
878 }
879
880 fn len(&self) -> usize {
881 self.len()
882 }
883}
884
885impl<K, V> MapCollection for BTreeMap<K, V> {
886 type Key = K;
887 type Value = V;
888 type Iter<'a>
889 = std::collections::btree_map::Iter<'a, K, V>
890 where
891 Self: 'a;
892
893 fn iter(&self) -> Self::Iter<'_> {
894 self.iter()
895 }
896
897 fn len(&self) -> usize {
898 self.len()
899 }
900}
901
902pub trait EnumValue {
903 fn to_value_enum(&self) -> ValueEnum;
904}
905
906pub trait FieldProjection {
907 fn get_value_by_index(&self, index: usize) -> Option<Value>;
909}
910
911#[derive(Clone, Copy, Debug, Eq, PartialEq)]
919pub enum RuntimeValueKind {
920 Atomic,
922
923 Structured {
926 queryable: bool,
928 },
929}
930
931impl RuntimeValueKind {
932 #[must_use]
933 pub const fn is_queryable(self) -> bool {
934 match self {
935 Self::Atomic => true,
936 Self::Structured { queryable } => queryable,
937 }
938 }
939}
940
941pub trait RuntimeValueMeta {
950 fn kind() -> RuntimeValueKind
951 where
952 Self: Sized;
953}
954
955pub fn runtime_value_collection_to_value<C>(collection: &C) -> Value
964where
965 C: Collection,
966 C::Item: RuntimeValueEncode,
967{
968 Value::List(
969 collection
970 .iter()
971 .map(RuntimeValueEncode::to_value)
972 .collect(),
973 )
974}
975
976#[must_use]
985pub fn runtime_value_vec_from_value<T>(value: &Value) -> Option<Vec<T>>
986where
987 T: RuntimeValueDecode,
988{
989 let Value::List(values) = value else {
990 return None;
991 };
992
993 let mut out = Vec::with_capacity(values.len());
994 for value in values {
995 out.push(T::from_value(value)?);
996 }
997
998 Some(out)
999}
1000
1001#[must_use]
1010pub fn runtime_value_btree_set_from_value<T>(value: &Value) -> Option<BTreeSet<T>>
1011where
1012 T: Ord + RuntimeValueDecode,
1013{
1014 let Value::List(values) = value else {
1015 return None;
1016 };
1017
1018 let mut out = BTreeSet::new();
1019 for value in values {
1020 let item = T::from_value(value)?;
1021 if !out.insert(item) {
1022 return None;
1023 }
1024 }
1025
1026 Some(out)
1027}
1028
1029pub fn runtime_value_map_collection_to_value<M>(map: &M, path: &'static str) -> Value
1039where
1040 M: MapCollection,
1041 M::Key: RuntimeValueEncode,
1042 M::Value: RuntimeValueEncode,
1043{
1044 let mut entries: Vec<(Value, Value)> = map
1045 .iter()
1046 .map(|(key, value)| {
1047 (
1048 RuntimeValueEncode::to_value(key),
1049 RuntimeValueEncode::to_value(value),
1050 )
1051 })
1052 .collect();
1053
1054 if let Err(err) = Value::validate_map_entries(entries.as_slice()) {
1055 debug_assert!(false, "invalid map field value for {path}: {err}");
1056 return Value::Map(entries);
1057 }
1058
1059 Value::sort_map_entries_in_place(entries.as_mut_slice());
1060
1061 for i in 1..entries.len() {
1062 let (left_key, _) = &entries[i - 1];
1063 let (right_key, _) = &entries[i];
1064 if Value::canonical_cmp_key(left_key, right_key) == Ordering::Equal {
1065 debug_assert!(
1066 false,
1067 "duplicate map key in {path} after value-surface canonicalization",
1068 );
1069 break;
1070 }
1071 }
1072
1073 Value::Map(entries)
1074}
1075
1076#[must_use]
1085pub fn runtime_value_btree_map_from_value<K, V>(value: &Value) -> Option<BTreeMap<K, V>>
1086where
1087 K: Ord + RuntimeValueDecode,
1088 V: RuntimeValueDecode,
1089{
1090 let Value::Map(entries) = value else {
1091 return None;
1092 };
1093
1094 let normalized = Value::normalize_map_entries(entries.clone()).ok()?;
1095 if normalized.as_slice() != entries.as_slice() {
1096 return None;
1097 }
1098
1099 let mut map = BTreeMap::new();
1100 for (entry_key, entry_value) in normalized {
1101 let key = K::from_value(&entry_key)?;
1102 let value = V::from_value(&entry_value)?;
1103 map.insert(key, value);
1104 }
1105
1106 Some(map)
1107}
1108
1109#[must_use]
1118pub fn runtime_value_from_vec_into<T, I>(entries: Vec<I>) -> Vec<T>
1119where
1120 I: Into<T>,
1121{
1122 entries.into_iter().map(Into::into).collect()
1123}
1124
1125#[must_use]
1134pub fn runtime_value_from_vec_into_btree_set<T, I>(entries: Vec<I>) -> BTreeSet<T>
1135where
1136 I: Into<T>,
1137 T: Ord,
1138{
1139 entries.into_iter().map(Into::into).collect()
1140}
1141
1142#[must_use]
1151pub fn runtime_value_from_vec_into_btree_map<K, V, IK, IV>(entries: Vec<(IK, IV)>) -> BTreeMap<K, V>
1152where
1153 IK: Into<K>,
1154 IV: Into<V>,
1155 K: Ord,
1156{
1157 entries
1158 .into_iter()
1159 .map(|(key, value)| (key.into(), value.into()))
1160 .collect()
1161}
1162
1163#[must_use]
1172pub fn runtime_value_into<T, U>(value: U) -> T
1173where
1174 U: Into<T>,
1175{
1176 value.into()
1177}
1178
1179impl RuntimeValueMeta for &str {
1180 fn kind() -> RuntimeValueKind {
1181 RuntimeValueKind::Atomic
1182 }
1183}
1184
1185impl RuntimeValueEncode for &str {
1186 fn to_value(&self) -> Value {
1187 Value::Text((*self).to_string())
1188 }
1189}
1190
1191impl RuntimeValueDecode for &str {
1192 fn from_value(_value: &Value) -> Option<Self> {
1193 None
1194 }
1195}
1196
1197impl RuntimeValueMeta for String {
1198 fn kind() -> RuntimeValueKind {
1199 RuntimeValueKind::Atomic
1200 }
1201}
1202
1203impl RuntimeValueEncode for String {
1204 fn to_value(&self) -> Value {
1205 Value::Text(self.clone())
1206 }
1207}
1208
1209impl RuntimeValueDecode for String {
1210 fn from_value(value: &Value) -> Option<Self> {
1211 match value {
1212 Value::Text(v) => Some(v.clone()),
1213 _ => None,
1214 }
1215 }
1216}
1217
1218impl<T: RuntimeValueMeta> RuntimeValueMeta for Option<T> {
1219 fn kind() -> RuntimeValueKind {
1220 T::kind()
1221 }
1222}
1223
1224impl<T: RuntimeValueEncode> RuntimeValueEncode for Option<T> {
1225 fn to_value(&self) -> Value {
1226 match self {
1227 Some(v) => v.to_value(),
1228 None => Value::Null,
1229 }
1230 }
1231}
1232
1233impl<T: RuntimeValueDecode> RuntimeValueDecode for Option<T> {
1234 fn from_value(value: &Value) -> Option<Self> {
1235 if matches!(value, Value::Null) {
1236 return Some(None);
1237 }
1238
1239 T::from_value(value).map(Some)
1240 }
1241}
1242
1243impl<T: RuntimeValueMeta> RuntimeValueMeta for Box<T> {
1244 fn kind() -> RuntimeValueKind {
1245 T::kind()
1246 }
1247}
1248
1249impl<T: RuntimeValueEncode> RuntimeValueEncode for Box<T> {
1250 fn to_value(&self) -> Value {
1251 (**self).to_value()
1252 }
1253}
1254
1255impl<T: RuntimeValueDecode> RuntimeValueDecode for Box<T> {
1256 fn from_value(value: &Value) -> Option<Self> {
1257 T::from_value(value).map(Self::new)
1258 }
1259}
1260
1261impl<T> RuntimeValueMeta for Vec<T> {
1262 fn kind() -> RuntimeValueKind {
1263 RuntimeValueKind::Structured { queryable: true }
1264 }
1265}
1266
1267impl<T: RuntimeValueEncode> RuntimeValueEncode for Vec<T> {
1268 fn to_value(&self) -> Value {
1269 runtime_value_collection_to_value(self)
1270 }
1271}
1272
1273impl<T: RuntimeValueDecode> RuntimeValueDecode for Vec<T> {
1274 fn from_value(value: &Value) -> Option<Self> {
1275 runtime_value_vec_from_value(value)
1276 }
1277}
1278
1279impl<T> RuntimeValueMeta for BTreeSet<T>
1280where
1281 T: Ord,
1282{
1283 fn kind() -> RuntimeValueKind {
1284 RuntimeValueKind::Structured { queryable: true }
1285 }
1286}
1287
1288impl<T> RuntimeValueEncode for BTreeSet<T>
1289where
1290 T: Ord + RuntimeValueEncode,
1291{
1292 fn to_value(&self) -> Value {
1293 runtime_value_collection_to_value(self)
1294 }
1295}
1296
1297impl<T> RuntimeValueDecode for BTreeSet<T>
1298where
1299 T: Ord + RuntimeValueDecode,
1300{
1301 fn from_value(value: &Value) -> Option<Self> {
1302 runtime_value_btree_set_from_value(value)
1303 }
1304}
1305
1306impl<K, V> RuntimeValueMeta for BTreeMap<K, V>
1307where
1308 K: Ord,
1309{
1310 fn kind() -> RuntimeValueKind {
1311 RuntimeValueKind::Structured { queryable: true }
1312 }
1313}
1314
1315impl<K, V> RuntimeValueEncode for BTreeMap<K, V>
1316where
1317 K: Ord + RuntimeValueEncode,
1318 V: RuntimeValueEncode,
1319{
1320 fn to_value(&self) -> Value {
1321 runtime_value_map_collection_to_value(self, std::any::type_name::<Self>())
1322 }
1323}
1324
1325impl<K, V> RuntimeValueDecode for BTreeMap<K, V>
1326where
1327 K: Ord + RuntimeValueDecode,
1328 V: RuntimeValueDecode,
1329{
1330 fn from_value(value: &Value) -> Option<Self> {
1331 runtime_value_btree_map_from_value(value)
1332 }
1333}
1334
1335#[macro_export]
1337macro_rules! impl_runtime_value {
1338 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
1339 $(
1340 impl RuntimeValueMeta for $type {
1341 fn kind() -> RuntimeValueKind {
1342 RuntimeValueKind::Atomic
1343 }
1344 }
1345
1346 impl RuntimeValueEncode for $type {
1347 fn to_value(&self) -> Value {
1348 Value::$variant((*self).into())
1349 }
1350 }
1351
1352 impl RuntimeValueDecode for $type {
1353 fn from_value(value: &Value) -> Option<Self> {
1354 match value {
1355 Value::$variant(v) => (*v).try_into().ok(),
1356 _ => None,
1357 }
1358 }
1359 }
1360 )*
1361 };
1362}
1363
1364impl_runtime_value!(
1365 i8 => Int,
1366 i16 => Int,
1367 i32 => Int,
1368 i64 => Int,
1369 u8 => Uint,
1370 u16 => Uint,
1371 u32 => Uint,
1372 u64 => Uint,
1373 bool => Bool,
1374);
1375
1376pub trait Inner<T> {
1387 fn inner(&self) -> &T;
1388 fn into_inner(self) -> T;
1389}
1390
1391pub trait Repr {
1398 type Inner;
1399
1400 fn repr(&self) -> Self::Inner;
1401 fn from_repr(inner: Self::Inner) -> Self;
1402}
1403
1404pub trait Sanitizer<T> {
1415 fn sanitize(&self, value: &mut T) -> Result<(), String>;
1416
1417 fn sanitize_with_context(
1418 &self,
1419 value: &mut T,
1420 ctx: &mut dyn VisitorContext,
1421 ) -> Result<(), String> {
1422 let _ = ctx;
1423
1424 self.sanitize(value)
1425 }
1426}
1427
1428pub trait Validator<T: ?Sized> {
1435 fn validate(&self, value: &T, ctx: &mut dyn VisitorContext);
1436}