1use std::collections::HashMap;
2
3use async_trait::async_trait;
4use destream::{en, EncodeMap};
5use futures::stream::{self, StreamExt, TryStreamExt};
6use futures::TryFutureExt;
7
8use tc_error::*;
9use tc_scalar::{OpDef, Scalar};
10use tc_transact::{Gateway, IntoView, Transaction};
11use tcgeneric::{Id, NativeClass};
12
13use super::object::ObjectView;
14use super::{CacheBlock, StateType};
15
16use super::State;
17
18pub enum StateView<'en> {
20 #[cfg(feature = "chain")]
21 Chain(tc_chain::ChainView<'en, tc_collection::CollectionView<'en>>),
22 Closure((HashMap<Id, StateView<'en>>, OpDef)),
23 #[cfg(feature = "collection")]
24 Collection(tc_collection::CollectionView<'en>),
25 Map(HashMap<Id, StateView<'en>>),
26 Object(Box<ObjectView<'en>>),
27 Scalar(Scalar),
28 Tuple(Vec<StateView<'en>>),
29}
30
31#[async_trait]
32impl<'en, Txn> IntoView<'en, CacheBlock> for State<Txn>
33where
34 Txn: Transaction<CacheBlock> + Gateway<State<Txn>>,
35{
36 type Txn = Txn;
37 type View = StateView<'en>;
38
39 async fn into_view(self, txn: Self::Txn) -> TCResult<Self::View> {
40 match self {
41 #[cfg(feature = "chain")]
42 Self::Chain(chain) => chain.into_view(txn).map_ok(StateView::Chain).await,
43 Self::Closure(closure) => closure.into_view(txn).map_ok(StateView::Closure).await,
44 #[cfg(feature = "collection")]
45 Self::Collection(collection) => {
46 collection
47 .into_view(txn)
48 .map_ok(StateView::Collection)
49 .await
50 }
51 Self::Map(map) => {
52 let map_view = stream::iter(map.into_iter())
53 .map(|(key, state)| state.into_view(txn.clone()).map_ok(|view| (key, view)))
54 .buffer_unordered(num_cpus::get())
55 .try_collect::<HashMap<Id, StateView>>()
56 .await?;
57
58 Ok(StateView::Map(map_view))
59 }
60 Self::Object(object) => {
61 object
62 .into_view(txn)
63 .map_ok(Box::new)
64 .map_ok(StateView::Object)
65 .await
66 }
67 Self::Scalar(scalar) => Ok(StateView::Scalar(scalar)),
68 Self::Tuple(tuple) => {
69 let tuple_view = stream::iter(tuple.into_iter())
70 .map(|state| state.into_view(txn.clone()))
71 .buffered(num_cpus::get())
72 .try_collect::<Vec<StateView>>()
73 .await?;
74
75 Ok(StateView::Tuple(tuple_view.into()))
76 }
77 }
78 }
79}
80
81impl<'en> en::IntoStream<'en> for StateView<'en> {
82 fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
83 match self {
84 #[cfg(feature = "chain")]
85 Self::Chain(chain) => chain.into_stream(encoder),
86 Self::Closure(closure) => {
87 let mut map = encoder.encode_map(Some(1))?;
88 map.encode_key(StateType::Closure.path().to_string())?;
89 map.encode_value(closure)?;
90 map.end()
91 }
92 #[cfg(feature = "collection")]
93 Self::Collection(collection) => collection.into_stream(encoder),
94 Self::Map(map) => map.into_stream(encoder),
95 Self::Object(object) => object.into_stream(encoder),
96 Self::Scalar(scalar) => scalar.into_stream(encoder),
97 Self::Tuple(tuple) => tuple.into_stream(encoder),
98 }
99 }
100}