opensrv_clickhouse/types/column/
iter.rs

1// Copyright 2021 Datafuse Labs.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(clippy::cast_ptr_alignment)]
16
17use std::iter::FusedIterator;
18use std::marker;
19use std::mem;
20use std::net::Ipv4Addr;
21use std::net::Ipv6Addr;
22use std::ptr;
23use std::slice;
24
25use chrono::prelude::*;
26use chrono::NaiveDate;
27use chrono_tz::Tz;
28
29use crate::errors::Error;
30use crate::errors::FromSqlError;
31use crate::errors::Result;
32use crate::types::column::column_data::ArcColumnData;
33use crate::types::column::datetime64::to_datetime;
34use crate::types::column::StringPool;
35use crate::types::decimal::NoBits;
36use crate::types::Column;
37use crate::types::ColumnType;
38use crate::types::Complex;
39use crate::types::Decimal;
40use crate::types::Simple;
41use crate::types::SqlType;
42
43macro_rules! simple_num_iterable {
44    ( $($t:ty: $k:ident),* ) => {
45        $(
46            impl<'a> Iterable<'a, Simple> for $t {
47                type Iter = slice::Iter<'a, $t>;
48
49                fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
50                    if column_type != SqlType::$k {
51                        return Err(Error::FromSql(FromSqlError::InvalidType {
52                            src: column.sql_type().to_string(),
53                            dst: SqlType::$k.to_string(),
54                        }));
55                    }
56
57                    unsafe {
58                        let mut ptr: *const u8 = ptr::null();
59                        let mut size: usize = 0;
60                        column.get_internal(&[&mut ptr, &mut size as *mut usize as *mut *const u8], 0)?;
61                        assert_ne!(ptr, ptr::null());
62                        Ok(slice::from_raw_parts(ptr as *const $t, size).iter())
63                    }
64                }
65            }
66        )*
67    };
68}
69
70simple_num_iterable! {
71    u8: UInt8,
72    u16: UInt16,
73    u32: UInt32,
74    u64: UInt64,
75
76    i8: Int8,
77    i16: Int16,
78    i32: Int32,
79    i64: Int64,
80
81    f32: Float32,
82    f64: Float64
83}
84
85macro_rules! iterator {
86    (
87        $name:ident: $type:ty
88    ) => {
89        impl<'a> Iterator for $name<'a> {
90            type Item = $type;
91
92            #[inline]
93            fn next(&mut self) -> Option<Self::Item> {
94                if self.ptr == self.end {
95                    None
96                } else {
97                    Some(unsafe { self.next_unchecked() })
98                }
99            }
100
101            #[inline]
102            fn size_hint(&self) -> (usize, Option<usize>) {
103                let exact = self.len();
104                (exact, Some(exact))
105            }
106
107            #[inline]
108            fn count(self) -> usize {
109                self.len()
110            }
111
112            #[inline]
113            fn nth(&mut self, n: usize) -> Option<Self::Item> {
114                if n >= self.len() {
115                    // This iterator is now empty.
116                    self.ptr = self.end;
117                    return None;
118                }
119                // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
120                self.post_inc_start(n);
121                self.next()
122            }
123        }
124    };
125}
126
127macro_rules! exact_size_iterator {
128    (
129        $name:ident: $type:ty
130    ) => {
131        impl ExactSizeIterator for $name<'_> {
132            #[inline(always)]
133            fn len(&self) -> usize {
134                (self.end as usize - self.ptr as usize) / mem::size_of::<$type>()
135            }
136        }
137    };
138}
139
140pub trait Iterable<'a, K: ColumnType> {
141    type Iter: Iterator;
142
143    fn iter(column: &'a Column<K>, column_type: SqlType) -> Result<Self::Iter>;
144}
145
146enum StringInnerIterator<'a> {
147    String(&'a StringPool),
148    FixedString(*const u8, usize),
149}
150
151pub struct StringIterator<'a> {
152    inner: StringInnerIterator<'a>,
153    index: usize,
154    size: usize,
155}
156
157pub struct DecimalIterator<'a> {
158    ptr: *const u8,
159    end: *const u8,
160    precision: u8,
161    scale: u8,
162    nobits: NoBits,
163    _marker: marker::PhantomData<&'a ()>,
164}
165
166pub struct Ipv4Iterator<'a> {
167    ptr: *const u8,
168    end: *const u8,
169    _marker: marker::PhantomData<&'a ()>,
170}
171
172pub struct Ipv6Iterator<'a> {
173    ptr: *const u8,
174    end: *const u8,
175    _marker: marker::PhantomData<&'a ()>,
176}
177
178pub struct UuidIterator<'a> {
179    ptr: *const u8,
180    end: *const u8,
181    _marker: marker::PhantomData<&'a ()>,
182}
183
184pub struct DateIterator<'a> {
185    ptr: *const u16,
186    end: *const u16,
187    tz: Tz,
188    _marker: marker::PhantomData<&'a ()>,
189}
190
191enum DateTimeInnerIterator {
192    DateTime32(*const u32, *const u32),
193    DateTime64(*const i64, *const i64, u32),
194}
195
196pub struct DateTimeIterator<'a> {
197    inner: DateTimeInnerIterator,
198    tz: Tz,
199    _marker: marker::PhantomData<&'a ()>,
200}
201
202pub struct NullableIterator<'a, I> {
203    inner: I,
204    ptr: *const u8,
205    end: *const u8,
206    _marker: marker::PhantomData<&'a ()>,
207}
208
209pub struct ArrayIterator<'a, I> {
210    inner: I,
211    offsets: &'a [u64],
212    index: usize,
213    size: usize,
214}
215
216impl ExactSizeIterator for StringIterator<'_> {
217    #[inline(always)]
218    fn len(&self) -> usize {
219        self.size - self.index
220    }
221}
222
223impl<'a> Iterator for StringIterator<'a> {
224    type Item = &'a [u8];
225
226    #[inline]
227    fn next(&mut self) -> Option<Self::Item> {
228        match self.inner {
229            StringInnerIterator::String(string_pool) => {
230                if self.index == self.size {
231                    None
232                } else {
233                    let old_index = self.index;
234                    self.index += 1;
235                    Some(unsafe { string_pool.get_unchecked(old_index) })
236                }
237            }
238            StringInnerIterator::FixedString(buffer, str_len) => {
239                if self.index >= self.size {
240                    None
241                } else {
242                    let shift = self.index * str_len;
243                    self.index += 1;
244                    unsafe {
245                        let ptr = buffer.add(shift);
246                        Some(slice::from_raw_parts(ptr, str_len))
247                    }
248                }
249            }
250        }
251    }
252
253    #[inline]
254    fn size_hint(&self) -> (usize, Option<usize>) {
255        let exact = self.len();
256        (exact, Some(exact))
257    }
258
259    #[inline]
260    fn count(self) -> usize {
261        self.len()
262    }
263
264    #[inline]
265    fn nth(&mut self, n: usize) -> Option<Self::Item> {
266        if n >= self.len() {
267            // This iterator is now empty.
268            self.index = self.size;
269            return None;
270        }
271
272        self.index += n;
273        self.next()
274    }
275}
276
277impl FusedIterator for StringIterator<'_> {}
278
279impl<'a> DecimalIterator<'a> {
280    #[inline(always)]
281    unsafe fn next_unchecked_<T>(&mut self) -> Decimal
282    where
283        T: Copy + Sized,
284        i64: From<T>,
285    {
286        let current_value = *(self.ptr as *const T);
287        self.ptr = (self.ptr as *const T).offset(1) as *const u8;
288
289        Decimal {
290            underlying: current_value.into(),
291            nobits: self.nobits,
292            precision: self.precision,
293            scale: self.scale,
294        }
295    }
296
297    #[inline(always)]
298    unsafe fn next_unchecked(&mut self) -> Decimal {
299        match self.nobits {
300            NoBits::N32 => self.next_unchecked_::<i32>(),
301            NoBits::N64 => self.next_unchecked_::<i64>(),
302        }
303    }
304
305    #[inline(always)]
306    fn post_inc_start(&mut self, n: usize) {
307        unsafe {
308            match self.nobits {
309                NoBits::N32 => self.ptr = (self.ptr as *const i32).add(n) as *const u8,
310                NoBits::N64 => self.ptr = (self.ptr as *const i64).add(n) as *const u8,
311            }
312        }
313    }
314}
315
316impl<'a> ExactSizeIterator for DecimalIterator<'a> {
317    #[inline(always)]
318    fn len(&self) -> usize {
319        let size = match self.nobits {
320            NoBits::N32 => mem::size_of::<i32>(),
321            NoBits::N64 => mem::size_of::<i64>(),
322        };
323        (self.end as usize - self.ptr as usize) / size
324    }
325}
326
327iterator! { DecimalIterator: Decimal }
328
329iterator! { Ipv4Iterator: Ipv4Addr }
330
331impl<'a> Ipv4Iterator<'a> {
332    #[inline(always)]
333    unsafe fn next_unchecked(&mut self) -> Ipv4Addr {
334        let v = slice::from_raw_parts(self.ptr, 4);
335        let mut m = [0_u8; 4];
336        m.copy_from_slice(v);
337        m.reverse();
338        self.ptr = self.ptr.offset(4);
339
340        Ipv4Addr::from(m)
341    }
342
343    #[inline(always)]
344    fn post_inc_start(&mut self, n: usize) {
345        unsafe {
346            self.ptr = self.ptr.add(n * 4);
347        }
348    }
349}
350
351impl<'a> ExactSizeIterator for Ipv4Iterator<'a> {
352    #[inline(always)]
353    fn len(&self) -> usize {
354        let size = 4;
355        (self.end as usize - self.ptr as usize) / size
356    }
357}
358
359iterator! { Ipv6Iterator: Ipv6Addr }
360
361impl<'a> Ipv6Iterator<'a> {
362    #[inline(always)]
363    unsafe fn next_unchecked(&mut self) -> Ipv6Addr {
364        let v = slice::from_raw_parts(self.ptr, 16);
365        let mut m = [0_u8; 16];
366        m.copy_from_slice(v);
367        self.ptr = self.ptr.offset(16);
368
369        Ipv6Addr::from(m)
370    }
371
372    #[inline(always)]
373    fn post_inc_start(&mut self, n: usize) {
374        unsafe {
375            self.ptr = self.ptr.add(n * 16);
376        }
377    }
378}
379
380impl<'a> ExactSizeIterator for Ipv6Iterator<'a> {
381    #[inline(always)]
382    fn len(&self) -> usize {
383        let size = 16;
384        (self.end as usize - self.ptr as usize) / size
385    }
386}
387
388iterator! { UuidIterator: uuid::Uuid }
389
390impl<'a> UuidIterator<'a> {
391    #[inline(always)]
392    unsafe fn next_unchecked(&mut self) -> uuid::Uuid {
393        let v = slice::from_raw_parts(self.ptr, 16);
394        let mut m = [0_u8; 16];
395        m.copy_from_slice(v);
396        m[..8].reverse();
397        m[8..].reverse();
398        self.ptr = self.ptr.offset(16);
399
400        uuid::Uuid::from_bytes(m)
401    }
402
403    #[inline(always)]
404    fn post_inc_start(&mut self, n: usize) {
405        unsafe {
406            self.ptr = self.ptr.add(n * 16);
407        }
408    }
409}
410
411impl<'a> ExactSizeIterator for UuidIterator<'a> {
412    #[inline(always)]
413    fn len(&self) -> usize {
414        let size = 16;
415        (self.end as usize - self.ptr as usize) / size
416    }
417}
418
419impl<'a> DateIterator<'a> {
420    #[inline(always)]
421    unsafe fn next_unchecked(&mut self) -> NaiveDate {
422        let current_value = *self.ptr;
423        self.ptr = self.ptr.offset(1);
424
425        let time = self
426            .tz
427            .timestamp_opt(i64::from(current_value) * 24 * 3600, 0)
428            .unwrap();
429        time.date_naive()
430    }
431
432    #[inline(always)]
433    fn post_inc_start(&mut self, n: usize) {
434        unsafe { self.ptr = self.ptr.add(n) }
435    }
436}
437
438impl<'a> DateTimeIterator<'a> {
439    #[inline(always)]
440    unsafe fn next_unchecked(&mut self) -> DateTime<Tz> {
441        match &mut self.inner {
442            DateTimeInnerIterator::DateTime32(ptr, _) => {
443                let current_value = **ptr;
444                *ptr = ptr.offset(1);
445                self.tz.timestamp_opt(i64::from(current_value), 0).unwrap()
446            }
447            DateTimeInnerIterator::DateTime64(ptr, _, precision) => {
448                let current_value = **ptr;
449                *ptr = ptr.offset(1);
450                to_datetime(current_value, *precision, self.tz)
451            }
452        }
453    }
454
455    #[inline(always)]
456    fn post_inc_start(&mut self, n: usize) {
457        match &mut self.inner {
458            DateTimeInnerIterator::DateTime32(ptr, _) => unsafe { *ptr = ptr.add(n) },
459            DateTimeInnerIterator::DateTime64(ptr, _, _) => unsafe { *ptr = ptr.add(n) },
460        }
461    }
462}
463
464exact_size_iterator! { DateIterator: u16 }
465
466impl ExactSizeIterator for DateTimeIterator<'_> {
467    #[inline(always)]
468    fn len(&self) -> usize {
469        match self.inner {
470            DateTimeInnerIterator::DateTime32(ptr, end) => {
471                (end as usize - ptr as usize) / mem::size_of::<u32>()
472            }
473            DateTimeInnerIterator::DateTime64(ptr, end, _) => {
474                (end as usize - ptr as usize) / mem::size_of::<i64>()
475            }
476        }
477    }
478}
479
480iterator! { DateIterator: NaiveDate }
481
482impl<'a> Iterator for DateTimeIterator<'a> {
483    type Item = DateTime<Tz>;
484
485    #[inline]
486    fn next(&mut self) -> Option<Self::Item> {
487        if self.len() == 0 {
488            None
489        } else {
490            Some(unsafe { self.next_unchecked() })
491        }
492    }
493
494    #[inline]
495    fn size_hint(&self) -> (usize, Option<usize>) {
496        let exact = self.len();
497        (exact, Some(exact))
498    }
499
500    #[inline]
501    fn count(self) -> usize {
502        self.len()
503    }
504
505    #[inline]
506    fn nth(&mut self, n: usize) -> Option<Self::Item> {
507        if n >= self.len() {
508            // This iterator is now empty.
509            match &mut self.inner {
510                DateTimeInnerIterator::DateTime32(ptr, end) => *ptr = *end,
511                DateTimeInnerIterator::DateTime64(ptr, end, _) => *ptr = *end,
512            }
513            return None;
514        }
515        // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
516        self.post_inc_start(n);
517        self.next()
518    }
519}
520
521impl<'a, I> ExactSizeIterator for NullableIterator<'a, I>
522where
523    I: Iterator,
524{
525    #[inline(always)]
526    fn len(&self) -> usize {
527        let start = self.ptr;
528        self.end as usize - start as usize
529    }
530}
531
532impl<'a, I> Iterator for NullableIterator<'a, I>
533where
534    I: Iterator,
535{
536    type Item = Option<I::Item>;
537
538    fn next(&mut self) -> Option<Self::Item> {
539        if self.ptr == self.end {
540            return None;
541        }
542
543        let value = self.inner.next()?;
544        unsafe {
545            let flag = *self.ptr;
546            self.ptr = self.ptr.offset(1);
547
548            Some(if flag != 0 { None } else { Some(value) })
549        }
550    }
551
552    #[inline]
553    fn size_hint(&self) -> (usize, Option<usize>) {
554        let exact = self.len();
555        (exact, Some(exact))
556    }
557
558    #[inline]
559    fn count(self) -> usize {
560        self.len()
561    }
562}
563
564impl<'a, I: Iterator> FusedIterator for NullableIterator<'a, I> {}
565
566impl<'a, I: Iterator> ExactSizeIterator for ArrayIterator<'a, I> {
567    #[inline(always)]
568    fn len(&self) -> usize {
569        self.size - self.index
570    }
571}
572
573impl<'a, I: Iterator> Iterator for ArrayIterator<'a, I> {
574    type Item = Vec<I::Item>;
575
576    fn next(&mut self) -> Option<Self::Item> {
577        if self.index == self.size {
578            return None;
579        }
580
581        let start = if self.index > 0 {
582            self.offsets[self.index - 1] as usize
583        } else {
584            0_usize
585        };
586        let end = self.offsets[self.index] as usize;
587
588        let size = end - start;
589
590        let mut v = Vec::with_capacity(size);
591        for _ in 0..size {
592            if let Some(item) = self.inner.next() {
593                v.push(item);
594            }
595        }
596
597        self.index += 1;
598        Some(v)
599    }
600
601    #[inline]
602    fn size_hint(&self) -> (usize, Option<usize>) {
603        let exact = self.len();
604        (exact, Some(exact))
605    }
606
607    #[inline]
608    fn count(self) -> usize {
609        self.len()
610    }
611}
612
613impl<'a, I: Iterator> FusedIterator for ArrayIterator<'a, I> {}
614
615impl<'a> Iterable<'a, Simple> for Ipv4Addr {
616    type Iter = Ipv4Iterator<'a>;
617
618    fn iter(column: &'a Column<Simple>, _column_type: SqlType) -> Result<Self::Iter> {
619        let inner = unsafe {
620            let mut inner: *const u8 = ptr::null();
621            column.get_internal(&[&mut inner], 0)?;
622            &*(inner as *const Vec<u8>)
623        };
624
625        let ptr = inner.as_ptr();
626        let end = unsafe { ptr.add(inner.len()) };
627
628        Ok(Ipv4Iterator {
629            ptr,
630            end,
631            _marker: marker::PhantomData,
632        })
633    }
634}
635
636impl<'a> Iterable<'a, Simple> for Ipv6Addr {
637    type Iter = Ipv6Iterator<'a>;
638
639    fn iter(column: &'a Column<Simple>, _column_type: SqlType) -> Result<Self::Iter> {
640        let inner = unsafe {
641            let mut inner: *const u8 = ptr::null();
642            column.get_internal(&[&mut inner], 0)?;
643            &*(inner as *const Vec<u8>)
644        };
645
646        let ptr = inner.as_ptr();
647        let end = unsafe { ptr.add(inner.len()) };
648
649        Ok(Ipv6Iterator {
650            ptr,
651            end,
652            _marker: marker::PhantomData,
653        })
654    }
655}
656
657impl<'a> Iterable<'a, Simple> for uuid::Uuid {
658    type Iter = UuidIterator<'a>;
659
660    fn iter(column: &'a Column<Simple>, _column_type: SqlType) -> Result<Self::Iter> {
661        let inner = unsafe {
662            let mut inner: *const u8 = ptr::null();
663            column.get_internal(&[&mut inner], 0)?;
664            &*(inner as *const Vec<u8>)
665        };
666
667        let ptr = inner.as_ptr();
668        let end = unsafe { ptr.add(inner.len()) };
669
670        Ok(UuidIterator {
671            ptr,
672            end,
673            _marker: marker::PhantomData,
674        })
675    }
676}
677
678impl<'a> Iterable<'a, Simple> for &[u8] {
679    type Iter = StringIterator<'a>;
680
681    fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
682        let mut size: usize = 0;
683        let inner = match column_type {
684            SqlType::String => {
685                let string_pool = unsafe {
686                    let mut string_pool: *const u8 = ptr::null();
687                    column.get_internal(
688                        &[&mut string_pool, &mut size as *mut usize as *mut *const u8],
689                        0,
690                    )?;
691                    &*(string_pool as *const StringPool)
692                };
693
694                StringInnerIterator::String(string_pool)
695            }
696            SqlType::FixedString(str_len) => {
697                let buffer = unsafe {
698                    let mut buffer: *const u8 = ptr::null();
699                    column.get_internal(
700                        &[&mut buffer, &mut size as *mut usize as *mut *const u8],
701                        0,
702                    )?;
703                    assert_ne!(buffer, ptr::null());
704                    buffer
705                };
706
707                StringInnerIterator::FixedString(buffer, str_len)
708            }
709            _ => {
710                return Err(Error::FromSql(FromSqlError::InvalidType {
711                    src: column.sql_type().to_string(),
712                    dst: SqlType::String.to_string(),
713                }))
714            }
715        };
716
717        Ok(StringIterator {
718            inner,
719            size,
720            index: 0,
721        })
722    }
723}
724
725impl<'a> Iterable<'a, Simple> for Decimal {
726    type Iter = DecimalIterator<'a>;
727
728    fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
729        let (precision, scale) = if let SqlType::Decimal(precision, scale) = column_type {
730            (precision, scale)
731        } else {
732            return Err(Error::FromSql(FromSqlError::InvalidType {
733                src: column.sql_type().to_string(),
734                dst: SqlType::Decimal(255, 255).to_string(),
735            }));
736        };
737
738        let (ptr, size, nobits) = unsafe {
739            let mut ptr: *const u8 = ptr::null();
740            let mut size: usize = 0;
741            let mut nobits: NoBits = NoBits::N32;
742            column.get_internal(
743                &[
744                    &mut ptr,
745                    &mut size as *mut usize as *mut *const u8,
746                    &mut nobits as *mut NoBits as *mut *const u8,
747                ],
748                0,
749            )?;
750            assert_ne!(ptr, ptr::null());
751            (ptr, size, nobits)
752        };
753
754        let end = unsafe {
755            match nobits {
756                NoBits::N32 => (ptr as *const u32).add(size) as *const u8,
757                NoBits::N64 => (ptr as *const u64).add(size) as *const u8,
758            }
759        };
760
761        Ok(DecimalIterator {
762            ptr,
763            end,
764            precision,
765            scale,
766            nobits,
767            _marker: marker::PhantomData,
768        })
769    }
770}
771
772impl<'a> Iterable<'a, Simple> for DateTime<Tz> {
773    type Iter = DateTimeIterator<'a>;
774
775    fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
776        match column_type {
777            SqlType::DateTime(_) => (),
778            _ => {
779                return Err(Error::FromSql(FromSqlError::InvalidType {
780                    src: column.sql_type().to_string(),
781                    dst: "DateTime<?>".into(),
782                }));
783            }
784        }
785
786        let (byte_ptr, size, tz, precision) = date_iter(column)?;
787
788        let inner = match precision {
789            None => {
790                let ptr = byte_ptr as *const u32;
791                let end = unsafe { ptr.add(size) };
792                DateTimeInnerIterator::DateTime32(ptr, end)
793            }
794            Some(precision) => {
795                let ptr = byte_ptr as *const i64;
796                let end = unsafe { ptr.add(size) };
797                DateTimeInnerIterator::DateTime64(ptr, end, precision)
798            }
799        };
800
801        Ok(DateTimeIterator {
802            inner,
803            tz,
804            _marker: marker::PhantomData,
805        })
806    }
807}
808
809impl<'a> Iterable<'a, Simple> for NaiveDate {
810    type Iter = DateIterator<'a>;
811
812    fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
813        if column_type != SqlType::Date {
814            return Err(Error::FromSql(FromSqlError::InvalidType {
815                src: column.sql_type().to_string(),
816                dst: SqlType::Date.to_string(),
817            }));
818        };
819
820        let (byte_ptr, size, tz, precision) = date_iter(column)?;
821        assert!(precision.is_none());
822        let ptr = byte_ptr as *const u16;
823        let end = unsafe { ptr.add(size) };
824        Ok(DateIterator {
825            ptr,
826            end,
827            tz,
828            _marker: marker::PhantomData,
829        })
830    }
831}
832
833fn date_iter(column: &Column<Simple>) -> Result<(*const u8, usize, Tz, Option<u32>)> {
834    let (ptr, size, tz, precision) = unsafe {
835        let mut ptr: *const u8 = ptr::null();
836        let mut tz: *const Tz = ptr::null();
837        let mut size: usize = 0;
838        let mut precision: Option<u32> = None;
839        column.get_internal(
840            &[
841                &mut ptr as *mut *const u8,
842                &mut tz as *mut *const Tz as *mut *const u8,
843                &mut size as *mut usize as *mut *const u8,
844                &mut precision as *mut Option<u32> as *mut *const u8,
845            ],
846            0,
847        )?;
848        assert_ne!(ptr, ptr::null());
849        assert_ne!(tz, ptr::null());
850        (ptr, size, &*tz, precision)
851    };
852
853    Ok((ptr, size, *tz, precision))
854}
855
856impl<'a, T> Iterable<'a, Simple> for Option<T>
857where
858    T: Iterable<'a, Simple>,
859{
860    type Iter = NullableIterator<'a, T::Iter>;
861
862    fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
863        let inner = if let SqlType::Nullable(inner_type) = column_type {
864            T::iter(column, inner_type.clone())?
865        } else {
866            return Err(Error::FromSql(FromSqlError::InvalidType {
867                src: column_type.to_string(),
868                dst: "Nullable".into(),
869            }));
870        };
871
872        let (ptr, end) = unsafe {
873            let mut ptr: *const u8 = ptr::null();
874            let mut size: usize = 0;
875            column.get_internal(
876                &[&mut ptr, &mut size as *mut usize as *mut *const u8],
877                column_type.level(),
878            )?;
879            assert_ne!(ptr, ptr::null());
880            let end = ptr.add(size);
881            (ptr, end)
882        };
883
884        Ok(NullableIterator {
885            inner,
886            ptr,
887            end,
888            _marker: marker::PhantomData,
889        })
890    }
891}
892
893impl<'a, T> Iterable<'a, Simple> for Vec<T>
894where
895    T: Iterable<'a, Simple>,
896{
897    type Iter = ArrayIterator<'a, T::Iter>;
898
899    fn iter(column: &'a Column<Simple>, column_type: SqlType) -> Result<Self::Iter> {
900        let inner = if let SqlType::Array(inner_type) = column_type {
901            T::iter(column, inner_type.clone())?
902        } else {
903            return Err(Error::FromSql(FromSqlError::InvalidType {
904                src: column_type.to_string(),
905                dst: "Array".into(),
906            }));
907        };
908
909        let mut size: usize = 0;
910        let offsets = unsafe {
911            let mut ptr: *const u8 = ptr::null();
912            column.get_internal(
913                &[&mut ptr, &mut size as *mut usize as *mut *const u8],
914                column_type.level(),
915            )?;
916            assert_ne!(ptr, ptr::null());
917            slice::from_raw_parts(ptr as *const u64, size)
918        };
919
920        Ok(ArrayIterator {
921            inner,
922            offsets,
923            index: 0,
924            size,
925        })
926    }
927}
928
929pub struct ComplexIterator<'a, T>
930where
931    T: Iterable<'a, Simple>,
932{
933    column_type: SqlType,
934
935    data: &'a Vec<ArcColumnData>,
936
937    current_index: usize,
938    current: Option<<T as Iterable<'a, Simple>>::Iter>,
939
940    _marker: marker::PhantomData<T>,
941}
942
943impl<'a, T> Iterator for ComplexIterator<'a, T>
944where
945    T: Iterable<'a, Simple>,
946{
947    type Item = <<T as Iterable<'a, Simple>>::Iter as Iterator>::Item;
948
949    fn next(&mut self) -> Option<Self::Item> {
950        if self.current_index == self.data.len() && self.current.is_none() {
951            return None;
952        }
953
954        if self.current.is_none() {
955            let column: Column<Simple> = Column {
956                name: String::new(),
957                data: self.data[self.current_index].clone(),
958                _marker: marker::PhantomData,
959            };
960
961            let iter =
962                unsafe { T::iter(mem::transmute(&column), self.column_type.clone()) }.unwrap();
963
964            self.current = Some(iter);
965            self.current_index += 1;
966        }
967
968        let ret = self.current.as_mut().and_then(|iter| iter.next());
969
970        match ret {
971            None => {
972                self.current = None;
973                self.next()
974            }
975            Some(r) => Some(r),
976        }
977    }
978}
979
980impl<'a, T> Iterable<'a, Complex> for T
981where
982    T: Iterable<'a, Simple> + 'a,
983{
984    type Iter = ComplexIterator<'a, T>;
985
986    fn iter(column: &Column<Complex>, column_type: SqlType) -> Result<Self::Iter> {
987        let data: &Vec<ArcColumnData> = unsafe {
988            let mut data: *const Vec<ArcColumnData> = ptr::null();
989
990            column.get_internal(
991                &[&mut data as *mut *const Vec<ArcColumnData> as *mut *const u8],
992                0xff,
993            )?;
994
995            &*data
996        };
997
998        Ok(ComplexIterator {
999            column_type,
1000            data,
1001
1002            current_index: 0,
1003            current: None,
1004
1005            _marker: marker::PhantomData,
1006        })
1007    }
1008}