1use std::collections::HashSet;
4use std::convert::{TryFrom, TryInto};
5use std::fmt;
6use std::str::FromStr;
7
8use async_trait::async_trait;
9use bytes::Bytes;
10use destream::de;
11use destream::ArrayAccess;
12use futures::future::TryFutureExt;
13use futures::stream::{StreamExt, TryStreamExt};
14use log::debug;
15use safecast::*;
16
17#[cfg(feature = "chain")]
18use tc_chain::ChainVisitor;
19#[cfg(feature = "collection")]
20use tc_collection::{CollectionType, CollectionVisitor};
21use tc_error::*;
22use tc_scalar::*;
23use tc_transact::hash::{AsyncHash, Hash, Output, Sha256};
24use tc_transact::public::{ClosureInstance, Public, StateInstance, ToState};
25use tc_transact::{Gateway, Transaction, TxnId};
26use tc_value::{Float, Host, Link, Number, NumberType, TCString, Value, ValueType};
27use tcgeneric::{
28 label, path_label, Class, Id, Instance, Label, Map, NativeClass, PathLabel, PathSegment,
29 TCPath, TCPathBuf, Tuple,
30};
31
32use closure::*;
33use object::{InstanceClass, Object, ObjectType, ObjectVisitor};
34
35pub use block::CacheBlock;
36#[cfg(feature = "chain")]
37pub use chain::*;
38#[cfg(feature = "collection")]
39pub use collection::*;
40
41mod block;
42pub mod closure;
43pub mod object;
44pub mod public;
45pub mod view;
46
47pub const PREFIX: PathLabel = path_label(&["state"]);
49
50#[cfg(feature = "chain")]
51pub mod chain {
52 use crate::{CacheBlock, State};
53
54 pub use tc_chain::{ChainType, Recover};
55
56 pub type Chain<Txn, T> = tc_chain::Chain<State<Txn>, Txn, CacheBlock, T>;
57 pub type BlockChain<Txn, T> = tc_chain::BlockChain<State<Txn>, Txn, CacheBlock, T>;
58 pub type SyncChain<Txn, T> = tc_chain::SyncChain<State<Txn>, Txn, CacheBlock, T>;
59}
60
61#[cfg(feature = "collection")]
62pub mod collection {
63 use crate::CacheBlock;
64
65 pub use tc_collection::Schema;
66
67 #[cfg(feature = "btree")]
68 pub use tc_collection::btree::{BTreeSchema, BTreeType};
69 #[cfg(all(feature = "table", not(feature = "btree")))]
70 pub(crate) use tc_collection::btree::{BTreeSchema, BTreeType};
71 #[cfg(feature = "table")]
72 pub use tc_collection::table::{TableSchema, TableType};
73 #[cfg(feature = "tensor")]
74 pub use tc_collection::tensor::TensorType;
75
76 pub type Collection<Txn> = tc_collection::Collection<Txn, CacheBlock>;
77 pub type CollectionBase<Txn> = tc_collection::CollectionBase<Txn, CacheBlock>;
78
79 #[cfg(feature = "btree")]
80 pub type BTree<Txn> = tc_collection::BTree<Txn, CacheBlock>;
81 #[cfg(feature = "btree")]
82 pub type BTreeFile<Txn> = tc_collection::BTreeFile<Txn, CacheBlock>;
83 #[cfg(all(any(feature = "table", feature = "tensor"), not(feature = "btree")))]
84 pub(crate) type BTree<Txn> = tc_collection::BTree<Txn, CacheBlock>;
85 #[cfg(all(feature = "table", not(feature = "btree")))]
86 pub(crate) type BTreeFile<Txn> = tc_collection::BTreeFile<Txn, CacheBlock>;
87 #[cfg(feature = "table")]
88 pub type Table<Txn> = tc_collection::Table<Txn, CacheBlock>;
89 #[cfg(feature = "table")]
90 pub type TableFile<Txn> = tc_collection::TableFile<Txn, CacheBlock>;
91 #[cfg(feature = "tensor")]
92 pub type Tensor<Txn> = tc_collection::Tensor<Txn, CacheBlock>;
93}
94
95#[derive(Copy, Clone, Eq, PartialEq)]
97pub enum StateType {
98 #[cfg(feature = "chain")]
99 Chain(ChainType),
100 #[cfg(feature = "collection")]
101 Collection(CollectionType),
102 Closure,
103 Map,
104 Object(ObjectType),
105 Scalar(ScalarType),
106 Tuple,
107}
108
109impl Class for StateType {}
110
111impl NativeClass for StateType {
112 fn from_path(path: &[PathSegment]) -> Option<Self> {
113 debug!("StateType::from_path {}", TCPath::from(path));
114
115 if path.is_empty() {
116 None
117 } else if &path[0] == "state" {
118 if path.len() == 2 {
119 match path[1].as_str() {
120 "closure" => Some(Self::Closure),
121 "map" => Some(Self::Map),
122 "tuple" => Some(Self::Tuple),
123 _ => None,
124 }
125 } else if path.len() > 2 {
126 match path[1].as_str() {
127 #[cfg(feature = "chain")]
128 "chain" => ChainType::from_path(path).map(Self::Chain),
129 #[cfg(feature = "collection")]
130 "collection" => CollectionType::from_path(path).map(Self::Collection),
131 "object" => ObjectType::from_path(path).map(Self::Object),
132 "scalar" => ScalarType::from_path(path).map(Self::Scalar),
133 _ => None,
134 }
135 } else {
136 None
137 }
138 } else {
139 None
140 }
141 }
142
143 fn path(&self) -> TCPathBuf {
144 match self {
145 #[cfg(feature = "chain")]
146 Self::Chain(ct) => ct.path(),
147 #[cfg(feature = "collection")]
148 Self::Collection(ct) => ct.path(),
149 Self::Closure => path_label(&["state", "closure"]).into(),
150 Self::Map => path_label(&["state", "map"]).into(),
151 Self::Object(ot) => ot.path(),
152 Self::Scalar(st) => st.path(),
153 Self::Tuple => path_label(&["state", "tuple"]).into(),
154 }
155 }
156}
157
158#[cfg(any(feature = "btree", feature = "table"))]
159impl From<BTreeType> for StateType {
160 fn from(btt: BTreeType) -> Self {
161 CollectionType::BTree(btt).into()
162 }
163}
164
165#[cfg(feature = "collection")]
166impl From<CollectionType> for StateType {
167 fn from(ct: CollectionType) -> Self {
168 Self::Collection(ct)
169 }
170}
171
172impl From<NumberType> for StateType {
173 fn from(nt: NumberType) -> Self {
174 ValueType::from(nt).into()
175 }
176}
177
178#[cfg(feature = "chain")]
179impl From<ChainType> for StateType {
180 fn from(ct: ChainType) -> Self {
181 Self::Chain(ct)
182 }
183}
184
185impl From<ObjectType> for StateType {
186 fn from(ot: ObjectType) -> Self {
187 Self::Object(ot)
188 }
189}
190
191impl From<ScalarType> for StateType {
192 fn from(st: ScalarType) -> Self {
193 Self::Scalar(st)
194 }
195}
196
197#[cfg(feature = "table")]
198impl From<TableType> for StateType {
199 fn from(tt: TableType) -> Self {
200 Self::Collection(tt.into())
201 }
202}
203
204#[cfg(feature = "tensor")]
205impl From<TensorType> for StateType {
206 fn from(tt: TensorType) -> Self {
207 Self::Collection(tt.into())
208 }
209}
210
211impl From<ValueType> for StateType {
212 fn from(vt: ValueType) -> Self {
213 Self::Scalar(vt.into())
214 }
215}
216
217impl TryFrom<StateType> for ScalarType {
218 type Error = TCError;
219
220 fn try_from(st: StateType) -> TCResult<Self> {
221 match st {
222 StateType::Scalar(st) => Ok(st),
223 other => Err(TCError::unexpected(other, "a Scalar class")),
224 }
225 }
226}
227
228impl fmt::Debug for StateType {
229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230 match self {
231 #[cfg(feature = "chain")]
232 Self::Chain(ct) => fmt::Debug::fmt(ct, f),
233 #[cfg(feature = "collection")]
234 Self::Collection(ct) => fmt::Debug::fmt(ct, f),
235 Self::Closure => f.write_str("closure"),
236 Self::Map => f.write_str("Map<State>"),
237 Self::Object(ot) => fmt::Debug::fmt(ot, f),
238 Self::Scalar(st) => fmt::Debug::fmt(st, f),
239 Self::Tuple => f.write_str("Tuple<State>"),
240 }
241 }
242}
243
244pub enum State<Txn> {
246 #[cfg(feature = "chain")]
247 Chain(Chain<Txn, CollectionBase<Txn>>),
248 #[cfg(feature = "collection")]
249 Collection(Collection<Txn>),
250 Closure(Closure<Txn>),
251 Map(Map<Self>),
252 Object(Object<Txn>),
253 Scalar(Scalar),
254 Tuple(Tuple<Self>),
255}
256
257impl<Txn> Clone for State<Txn> {
258 fn clone(&self) -> Self {
259 match self {
260 #[cfg(feature = "chain")]
261 Self::Chain(chain) => Self::Chain(chain.clone()),
262 #[cfg(feature = "collection")]
263 Self::Collection(collection) => Self::Collection(collection.clone()),
264 Self::Closure(closure) => Self::Closure(closure.clone()),
265 Self::Map(map) => Self::Map(map.clone()),
266 Self::Object(obj) => Self::Object(obj.clone()),
267 Self::Scalar(scalar) => Self::Scalar(scalar.clone()),
268 Self::Tuple(tuple) => Self::Tuple(tuple.clone()),
269 }
270 }
271}
272
273impl<Txn> State<Txn> {
274 pub const PREFIX: Label = label("state");
276
277 pub fn is_none(&self) -> bool {
279 match self {
280 Self::Map(map) => map.is_empty(),
281 Self::Scalar(scalar) => scalar.is_none(),
282 Self::Tuple(tuple) => tuple.is_empty(),
283 _ => false,
284 }
285 }
286
287 pub fn is_some(&self) -> bool {
289 !self.is_none()
290 }
291
292 pub fn try_into_map<Err, OnErr: Fn(Self) -> Err>(self, err: OnErr) -> Result<Map<Self>, Err> {
294 match self {
295 State::Map(states) => Ok(states),
296 State::Scalar(Scalar::Map(states)) => Ok(states
297 .into_iter()
298 .map(|(id, scalar)| (id, State::Scalar(scalar)))
299 .collect()),
300
301 other => Err((err)(other)),
302 }
303 }
304
305 pub fn try_into_tuple<Err: Fn(Self) -> TCError>(self, err: Err) -> TCResult<Tuple<Self>> {
308 match self {
309 State::Tuple(tuple) => Ok(tuple),
310 State::Scalar(Scalar::Tuple(tuple)) => {
311 Ok(tuple.into_iter().map(State::Scalar).collect())
312 }
313 State::Scalar(Scalar::Value(Value::Tuple(tuple))) => {
314 Ok(tuple.into_iter().map(State::from).collect())
315 }
316 other => Err((err)(other)),
317 }
318 }
319}
320
321impl<Txn> State<Txn>
322where
323 Txn: Transaction<CacheBlock> + Gateway<Self>,
324{
325 pub fn is_ref(&self) -> bool {
327 match self {
328 Self::Map(map) => map.values().any(Self::is_ref),
329 Self::Scalar(scalar) => Refer::<Self>::is_ref(scalar),
330 Self::Tuple(tuple) => tuple.iter().any(Self::is_ref),
331 _ => false,
332 }
333 }
334}
335
336impl<Txn> StateInstance for State<Txn>
337where
338 Txn: Transaction<CacheBlock> + Gateway<Self>,
339{
340 type FE = CacheBlock;
341 type Txn = Txn;
342 type Closure = Closure<Txn>;
343
344 fn is_map(&self) -> bool {
345 match self {
346 Self::Scalar(scalar) => scalar.is_map(),
347 Self::Map(_) => true,
348 _ => false,
349 }
350 }
351
352 fn is_tuple(&self) -> bool {
353 match self {
354 Self::Scalar(scalar) => scalar.is_tuple(),
355 Self::Tuple(_) => true,
356 _ => false,
357 }
358 }
359}
360
361#[async_trait]
362impl<Txn> Refer<Self> for State<Txn>
363where
364 Txn: Transaction<CacheBlock> + Gateway<Self>,
365{
366 fn dereference_self(self, path: &TCPathBuf) -> Self {
367 match self {
368 Self::Closure(closure) => Self::Closure(closure.dereference_self(path)),
369 Self::Map(map) => {
370 let map = map
371 .into_iter()
372 .map(|(id, state)| (id, state.dereference_self(path)))
373 .collect();
374
375 Self::Map(map)
376 }
377 Self::Scalar(scalar) => Self::Scalar(Refer::<Self>::dereference_self(scalar, path)),
378 Self::Tuple(tuple) => {
379 let tuple = tuple
380 .into_iter()
381 .map(|state| state.dereference_self(path))
382 .collect();
383
384 Self::Tuple(tuple)
385 }
386 other => other,
387 }
388 }
389
390 fn is_conditional(&self) -> bool {
391 match self {
392 Self::Map(map) => map.values().any(|state| state.is_conditional()),
393 Self::Scalar(scalar) => Refer::<Self>::is_conditional(scalar),
394 Self::Tuple(tuple) => tuple.iter().any(|state| state.is_conditional()),
395 _ => false,
396 }
397 }
398
399 fn is_inter_service_write(&self, cluster_path: &[PathSegment]) -> bool {
400 match self {
401 Self::Closure(closure) => closure.is_inter_service_write(cluster_path),
402 Self::Map(map) => map
403 .values()
404 .any(|state| state.is_inter_service_write(cluster_path)),
405
406 Self::Scalar(scalar) => Refer::<Self>::is_inter_service_write(scalar, cluster_path),
407
408 Self::Tuple(tuple) => tuple
409 .iter()
410 .any(|state| state.is_inter_service_write(cluster_path)),
411
412 _ => false,
413 }
414 }
415
416 fn is_ref(&self) -> bool {
417 match self {
418 Self::Map(map) => map.values().any(|state| state.is_ref()),
419 Self::Scalar(scalar) => Refer::<Self>::is_ref(scalar),
420 Self::Tuple(tuple) => tuple.iter().any(|state| state.is_ref()),
421 _ => false,
422 }
423 }
424
425 fn reference_self(self, path: &TCPathBuf) -> Self {
426 match self {
427 Self::Closure(closure) => Self::Closure(closure.reference_self(path)),
428 Self::Map(map) => {
429 let map = map
430 .into_iter()
431 .map(|(id, state)| (id, state.reference_self(path)))
432 .collect();
433
434 Self::Map(map)
435 }
436 Self::Scalar(scalar) => Self::Scalar(Refer::<Self>::reference_self(scalar, path)),
437 Self::Tuple(tuple) => {
438 let tuple = tuple
439 .into_iter()
440 .map(|state| state.reference_self(path))
441 .collect();
442
443 Self::Tuple(tuple)
444 }
445 other => other,
446 }
447 }
448
449 fn requires(&self, deps: &mut HashSet<Id>) {
450 match self {
451 Self::Map(map) => {
452 for state in map.values() {
453 state.requires(deps);
454 }
455 }
456 Self::Scalar(scalar) => Refer::<Self>::requires(scalar, deps),
457 Self::Tuple(tuple) => {
458 for state in tuple.iter() {
459 state.requires(deps);
460 }
461 }
462 _ => {}
463 }
464 }
465
466 async fn resolve<'a, T: ToState<Self> + Instance + Public<Self>>(
467 self,
468 context: &'a Scope<'a, Self, T>,
469 txn: &'a Txn,
470 ) -> TCResult<Self> {
471 debug!("State::resolve {:?}", self);
472
473 match self {
474 Self::Map(map) => {
475 let mut resolved = futures::stream::iter(map)
476 .map(|(id, state)| state.resolve(context, txn).map_ok(|state| (id, state)))
477 .buffer_unordered(num_cpus::get());
478
479 let mut map = Map::new();
480 while let Some((id, state)) = resolved.try_next().await? {
481 map.insert(id, state);
482 }
483
484 Ok(State::Map(map))
485 }
486 Self::Scalar(scalar) => scalar.resolve(context, txn).await,
487 Self::Tuple(tuple) => {
488 let len = tuple.len();
489 let mut resolved = futures::stream::iter(tuple)
490 .map(|state| state.resolve(context, txn))
491 .buffered(num_cpus::get());
492
493 let mut tuple = Vec::with_capacity(len);
494 while let Some(state) = resolved.try_next().await? {
495 tuple.push(state);
496 }
497
498 Ok(State::Tuple(tuple.into()))
499 }
500 other => Ok(other),
501 }
502 }
503}
504
505impl<Txn> Default for State<Txn> {
506 fn default() -> Self {
507 Self::Scalar(Scalar::default())
508 }
509}
510
511impl<Txn> Instance for State<Txn>
512where
513 Txn: Send + Sync,
514{
515 type Class = StateType;
516
517 fn class(&self) -> StateType {
518 match self {
519 #[cfg(feature = "chain")]
520 Self::Chain(chain) => StateType::Chain(chain.class()),
521 Self::Closure(_) => StateType::Closure,
522 #[cfg(feature = "collection")]
523 Self::Collection(collection) => StateType::Collection(collection.class()),
524 Self::Map(_) => StateType::Map,
525 Self::Object(object) => StateType::Object(object.class()),
526 Self::Scalar(scalar) => StateType::Scalar(scalar.class()),
527 Self::Tuple(_) => StateType::Tuple,
528 }
529 }
530}
531
532#[async_trait]
533impl<Txn> AsyncHash for State<Txn>
534where
535 Txn: Transaction<CacheBlock> + Gateway<Self>,
536{
537 async fn hash(&self, txn_id: TxnId) -> TCResult<Output<Sha256>> {
538 match self {
539 #[cfg(feature = "chain")]
540 Self::Chain(chain) => chain.hash(txn_id).await,
541 Self::Closure(closure) => closure.hash(txn_id).await,
542 #[cfg(feature = "collection")]
543 Self::Collection(collection) => collection.hash(txn_id).await,
544 Self::Map(map) => map.hash(txn_id).await,
545 Self::Object(object) => object.hash(txn_id).await,
546 Self::Scalar(scalar) => Ok(Hash::<Sha256>::hash(scalar)),
547 Self::Tuple(tuple) => tuple.hash(txn_id).await,
548 }
549 }
550}
551
552impl<Txn> From<()> for State<Txn> {
553 fn from(_: ()) -> Self {
554 State::Scalar(Scalar::Value(Value::None))
555 }
556}
557
558#[cfg(feature = "btree")]
559impl<Txn> From<BTree<Txn>> for State<Txn> {
560 fn from(btree: BTree<Txn>) -> Self {
561 Self::Collection(btree.into())
562 }
563}
564
565#[cfg(feature = "chain")]
566impl<Txn> From<Chain<Txn, CollectionBase<Txn>>> for State<Txn> {
567 fn from(chain: Chain<Txn, CollectionBase<Txn>>) -> Self {
568 Self::Chain(chain)
569 }
570}
571
572#[cfg(feature = "chain")]
573impl<Txn> From<BlockChain<Txn, CollectionBase<Txn>>> for State<Txn> {
574 fn from(chain: BlockChain<Txn, CollectionBase<Txn>>) -> Self {
575 Self::Chain(chain.into())
576 }
577}
578
579impl<Txn> From<Closure<Txn>> for State<Txn> {
580 fn from(closure: Closure<Txn>) -> Self {
581 Self::Closure(closure)
582 }
583}
584
585#[cfg(feature = "collection")]
586impl<Txn> From<Collection<Txn>> for State<Txn> {
587 fn from(collection: Collection<Txn>) -> Self {
588 Self::Collection(collection)
589 }
590}
591
592#[cfg(feature = "collection")]
593impl<Txn> From<CollectionBase<Txn>> for State<Txn> {
594 fn from(collection: CollectionBase<Txn>) -> Self {
595 Self::Collection(collection.into())
596 }
597}
598
599impl<Txn> From<Id> for State<Txn> {
600 fn from(id: Id) -> Self {
601 Self::Scalar(id.into())
602 }
603}
604
605impl<Txn> From<InstanceClass> for State<Txn> {
606 fn from(class: InstanceClass) -> Self {
607 Self::Object(class.into())
608 }
609}
610
611impl<Txn> From<Host> for State<Txn> {
612 fn from(host: Host) -> Self {
613 Self::Scalar(Scalar::from(host))
614 }
615}
616
617impl<Txn> From<Link> for State<Txn> {
618 fn from(link: Link) -> Self {
619 Self::Scalar(Scalar::from(link))
620 }
621}
622
623impl<Txn> From<Map<InstanceClass>> for State<Txn> {
624 fn from(map: Map<InstanceClass>) -> Self {
625 Self::Map(
626 map.into_iter()
627 .map(|(id, class)| (id, State::from(class)))
628 .collect(),
629 )
630 }
631}
632
633impl<Txn> From<Map<State<Txn>>> for State<Txn> {
634 fn from(map: Map<State<Txn>>) -> Self {
635 State::Map(map)
636 }
637}
638
639impl<Txn> From<Map<Scalar>> for State<Txn> {
640 fn from(map: Map<Scalar>) -> Self {
641 State::Scalar(map.into())
642 }
643}
644
645impl<Txn> From<Number> for State<Txn> {
646 fn from(n: Number) -> Self {
647 Self::Scalar(n.into())
648 }
649}
650
651impl<Txn> From<Object<Txn>> for State<Txn> {
652 fn from(object: Object<Txn>) -> Self {
653 State::Object(object)
654 }
655}
656
657impl<Txn> From<OpDef> for State<Txn> {
658 fn from(op_def: OpDef) -> Self {
659 State::Scalar(Scalar::Op(op_def))
660 }
661}
662
663impl<Txn> From<OpRef> for State<Txn> {
664 fn from(op_ref: OpRef) -> Self {
665 TCRef::Op(op_ref).into()
666 }
667}
668
669impl<Txn, T> From<Option<T>> for State<Txn>
670where
671 State<Txn>: From<T>,
672{
673 fn from(state: Option<T>) -> Self {
674 if let Some(state) = state {
675 state.into()
676 } else {
677 Value::None.into()
678 }
679 }
680}
681
682impl<Txn> From<Scalar> for State<Txn> {
683 fn from(scalar: Scalar) -> Self {
684 State::Scalar(scalar)
685 }
686}
687
688impl<Txn> From<StateType> for State<Txn> {
689 fn from(class: StateType) -> Self {
690 Self::Object(InstanceClass::from(class).into())
691 }
692}
693
694#[cfg(feature = "table")]
695impl<Txn> From<Table<Txn>> for State<Txn> {
696 fn from(table: Table<Txn>) -> Self {
697 Self::Collection(table.into())
698 }
699}
700
701#[cfg(feature = "tensor")]
702impl<Txn> From<Tensor<Txn>> for State<Txn> {
703 fn from(tensor: Tensor<Txn>) -> Self {
704 Self::Collection(tensor.into())
705 }
706}
707
708impl<Txn> From<Tuple<State<Txn>>> for State<Txn> {
709 fn from(tuple: Tuple<State<Txn>>) -> Self {
710 Self::Tuple(tuple)
711 }
712}
713
714impl<Txn> From<Tuple<Scalar>> for State<Txn> {
715 fn from(tuple: Tuple<Scalar>) -> Self {
716 Self::Scalar(tuple.into())
717 }
718}
719
720impl<Txn> From<Tuple<Value>> for State<Txn> {
721 fn from(tuple: Tuple<Value>) -> Self {
722 Self::Scalar(tuple.into())
723 }
724}
725
726impl<Txn> From<TCRef> for State<Txn> {
727 fn from(tc_ref: TCRef) -> Self {
728 Box::new(tc_ref).into()
729 }
730}
731
732impl<Txn> From<Box<TCRef>> for State<Txn> {
733 fn from(tc_ref: Box<TCRef>) -> Self {
734 Self::Scalar(Scalar::Ref(tc_ref))
735 }
736}
737
738impl<Txn> From<Value> for State<Txn> {
739 fn from(value: Value) -> Self {
740 Self::Scalar(value.into())
741 }
742}
743
744impl<Txn> From<bool> for State<Txn> {
745 fn from(b: bool) -> Self {
746 Self::Scalar(b.into())
747 }
748}
749
750impl<Txn> From<i64> for State<Txn> {
751 fn from(n: i64) -> Self {
752 Self::Scalar(n.into())
753 }
754}
755
756impl<Txn> From<usize> for State<Txn> {
757 fn from(n: usize) -> Self {
758 Self::Scalar(n.into())
759 }
760}
761
762impl<Txn> From<u64> for State<Txn> {
763 fn from(n: u64) -> Self {
764 Self::Scalar(n.into())
765 }
766}
767
768impl<Txn, T1> CastFrom<(T1,)> for State<Txn>
769where
770 Self: CastFrom<T1>,
771{
772 fn cast_from(value: (T1,)) -> Self {
773 State::Tuple(vec![value.0.cast_into()].into())
774 }
775}
776
777impl<Txn, T1, T2> CastFrom<(T1, T2)> for State<Txn>
778where
779 Self: CastFrom<T1>,
780 Self: CastFrom<T2>,
781{
782 fn cast_from(value: (T1, T2)) -> Self {
783 State::Tuple(vec![value.0.cast_into(), value.1.cast_into()].into())
784 }
785}
786
787impl<Txn, T1, T2, T3> CastFrom<(T1, T2, T3)> for State<Txn>
788where
789 Self: CastFrom<T1>,
790 Self: CastFrom<T2>,
791 Self: CastFrom<T3>,
792{
793 fn cast_from(value: (T1, T2, T3)) -> Self {
794 State::Tuple(
795 vec![
796 value.0.cast_into(),
797 value.1.cast_into(),
798 value.2.cast_into(),
799 ]
800 .into(),
801 )
802 }
803}
804
805impl<Txn, T1, T2, T3, T4> CastFrom<(T1, T2, T3, T4)> for State<Txn>
806where
807 Self: CastFrom<T1>,
808 Self: CastFrom<T2>,
809 Self: CastFrom<T3>,
810 Self: CastFrom<T4>,
811{
812 fn cast_from(value: (T1, T2, T3, T4)) -> Self {
813 State::Tuple(
814 vec![
815 value.0.cast_into(),
816 value.1.cast_into(),
817 value.2.cast_into(),
818 value.3.cast_into(),
819 ]
820 .into(),
821 )
822 }
823}
824
825impl<Txn> TryFrom<State<Txn>> for bool {
826 type Error = TCError;
827
828 fn try_from(state: State<Txn>) -> Result<Self, Self::Error> {
829 match state {
830 State::Scalar(scalar) => scalar.try_into(),
831 other => Err(TCError::unexpected(other, "a boolean")),
832 }
833 }
834}
835
836impl<Txn> TryFrom<State<Txn>> for Id {
837 type Error = TCError;
838
839 fn try_from(state: State<Txn>) -> TCResult<Id> {
840 match state {
841 State::Scalar(scalar) => scalar.try_into(),
842 other => Err(TCError::unexpected(other, "an Id")),
843 }
844 }
845}
846
847#[cfg(feature = "collection")]
848impl<Txn> TryFrom<State<Txn>> for Collection<Txn> {
849 type Error = TCError;
850
851 fn try_from(state: State<Txn>) -> TCResult<Collection<Txn>> {
852 match state {
853 State::Collection(collection) => Ok(collection),
854 other => Err(TCError::unexpected(other, "a Collection")),
855 }
856 }
857}
858
859impl<Txn> TryFrom<State<Txn>> for Scalar {
860 type Error = TCError;
861
862 fn try_from(state: State<Txn>) -> TCResult<Self> {
863 match state {
864 State::Map(map) => map
865 .into_iter()
866 .map(|(id, state)| Scalar::try_from(state).map(|scalar| (id, scalar)))
867 .collect::<TCResult<Map<Scalar>>>()
868 .map(Scalar::Map),
869
870 State::Scalar(scalar) => Ok(scalar),
871
872 State::Tuple(tuple) => tuple
873 .into_iter()
874 .map(|state| Scalar::try_from(state))
875 .collect::<TCResult<Tuple<Scalar>>>()
876 .map(Scalar::Tuple),
877
878 other => Err(TCError::unexpected(other, "a Scalar")),
879 }
880 }
881}
882
883impl<Txn> TryFrom<State<Txn>> for Map<Scalar> {
884 type Error = TCError;
885
886 fn try_from(state: State<Txn>) -> TCResult<Map<Scalar>> {
887 match state {
888 State::Map(map) => map
889 .into_iter()
890 .map(|(id, state)| Scalar::try_from(state).map(|scalar| (id, scalar)))
891 .collect(),
892
893 State::Scalar(Scalar::Map(map)) => Ok(map),
894
895 State::Tuple(tuple) => tuple
896 .into_iter()
897 .map(|item| -> TCResult<(Id, Scalar)> { item.try_into() })
898 .collect(),
899
900 other => Err(TCError::unexpected(other, "a Map")),
901 }
902 }
903}
904
905impl<Txn> TryFrom<State<Txn>> for Map<State<Txn>> {
906 type Error = TCError;
907
908 fn try_from(state: State<Txn>) -> TCResult<Map<State<Txn>>> {
909 match state {
910 State::Map(map) => Ok(map),
911
912 State::Scalar(Scalar::Map(map)) => Ok(map
913 .into_iter()
914 .map(|(id, scalar)| (id, State::Scalar(scalar)))
915 .collect()),
916
917 State::Tuple(tuple) => tuple
918 .into_iter()
919 .map(|item| -> TCResult<(Id, State<Txn>)> { item.try_into() })
920 .collect(),
921
922 other => Err(TCError::unexpected(other, "a Map")),
923 }
924 }
925}
926
927impl<Txn> TryFrom<State<Txn>> for Map<Value> {
928 type Error = TCError;
929
930 fn try_from(state: State<Txn>) -> TCResult<Map<Value>> {
931 match state {
932 State::Map(map) => map
933 .into_iter()
934 .map(|(id, state)| Value::try_from(state).map(|scalar| (id, scalar)))
935 .collect(),
936
937 State::Scalar(scalar) => scalar.try_into(),
938
939 State::Tuple(tuple) => tuple
940 .into_iter()
941 .map(|item| -> TCResult<(Id, Value)> { item.try_into() })
942 .collect(),
943
944 other => Err(TCError::unexpected(other, "a Map")),
945 }
946 }
947}
948
949impl<Txn> TryFrom<State<Txn>> for Tuple<State<Txn>>
950where
951 Txn: Send + Sync,
952{
953 type Error = TCError;
954
955 fn try_from(state: State<Txn>) -> Result<Self, Self::Error> {
956 match state {
957 State::Map(map) => Ok(map
958 .into_iter()
959 .map(|(id, state)| State::Tuple(vec![State::from(id), state].into()))
960 .collect()),
961
962 State::Scalar(scalar) => {
963 let tuple = Tuple::<Scalar>::try_from(scalar)?;
964 Ok(tuple.into_iter().map(State::Scalar).collect())
965 }
966
967 State::Tuple(tuple) => Ok(tuple),
968
969 other => Err(TCError::unexpected(other, "a Tuple")),
970 }
971 }
972}
973
974impl<Txn, T> TryFrom<State<Txn>> for (Id, T)
975where
976 T: TryFrom<State<Txn>> + TryFrom<Scalar>,
977 TCError: From<<T as TryFrom<State<Txn>>>::Error> + From<<T as TryFrom<Scalar>>::Error>,
978{
979 type Error = TCError;
980
981 fn try_from(state: State<Txn>) -> TCResult<Self> {
982 match state {
983 State::Scalar(scalar) => scalar.try_into().map_err(TCError::from),
984 State::Tuple(mut tuple) if tuple.len() == 2 => {
985 let value = tuple.pop().expect("value");
986 let key = tuple.pop().expect("key");
987 Ok((key.try_into()?, value.try_into()?))
988 }
989 other => Err(TCError::unexpected(other, "a map item")),
990 }
991 }
992}
993
994impl<Txn> TryFrom<State<Txn>> for Value {
995 type Error = TCError;
996
997 fn try_from(state: State<Txn>) -> TCResult<Value> {
998 match state {
999 State::Scalar(scalar) => scalar.try_into(),
1000
1001 State::Tuple(tuple) => tuple
1002 .into_iter()
1003 .map(Value::try_from)
1004 .collect::<TCResult<Tuple<Value>>>()
1005 .map(Value::Tuple),
1006
1007 other => Err(TCError::unexpected(other, "a Value")),
1008 }
1009 }
1010}
1011
1012#[cfg(feature = "chain")]
1013impl<Txn> TryCastFrom<State<Txn>> for Chain<Txn, CollectionBase<Txn>> {
1014 fn can_cast_from(state: &State<Txn>) -> bool {
1015 match state {
1016 State::Chain(_) => true,
1017 _ => false,
1018 }
1019 }
1020
1021 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1022 match state {
1023 State::Chain(chain) => Some(chain),
1024 _ => None,
1025 }
1026 }
1027}
1028
1029#[cfg(feature = "chain")]
1030impl<Txn> TryCastFrom<State<Txn>> for BlockChain<Txn, CollectionBase<Txn>> {
1031 fn can_cast_from(state: &State<Txn>) -> bool {
1032 match state {
1033 State::Chain(Chain::Block(_)) => true,
1034 _ => false,
1035 }
1036 }
1037
1038 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1039 match state {
1040 State::Chain(Chain::Block(chain)) => Some(chain),
1041 _ => None,
1042 }
1043 }
1044}
1045
1046#[cfg(feature = "chain")]
1047impl<Txn> TryCastFrom<State<Txn>> for SyncChain<Txn, CollectionBase<Txn>> {
1048 fn can_cast_from(state: &State<Txn>) -> bool {
1049 match state {
1050 State::Chain(Chain::Sync(_)) => true,
1051 _ => false,
1052 }
1053 }
1054
1055 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1056 match state {
1057 State::Chain(Chain::Sync(chain)) => Some(chain),
1058 _ => None,
1059 }
1060 }
1061}
1062
1063impl<Txn> TryCastFrom<State<Txn>> for Closure<Txn> {
1064 fn can_cast_from(state: &State<Txn>) -> bool {
1065 match state {
1066 State::Closure(_) => true,
1067 State::Scalar(scalar) => Self::can_cast_from(scalar),
1068 _ => false,
1069 }
1070 }
1071
1072 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1073 match state {
1074 State::Closure(closure) => Some(closure),
1075 State::Scalar(scalar) => Self::opt_cast_from(scalar),
1076 _ => None,
1077 }
1078 }
1079}
1080
1081impl<Txn> TryCastFrom<State<Txn>> for Box<dyn ClosureInstance<State<Txn>>>
1082where
1083 Txn: Transaction<CacheBlock> + Gateway<State<Txn>>,
1084{
1085 fn can_cast_from(state: &State<Txn>) -> bool {
1086 match state {
1087 State::Closure(_) => true,
1088 State::Scalar(scalar) => Closure::<Txn>::can_cast_from(scalar),
1089 _ => false,
1090 }
1091 }
1092
1093 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1094 match state {
1095 State::Closure(closure) => Some(Box::new(closure)),
1096 State::Scalar(scalar) => {
1097 if let Some(closure) = Closure::<Txn>::opt_cast_from(scalar) {
1098 let closure: Box<dyn ClosureInstance<State<Txn>>> = Box::new(closure);
1099 Some(closure)
1100 } else {
1101 None
1102 }
1103 }
1104 _ => None,
1105 }
1106 }
1107}
1108
1109#[cfg(feature = "collection")]
1110impl<Txn> TryCastFrom<State<Txn>> for Collection<Txn> {
1111 fn can_cast_from(state: &State<Txn>) -> bool {
1112 match state {
1113 State::Collection(_) => true,
1114 _ => false,
1115 }
1116 }
1117
1118 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1119 match state {
1120 State::Collection(collection) => Some(collection),
1121 _ => None,
1122 }
1123 }
1124}
1125
1126#[cfg(feature = "collection")]
1127impl<Txn> TryCastFrom<State<Txn>> for CollectionBase<Txn> {
1128 fn can_cast_from(state: &State<Txn>) -> bool {
1129 match state {
1130 State::Collection(collection) => CollectionBase::can_cast_from(collection),
1131 _ => false,
1132 }
1133 }
1134
1135 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1136 match state {
1137 State::Collection(collection) => CollectionBase::opt_cast_from(collection),
1138 _ => None,
1139 }
1140 }
1141}
1142
1143#[cfg(any(feature = "btree", feature = "table", feature = "tensor"))]
1144impl<Txn> TryCastFrom<State<Txn>> for BTree<Txn> {
1145 fn can_cast_from(state: &State<Txn>) -> bool {
1146 match state {
1147 State::Collection(collection) => BTree::can_cast_from(collection),
1148 _ => false,
1149 }
1150 }
1151
1152 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1153 match state {
1154 State::Collection(collection) => BTree::opt_cast_from(collection),
1155 _ => None,
1156 }
1157 }
1158}
1159
1160#[cfg(feature = "table")]
1161impl<Txn> TryCastFrom<State<Txn>> for Table<Txn> {
1162 fn can_cast_from(state: &State<Txn>) -> bool {
1163 match state {
1164 State::Collection(collection) => Table::can_cast_from(collection),
1165 _ => false,
1166 }
1167 }
1168
1169 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1170 match state {
1171 State::Collection(collection) => Table::opt_cast_from(collection),
1172 _ => None,
1173 }
1174 }
1175}
1176
1177#[cfg(feature = "tensor")]
1178impl<Txn> TryCastFrom<State<Txn>> for Tensor<Txn> {
1179 fn can_cast_from(state: &State<Txn>) -> bool {
1180 match state {
1181 State::Collection(collection) => Tensor::can_cast_from(collection),
1182 _ => false,
1183 }
1184 }
1185
1186 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1187 match state {
1188 State::Collection(collection) => Tensor::opt_cast_from(collection),
1189 _ => None,
1190 }
1191 }
1192}
1193
1194impl<Txn, T> TryCastFrom<State<Txn>> for (T,)
1195where
1196 T: TryCastFrom<State<Txn>>,
1197{
1198 fn can_cast_from(state: &State<Txn>) -> bool {
1199 match state {
1200 State::Tuple(tuple) => Self::can_cast_from(tuple),
1201 _ => false,
1202 }
1203 }
1204
1205 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1206 match state {
1207 State::Tuple(tuple) => Self::opt_cast_from(tuple),
1208 _ => None,
1209 }
1210 }
1211}
1212
1213impl<Txn, T1, T2> TryCastFrom<State<Txn>> for (T1, T2)
1214where
1215 T1: TryCastFrom<State<Txn>>,
1216 T2: TryCastFrom<State<Txn>>,
1217{
1218 fn can_cast_from(state: &State<Txn>) -> bool {
1219 match state {
1220 State::Tuple(tuple) => Self::can_cast_from(tuple),
1221 _ => false,
1222 }
1223 }
1224
1225 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1226 match state {
1227 State::Tuple(tuple) => Self::opt_cast_from(tuple),
1228 _ => None,
1229 }
1230 }
1231}
1232
1233impl<Txn, T1, T2, T3> TryCastFrom<State<Txn>> for (T1, T2, T3)
1234where
1235 T1: TryCastFrom<State<Txn>>,
1236 T2: TryCastFrom<State<Txn>>,
1237 T3: TryCastFrom<State<Txn>>,
1238{
1239 fn can_cast_from(state: &State<Txn>) -> bool {
1240 match state {
1241 State::Tuple(tuple) => Self::can_cast_from(tuple),
1242 _ => false,
1243 }
1244 }
1245
1246 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1247 match state {
1248 State::Tuple(tuple) => Self::opt_cast_from(tuple),
1249 _ => None,
1250 }
1251 }
1252}
1253
1254impl<Txn, T: TryCastFrom<State<Txn>>> TryCastFrom<State<Txn>> for Vec<T> {
1256 fn can_cast_from(state: &State<Txn>) -> bool {
1257 match state {
1258 State::Tuple(tuple) => Self::can_cast_from(tuple),
1259 _ => false,
1260 }
1261 }
1262
1263 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1264 match state {
1265 State::Tuple(source) => Self::opt_cast_from(source),
1266 _ => None,
1267 }
1268 }
1269}
1270
1271impl<Txn, T> TryCastFrom<State<Txn>> for Tuple<T>
1273where
1274 T: TryCastFrom<State<Txn>>,
1275{
1276 fn can_cast_from(state: &State<Txn>) -> bool {
1277 match state {
1278 State::Tuple(tuple) => Vec::<T>::can_cast_from(tuple),
1279 _ => false,
1280 }
1281 }
1282
1283 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1284 match state {
1285 State::Tuple(tuple) => Vec::<T>::opt_cast_from(tuple).map(Tuple::from),
1286 _ => None,
1287 }
1288 }
1289}
1290
1291impl<Txn> TryCastFrom<State<Txn>> for InstanceClass {
1292 fn can_cast_from(state: &State<Txn>) -> bool {
1293 match state {
1294 State::Object(Object::Class(_)) => true,
1295 State::Scalar(scalar) => Self::can_cast_from(scalar),
1296 State::Tuple(tuple) => tuple.matches::<(Link, Map<Scalar>)>(),
1297 _ => false,
1298 }
1299 }
1300
1301 fn opt_cast_from(state: State<Txn>) -> Option<InstanceClass> {
1302 match state {
1303 State::Object(Object::Class(class)) => Some(class),
1304 State::Scalar(scalar) => Self::opt_cast_from(scalar),
1305 State::Tuple(tuple) => {
1306 let (extends, proto) = tuple.opt_cast_into()?;
1307 Some(Self::cast_from((extends, proto)))
1308 }
1309 _ => None,
1310 }
1311 }
1312}
1313
1314impl<Txn, T> TryCastFrom<State<Txn>> for Map<T>
1315where
1316 T: TryCastFrom<State<Txn>>,
1317{
1318 fn can_cast_from(state: &State<Txn>) -> bool {
1319 match state {
1320 State::Map(map) => map.values().all(T::can_cast_from),
1321 State::Tuple(tuple) => tuple.iter().all(|item| item.matches::<(Id, State<Txn>)>()),
1322 _ => false,
1323 }
1324 }
1325
1326 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1327 match state {
1328 State::Map(map) => {
1329 let mut dest = Map::new();
1330
1331 for (key, value) in map {
1332 let value = T::opt_cast_from(value)?;
1333 dest.insert(key, value);
1334 }
1335
1336 Some(dest)
1337 }
1338 State::Tuple(tuple) => {
1339 let mut dest = Map::new();
1340
1341 for item in tuple {
1342 let (key, value): (Id, T) = item.opt_cast_into()?;
1343 dest.insert(key, value);
1344 }
1345
1346 Some(dest)
1347 }
1348 _ => None,
1349 }
1350 }
1351}
1352
1353impl<Txn> TryCastFrom<State<Txn>> for Scalar {
1354 fn can_cast_from(state: &State<Txn>) -> bool {
1355 match state {
1356 State::Map(map) => map.values().all(Scalar::can_cast_from),
1357 State::Object(object) => Self::can_cast_from(object),
1358 State::Scalar(_) => true,
1359 State::Tuple(tuple) => Vec::<Scalar>::can_cast_from(tuple),
1360 _ => false,
1361 }
1362 }
1363
1364 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1365 match state {
1366 State::Map(map) => {
1367 let mut dest = Map::new();
1368
1369 for (key, state) in map.into_iter() {
1370 let scalar = Scalar::opt_cast_from(state)?;
1371 dest.insert(key, scalar);
1372 }
1373
1374 Some(Scalar::Map(dest))
1375 }
1376 State::Object(object) => Self::opt_cast_from(object),
1377 State::Scalar(scalar) => Some(scalar),
1378
1379 State::Tuple(tuple) => {
1380 let mut scalar = Tuple::<Scalar>::with_capacity(tuple.len());
1381
1382 for state in tuple {
1383 scalar.push(state.opt_cast_into()?);
1384 }
1385
1386 Some(Scalar::Tuple(scalar))
1387 }
1388
1389 _ => None,
1390 }
1391 }
1392}
1393
1394impl<Txn> TryCastFrom<State<Txn>> for Value {
1395 fn can_cast_from(state: &State<Txn>) -> bool {
1396 match state {
1397 State::Object(object) => Self::can_cast_from(object),
1398 State::Scalar(scalar) => Self::can_cast_from(scalar),
1399 State::Tuple(tuple) => tuple.iter().all(Self::can_cast_from),
1400 _ => false,
1401 }
1402 }
1403
1404 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1405 match state {
1406 State::Object(object) => Self::opt_cast_from(object),
1407 State::Scalar(scalar) => Self::opt_cast_from(scalar),
1408
1409 State::Tuple(tuple) => {
1410 let mut value = Tuple::<Value>::with_capacity(tuple.len());
1411
1412 for state in tuple {
1413 value.push(state.opt_cast_into()?);
1414 }
1415
1416 Some(Value::Tuple(value))
1417 }
1418
1419 _ => None,
1420 }
1421 }
1422}
1423
1424impl<Txn> TryCastFrom<State<Txn>> for Link {
1425 fn can_cast_from(state: &State<Txn>) -> bool {
1426 match state {
1427 State::Object(Object::Class(class)) => Self::can_cast_from(class),
1428 State::Scalar(scalar) => Self::can_cast_from(scalar),
1429 _ => false,
1430 }
1431 }
1432
1433 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1434 match state {
1435 State::Object(Object::Class(class)) => Self::opt_cast_from(class).map(Self::from),
1436 State::Scalar(scalar) => Self::opt_cast_from(scalar).map(Self::from),
1437 _ => None,
1438 }
1439 }
1440}
1441
1442macro_rules! from_scalar {
1443 ($t:ty) => {
1444 impl<Txn> TryCastFrom<State<Txn>> for $t {
1445 fn can_cast_from(state: &State<Txn>) -> bool {
1446 match state {
1447 State::Scalar(scalar) => Self::can_cast_from(scalar),
1448 _ => false,
1449 }
1450 }
1451
1452 fn opt_cast_from(state: State<Txn>) -> Option<Self> {
1453 match state {
1454 State::Scalar(scalar) => Self::opt_cast_from(scalar),
1455 _ => None,
1456 }
1457 }
1458 }
1459 };
1460}
1461
1462from_scalar!(Bytes);
1463from_scalar!(Float);
1464from_scalar!(Id);
1465from_scalar!(IdRef);
1466from_scalar!(Host);
1467from_scalar!(Number);
1468from_scalar!(OpDef);
1469from_scalar!(OpRef);
1470from_scalar!(TCPathBuf);
1471from_scalar!(TCString);
1472from_scalar!(bool);
1473from_scalar!(usize);
1474from_scalar!(u64);
1475
1476impl<Txn> fmt::Debug for State<Txn> {
1477 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1478 match self {
1479 #[cfg(feature = "chain")]
1480 Self::Chain(chain) => fmt::Debug::fmt(chain, f),
1481 Self::Closure(closure) => fmt::Debug::fmt(closure, f),
1482 #[cfg(feature = "collection")]
1483 Self::Collection(collection) => fmt::Debug::fmt(collection, f),
1484 Self::Map(map) => fmt::Debug::fmt(map, f),
1485 Self::Object(object) => fmt::Debug::fmt(object, f),
1486 Self::Scalar(scalar) => fmt::Debug::fmt(scalar, f),
1487 Self::Tuple(tuple) => fmt::Debug::fmt(tuple, f),
1488 }
1489 }
1490}
1491
1492struct StateVisitor<Txn> {
1493 txn: Txn,
1494 scalar: ScalarVisitor,
1495}
1496
1497impl<Txn> StateVisitor<Txn>
1498where
1499 Txn: Transaction<CacheBlock> + Gateway<State<Txn>>,
1500{
1501 async fn visit_map_value<A: de::MapAccess>(
1502 &self,
1503 class: StateType,
1504 access: &mut A,
1505 ) -> Result<State<Txn>, A::Error> {
1506 debug!("decode instance of {:?}", class);
1507
1508 match class {
1509 #[cfg(feature = "chain")]
1510 StateType::Chain(ct) => {
1511 ChainVisitor::new(self.txn.clone())
1512 .visit_map_value(ct, access)
1513 .map_ok(State::Chain)
1514 .await
1515 }
1516 StateType::Closure => {
1517 access
1518 .next_value(self.txn.clone())
1519 .map_ok(State::Closure)
1520 .await
1521 }
1522 #[cfg(feature = "collection")]
1523 StateType::Collection(ct) => {
1524 CollectionVisitor::new(self.txn.clone())
1525 .visit_map_value(ct, access)
1526 .map_ok(Collection::from)
1527 .map_ok(State::Collection)
1528 .await
1529 }
1530 StateType::Map => access.next_value(self.txn.clone()).await,
1531 StateType::Object(ot) => {
1532 let txn = self.txn.subcontext_unique();
1533
1534 let state = access.next_value(txn).await?;
1535 ObjectVisitor::new()
1536 .visit_map_value(ot, state)
1537 .map_ok(State::Object)
1538 .await
1539 }
1540 StateType::Scalar(st) => {
1541 ScalarVisitor::visit_map_value(st, access)
1542 .map_ok(State::Scalar)
1543 .await
1544 }
1545 StateType::Tuple => access.next_value(self.txn.clone()).await,
1546 }
1547 }
1548}
1549
1550#[async_trait]
1551impl<'a, Txn> de::Visitor for StateVisitor<Txn>
1552where
1553 Txn: Transaction<CacheBlock> + Gateway<State<Txn>>,
1554{
1555 type Value = State<Txn>;
1556
1557 fn expecting() -> &'static str {
1558 r#"a State, e.g. 1 or [2] or "three" or {"/state/scalar/value/number/complex": [3.14, -1.414]}"#
1559 }
1560
1561 async fn visit_array_u8<A: ArrayAccess<u8>>(self, array: A) -> Result<Self::Value, A::Error> {
1562 self.scalar
1563 .visit_array_u8(array)
1564 .map_ok(State::Scalar)
1565 .await
1566 }
1567
1568 fn visit_bool<E: de::Error>(self, b: bool) -> Result<Self::Value, E> {
1569 self.scalar.visit_bool(b).map(State::Scalar)
1570 }
1571
1572 fn visit_i8<E: de::Error>(self, i: i8) -> Result<Self::Value, E> {
1573 self.scalar.visit_i8(i).map(State::Scalar)
1574 }
1575
1576 fn visit_i16<E: de::Error>(self, i: i16) -> Result<Self::Value, E> {
1577 self.scalar.visit_i16(i).map(State::Scalar)
1578 }
1579
1580 fn visit_i32<E: de::Error>(self, i: i32) -> Result<Self::Value, E> {
1581 self.scalar.visit_i32(i).map(State::Scalar)
1582 }
1583
1584 fn visit_i64<E: de::Error>(self, i: i64) -> Result<Self::Value, E> {
1585 self.scalar.visit_i64(i).map(State::Scalar)
1586 }
1587
1588 fn visit_u8<E: de::Error>(self, u: u8) -> Result<Self::Value, E> {
1589 self.scalar.visit_u8(u).map(State::Scalar)
1590 }
1591
1592 fn visit_u16<E: de::Error>(self, u: u16) -> Result<Self::Value, E> {
1593 self.scalar.visit_u16(u).map(State::Scalar)
1594 }
1595
1596 fn visit_u32<E: de::Error>(self, u: u32) -> Result<Self::Value, E> {
1597 self.scalar.visit_u32(u).map(State::Scalar)
1598 }
1599
1600 fn visit_u64<E: de::Error>(self, u: u64) -> Result<Self::Value, E> {
1601 self.scalar.visit_u64(u).map(State::Scalar)
1602 }
1603
1604 fn visit_f32<E: de::Error>(self, f: f32) -> Result<Self::Value, E> {
1605 self.scalar.visit_f32(f).map(State::Scalar)
1606 }
1607
1608 fn visit_f64<E: de::Error>(self, f: f64) -> Result<Self::Value, E> {
1609 self.scalar.visit_f64(f).map(State::Scalar)
1610 }
1611
1612 fn visit_string<E: de::Error>(self, s: String) -> Result<Self::Value, E> {
1613 self.scalar.visit_string(s).map(State::Scalar)
1614 }
1615
1616 fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
1617 self.scalar.visit_unit().map(State::Scalar)
1618 }
1619
1620 fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
1621 self.scalar.visit_none().map(State::Scalar)
1622 }
1623
1624 async fn visit_map<A: de::MapAccess>(self, mut access: A) -> Result<Self::Value, A::Error> {
1625 if let Some(key) = access.next_key::<String>(()).await? {
1626 debug!("deserialize: key is {}", key);
1627
1628 if key.starts_with('/') {
1629 if let Ok(path) = TCPathBuf::from_str(&key) {
1630 debug!("is {} a classpath?", path);
1631
1632 if let Some(class) = StateType::from_path(&path) {
1633 debug!("deserialize instance of {:?}...", class);
1634 return self.visit_map_value(class, &mut access).await;
1635 } else {
1636 debug!("not a classpath: {}", path);
1637 }
1638 }
1639 }
1640
1641 if let Ok(subject) = reference::Subject::from_str(&key) {
1642 let params = access.next_value(()).await?;
1643 debug!("deserialize Scalar from key {} and value {:?}", key, params);
1644 return ScalarVisitor::visit_subject(subject, params).map(State::Scalar);
1645 }
1646
1647 let mut map = Map::<State<Txn>>::new();
1648
1649 let id = Id::from_str(&key).map_err(de::Error::custom)?;
1650 let txn = self.txn.subcontext(id.clone());
1651 let value = access.next_value(txn).await?;
1652 map.insert(id.clone(), value);
1653
1654 while let Some(id) = access.next_key::<Id>(()).await? {
1655 let txn = self.txn.subcontext(id.clone());
1656 let state = access.next_value(txn).await?;
1657 map.insert(id, state);
1658 }
1659
1660 debug!("deserialize map {map:?}");
1661 if map.len() == 1 {
1662 let value = map.as_ref().get(&id).expect("map value");
1663 if value.is_none() && !value.is_map() {
1664 return Ok(State::from(id));
1665 }
1666 }
1667
1668 Ok(State::Map(map))
1669 } else {
1670 Ok(State::Map(Map::default()))
1671 }
1672 }
1673
1674 async fn visit_seq<A: de::SeqAccess>(self, mut access: A) -> Result<Self::Value, A::Error> {
1675 let mut seq = if let Some(len) = access.size_hint() {
1676 Vec::with_capacity(len)
1677 } else {
1678 Vec::new()
1679 };
1680
1681 let mut i = 0usize;
1682 loop {
1683 let txn = self.txn.subcontext(i);
1684
1685 if let Some(next) = access.next_element(txn).await? {
1686 seq.push(next);
1687 i += 1;
1688 } else {
1689 break;
1690 }
1691 }
1692
1693 Ok(State::Tuple(seq.into()))
1694 }
1695}
1696
1697#[async_trait]
1698impl<Txn> de::FromStream for State<Txn>
1699where
1700 Txn: Transaction<CacheBlock> + Gateway<State<Txn>>,
1701{
1702 type Context = Txn;
1703
1704 async fn from_stream<D: de::Decoder>(txn: Txn, decoder: &mut D) -> Result<Self, D::Error> {
1705 let scalar = ScalarVisitor::default();
1706 decoder.decode_any(StateVisitor { txn, scalar }).await
1707 }
1708}