taos_query/common/raw/
rows.rs

1use std::{marker::PhantomData, ptr::NonNull};
2
3use serde::{
4    de::{DeserializeSeed, IntoDeserializer, MapAccess, SeqAccess, Visitor},
5    Deserializer,
6};
7
8use crate::{
9    common::{BorrowedValue, Value},
10    RawBlock,
11};
12
13pub struct IntoRowsIter<'a> {
14    pub(crate) raw: RawBlock,
15    pub(crate) row: usize,
16    pub(crate) _marker: PhantomData<&'a bool>,
17}
18
19unsafe impl<'a> Send for IntoRowsIter<'a> {}
20unsafe impl<'a> Sync for IntoRowsIter<'a> {}
21
22impl<'a> Iterator for IntoRowsIter<'a> {
23    type Item = RowView<'a>;
24
25    fn next(&mut self) -> Option<Self::Item> {
26        if self.row >= self.raw.nrows() {
27            None
28        } else {
29            let row = self.row;
30            self.row += 1;
31            Some(RowView {
32                raw: unsafe { &*(&self.raw as *const RawBlock) },
33                row,
34                col: 0,
35            })
36        }
37    }
38}
39
40pub struct RowsIter<'a> {
41    pub(super) raw: NonNull<RawBlock>,
42    pub(super) row: usize,
43    pub(crate) _marker: PhantomData<&'a usize>,
44}
45
46unsafe impl<'a> Send for RowsIter<'a> {}
47unsafe impl<'a> Sync for RowsIter<'a> {}
48
49impl<'a> Iterator for RowsIter<'a> {
50    type Item = RowView<'a>;
51
52    fn next(&mut self) -> Option<Self::Item> {
53        if self.row >= unsafe { self.raw.as_mut() }.nrows() {
54            None
55        } else {
56            let row = self.row;
57            self.row += 1;
58            Some(RowView {
59                raw: unsafe { self.raw.as_mut() },
60                row,
61                col: 0,
62            })
63        }
64    }
65}
66
67impl<'a> RowsIter<'a> {
68    pub fn values(&mut self) -> ValueIter {
69        ValueIter {
70            raw: unsafe { self.raw.as_mut() },
71            row: self.row,
72            col: 0,
73        }
74    }
75    pub fn named_values(&mut self) -> RowView {
76        RowView {
77            raw: unsafe { self.raw.as_mut() },
78            row: self.row,
79            col: 0,
80        }
81    }
82}
83
84pub struct ValueIter<'a> {
85    raw: &'a RawBlock,
86    row: usize,
87    col: usize,
88}
89
90impl<'a> Iterator for ValueIter<'a> {
91    type Item = BorrowedValue<'a>;
92
93    fn next(&mut self) -> Option<Self::Item> {
94        if self.col >= self.raw.ncols() {
95            None
96        } else {
97            unsafe {
98                let col = self.col;
99                self.col += 1;
100                Some(self.raw.get_ref_unchecked(self.row, col))
101            }
102        }
103    }
104}
105
106pub struct RowView<'a> {
107    raw: &'a RawBlock,
108    row: usize,
109    col: usize,
110}
111
112impl<'a> Iterator for RowView<'a> {
113    type Item = (&'a str, BorrowedValue<'a>);
114
115    fn next(&mut self) -> Option<Self::Item> {
116        if self.col >= self.raw.ncols() {
117            None
118        } else {
119            unsafe {
120                let col = self.col;
121                self.col += 1;
122                Some((
123                    self.raw.fields.get_unchecked(col).as_str(),
124                    self.raw.get_ref_unchecked(self.row, col),
125                ))
126            }
127        }
128    }
129
130    fn size_hint(&self) -> (usize, Option<usize>) {
131        let max = self.raw.ncols();
132        if self.col < max {
133            let hint = max - self.col;
134            (hint, Some(hint))
135        } else {
136            (0, Some(0))
137        }
138    }
139}
140
141impl<'a> ExactSizeIterator for RowView<'a> {}
142
143impl<'a> std::fmt::Debug for RowView<'a> {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        f.debug_struct("RowView")
146            .field("raw", &self.raw)
147            .field("row", &self.row)
148            .field("col", &self.col)
149            .finish()
150    }
151}
152pub struct RowViewOfValue<'a>(RowView<'a>);
153
154impl<'a> Iterator for RowViewOfValue<'a> {
155    type Item = BorrowedValue<'a>;
156
157    fn next(&mut self) -> Option<Self::Item> {
158        if self.0.col >= self.0.raw.ncols() {
159            None
160        } else {
161            unsafe {
162                let col = self.0.col;
163                self.0.col += 1;
164                Some(self.0.raw.get_ref_unchecked(self.0.row, col))
165            }
166        }
167    }
168}
169
170impl<'a> RowView<'a> {
171    pub fn into_value_iter(self) -> RowViewOfValue<'a> {
172        RowViewOfValue(self)
173    }
174    fn walk_next(&mut self) -> Option<BorrowedValue<'a>> {
175        self.next().map(|(_, v)| v)
176    }
177
178    // fn walk(&mut self) {
179    //     self.col += 1;
180    // }
181
182    fn peek_name(&self) -> Option<&'a str> {
183        self.raw.fields.get(self.col).map(|s| s.as_str())
184    }
185    // fn peek_value(&self) -> Option<BorrowedValue<'a>> {
186    //     self.raw.get_ref(self.row, self.col)
187    // }
188
189    pub fn into_values(self) -> Vec<Value> {
190        self.map(|(_, b)| b.to_value()).collect()
191    }
192}
193
194pub(super) type DeError = taos_error::Error;
195
196impl<'de, 'a: 'de> SeqAccess<'de> for RowView<'a> {
197    type Error = DeError;
198
199    fn next_element_seed<S>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error>
200    where
201        S: DeserializeSeed<'de>,
202    {
203        match self.next() {
204            Some((_, v)) => seed
205                .deserialize(v)
206                .map_err(<Self::Error as serde::de::Error>::custom)
207                .map(Some),
208            None => Ok(None),
209        }
210    }
211}
212
213impl<'de, 'a: 'de> MapAccess<'de> for RowView<'a> {
214    type Error = DeError;
215
216    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
217    where
218        K: DeserializeSeed<'de>,
219    {
220        match self.peek_name() {
221            Some(name) => seed.deserialize(name.into_deserializer()).map(Some),
222            _ => Ok(None),
223        }
224    }
225
226    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
227    where
228        V: DeserializeSeed<'de>,
229    {
230        // let value = self
231        //     .walk_next()
232        //     .ok_or(<Self::Error as serde::de::Error>::custom(
233        //         "expect a value but no value remains",
234        //     ))?; // always be here, so it's safe to unwrap
235
236        seed.deserialize(&mut *self)
237            .map_err(<Self::Error as serde::de::Error>::custom)
238    }
239}
240
241impl<'de, 'a: 'de> Deserializer<'de> for &mut RowView<'a> {
242    type Error = DeError;
243
244    // Look at the input data to decide what Serde data model type to
245    // deserialize as. Not all data formats are able to support this operation.
246    // Formats that support `deserialize_any` are known as self-describing.
247    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
248    where
249        V: Visitor<'de>,
250    {
251        match self.walk_next() {
252            Some(v) => v
253                .deserialize_any(visitor)
254                .map_err(<Self::Error as serde::de::Error>::custom),
255            None => Err(<Self::Error as serde::de::Error>::custom(
256                "expect value, not none",
257            )),
258        }
259    }
260
261    serde::forward_to_deserialize_any! {
262        bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char bytes byte_buf enum
263        identifier ignored_any
264    }
265
266    // Refer to the "Understanding deserializer lifetimes" page for information
267    // about the three deserialization flavors of strings in Serde.
268    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
269    where
270        V: Visitor<'de>,
271    {
272        match self.walk_next() {
273            Some(v) => v
274                .deserialize_str(visitor)
275                .map_err(<Self::Error as serde::de::Error>::custom),
276            None => Err(<Self::Error as serde::de::Error>::custom(
277                "expect value, not none",
278            )),
279        }
280    }
281
282    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
283    where
284        V: Visitor<'de>,
285    {
286        self.deserialize_str(visitor)
287    }
288
289    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
290    where
291        V: Visitor<'de>,
292    {
293        match self.walk_next() {
294            Some(v) => {
295                if v.is_null() {
296                    visitor.visit_none()
297                } else {
298                    visitor
299                        .visit_some(v)
300                        .map_err(<Self::Error as serde::de::Error>::custom)
301                }
302            }
303            _ => Err(<Self::Error as serde::de::Error>::custom(
304                "expect next value",
305            )),
306        }
307    }
308
309    // In Serde, unit means an anonymous value containing no data.
310    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
311    where
312        V: Visitor<'de>,
313    {
314        match self.walk_next() {
315            Some(_v) => visitor.visit_unit(),
316            _ => Err(<Self::Error as serde::de::Error>::custom(
317                "there's no enough value",
318            )),
319        }
320    }
321
322    // Unit struct means a named value containing no data.
323    fn deserialize_unit_struct<V>(
324        self,
325        _name: &'static str,
326        visitor: V,
327    ) -> Result<V::Value, Self::Error>
328    where
329        V: Visitor<'de>,
330    {
331        self.deserialize_unit(visitor)
332    }
333
334    // As is done here, serializers are encouraged to treat newtype structs as
335    // insignificant wrappers around the data they contain. That means not
336    // parsing anything other than the contained value.
337    fn deserialize_newtype_struct<V>(
338        self,
339        _name: &'static str,
340        visitor: V,
341    ) -> Result<V::Value, Self::Error>
342    where
343        V: Visitor<'de>,
344    {
345        visitor.visit_newtype_struct(self)
346    }
347
348    // Deserialization of compound types like sequences and maps happens by
349    // passing the visitor an "Access" object that gives it the ability to
350    // iterate through the data contained in the sequence.
351    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
352    where
353        V: Visitor<'de>,
354    {
355        visitor.visit_seq(self)
356    }
357
358    // Tuples look just like sequences.
359    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
360    where
361        V: Visitor<'de>,
362    {
363        // self.deserialize_any(visitor)
364        visitor.visit_seq(self)
365    }
366
367    // Tuple structs look just like sequences.
368    fn deserialize_tuple_struct<V>(
369        self,
370        _name: &'static str,
371        _len: usize,
372        visitor: V,
373    ) -> Result<V::Value, Self::Error>
374    where
375        V: Visitor<'de>,
376    {
377        self.deserialize_seq(visitor)
378    }
379
380    // Much like `deserialize_seq` but calls the visitors `visit_map` method
381    // with a `MapAccess` implementation, rather than the visitor's `visit_seq`
382    // method with a `SeqAccess` implementation.
383    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
384    where
385        V: Visitor<'de>,
386    {
387        // No field names, just access as sequence.
388        if self.raw.fields.is_empty() {
389            return visitor.visit_seq(self);
390        }
391        visitor.visit_map(self)
392    }
393
394    // Structs look just like maps in JSON.
395    //
396    // Notice the `fields` parameter - a "struct" in the Serde data model means
397    // that the `Deserialize` implementation is required to know what the fields
398    // are before even looking at the input data. Any key-value pairing in which
399    // the fields cannot be known ahead of time is probably a map.
400    fn deserialize_struct<V>(
401        self,
402        _name: &'static str,
403        _fields: &'static [&'static str],
404        visitor: V,
405    ) -> Result<V::Value, Self::Error>
406    where
407        V: Visitor<'de>,
408    {
409        self.deserialize_map(visitor)
410    }
411}