Skip to main content

scylla_cql_core/deserialize/
value.rs

1//! Provides types for dealing with CQL value deserialization.
2
3use std::{
4    borrow::Cow,
5    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
6    hash::{BuildHasher, Hash},
7    net::IpAddr,
8    sync::Arc,
9};
10
11use bytes::Bytes;
12use uuid::Uuid;
13
14use std::fmt::Display;
15
16use thiserror::Error;
17
18use super::{DeserializationError, FrameSlice, TypeCheckError, make_error_replace_rust_name};
19use crate::frame::frame_errors::LowLevelDeserializationError;
20use crate::frame::response::result::CollectionType;
21use crate::frame::response::result::UserDefinedType;
22use crate::frame::response::result::{ColumnType, NativeType};
23use crate::frame::types;
24use crate::value::CqlVarintBorrowed;
25use crate::value::{
26    Counter, CqlDate, CqlDecimal, CqlDecimalBorrowed, CqlDuration, CqlTime, CqlTimestamp,
27    CqlTimeuuid, CqlValue, CqlVarint,
28};
29
30// Re-export for backwards compatibility. These types were moved to crate::value module.
31// Note: deprecated doesn't work on re-exports, users won't get the warning.
32// Added it anyway for documentation purposes.
33// TODO(2.0): Remove those re-exports.
34#[deprecated(since = "1.5.0", note = "Moved to `scylla_cql::value` module")]
35pub use crate::value::Emptiable;
36#[deprecated(since = "1.5.0", note = "Moved to `scylla_cql::value` module")]
37pub use crate::value::MaybeEmpty;
38
39/// A type that can be deserialized from a column value inside a row that was
40/// returned from a query.
41///
42/// For tips on how to write a custom implementation of this trait, see the
43/// documentation of the parent module.
44///
45/// The crate also provides a derive macro which allows to automatically
46/// implement the trait for a custom type. For more details on what the macro
47/// is capable of, see its documentation.
48pub trait DeserializeValue<'frame, 'metadata>
49where
50    Self: Sized,
51{
52    /// Checks that the column type matches what this type expects.
53    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError>;
54
55    /// Deserialize a column value from given serialized representation.
56    ///
57    /// This function can assume that the driver called `type_check` to verify
58    /// the column's type. Note that `deserialize` is not an unsafe function,
59    /// so it should not use the assumption about `type_check` being called
60    /// as an excuse to run `unsafe` code.
61    fn deserialize(
62        typ: &'metadata ColumnType<'metadata>,
63        v: Option<FrameSlice<'frame>>,
64    ) -> Result<Self, DeserializationError>;
65}
66
67impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for CqlValue {
68    fn type_check(_typ: &ColumnType) -> Result<(), TypeCheckError> {
69        // CqlValue accepts all possible CQL types
70        Ok(())
71    }
72
73    fn deserialize(
74        typ: &'metadata ColumnType<'metadata>,
75        v: Option<FrameSlice<'frame>>,
76    ) -> Result<Self, DeserializationError> {
77        use crate::frame::response::result::ColumnType::*;
78        use crate::frame::response::result::NativeType::*;
79
80        let mut frame_slice = ensure_not_null_frame_slice::<Self>(typ, v)?;
81
82        if frame_slice.as_slice().is_empty() {
83            match typ {
84                Native(Ascii) | Native(Blob) | Native(Text) => {
85                    // can't be empty
86                }
87                _ => return Ok(CqlValue::Empty),
88            }
89        }
90
91        // We re-create `v` from our frame_slice for delegating to other DeserializeValue impls.
92        let v = Some(frame_slice);
93
94        Ok(
95            #[deny(clippy::wildcard_enum_match_arm)]
96            match typ {
97                Native(Ascii) => {
98                    let s = String::deserialize(typ, v)?;
99                    CqlValue::Ascii(s)
100                }
101                Native(Boolean) => {
102                    let b = bool::deserialize(typ, v)?;
103                    CqlValue::Boolean(b)
104                }
105                Native(Blob) => {
106                    let b = Vec::<u8>::deserialize(typ, v)?;
107                    CqlValue::Blob(b)
108                }
109                Native(Date) => {
110                    let d = CqlDate::deserialize(typ, v)?;
111                    CqlValue::Date(d)
112                }
113                Native(Counter) => {
114                    let c = crate::value::Counter::deserialize(typ, v)?;
115                    CqlValue::Counter(c)
116                }
117                Native(Decimal) => {
118                    let d = CqlDecimal::deserialize(typ, v)?;
119                    CqlValue::Decimal(d)
120                }
121                Native(Double) => {
122                    let d = f64::deserialize(typ, v)?;
123                    CqlValue::Double(d)
124                }
125                Native(Float) => {
126                    let f = f32::deserialize(typ, v)?;
127                    CqlValue::Float(f)
128                }
129                Native(Int) => {
130                    let i = i32::deserialize(typ, v)?;
131                    CqlValue::Int(i)
132                }
133                Native(SmallInt) => {
134                    let si = i16::deserialize(typ, v)?;
135                    CqlValue::SmallInt(si)
136                }
137                Native(TinyInt) => {
138                    let ti = i8::deserialize(typ, v)?;
139                    CqlValue::TinyInt(ti)
140                }
141                Native(BigInt) => {
142                    let bi = i64::deserialize(typ, v)?;
143                    CqlValue::BigInt(bi)
144                }
145                Native(Text) => {
146                    let s = String::deserialize(typ, v)?;
147                    CqlValue::Text(s)
148                }
149                Native(Timestamp) => {
150                    let t = CqlTimestamp::deserialize(typ, v)?;
151                    CqlValue::Timestamp(t)
152                }
153                Native(Time) => {
154                    let t = CqlTime::deserialize(typ, v)?;
155                    CqlValue::Time(t)
156                }
157                Native(Timeuuid) => {
158                    let t = CqlTimeuuid::deserialize(typ, v)?;
159                    CqlValue::Timeuuid(t)
160                }
161                Native(Duration) => {
162                    let d = CqlDuration::deserialize(typ, v)?;
163                    CqlValue::Duration(d)
164                }
165                Native(Inet) => {
166                    let i = IpAddr::deserialize(typ, v)?;
167                    CqlValue::Inet(i)
168                }
169                Native(Uuid) => {
170                    let uuid = uuid::Uuid::deserialize(typ, v)?;
171                    CqlValue::Uuid(uuid)
172                }
173                Native(Varint) => {
174                    let vi = CqlVarint::deserialize(typ, v)?;
175                    CqlValue::Varint(vi)
176                }
177                Collection {
178                    typ: CollectionType::List(_type_name),
179                    ..
180                } => {
181                    let l = Vec::<CqlValue>::deserialize(typ, v)?;
182                    CqlValue::List(l)
183                }
184                Collection {
185                    typ: CollectionType::Map(_key_type, _value_type),
186                    ..
187                } => {
188                    let iter = MapIterator::<'_, '_, CqlValue, CqlValue>::deserialize(typ, v)?;
189                    let m: Vec<(CqlValue, CqlValue)> = collect_exact_vec(iter)?;
190                    CqlValue::Map(m)
191                }
192                Collection {
193                    typ: CollectionType::Set(_type_name),
194                    ..
195                } => {
196                    let s = Vec::<CqlValue>::deserialize(typ, v)?;
197                    CqlValue::Set(s)
198                }
199                Vector { .. } => {
200                    let iter = VectorIterator::deserialize(typ, v)?;
201                    let v: Vec<CqlValue> = iter.into_vec()?;
202                    CqlValue::Vector(v)
203                }
204                UserDefinedType {
205                    definition: udt, ..
206                } => {
207                    let iter = UdtIterator::deserialize(typ, v)?;
208                    let fields: Vec<(String, Option<CqlValue>)> =
209                        collect_exact_vec(iter.map(|((col_name, col_type), res)| {
210                            res.and_then(|v| {
211                                let val = Option::<CqlValue>::deserialize(col_type, v.flatten())?;
212                                Ok((col_name.clone().into_owned(), val))
213                            })
214                        }))?;
215
216                    CqlValue::UserDefinedType {
217                        keyspace: udt.keyspace.clone().into_owned(),
218                        name: udt.name.clone().into_owned(),
219                        fields,
220                    }
221                }
222                Tuple(type_names) => {
223                    let t = collect_exact_vec(type_names.iter().map(
224                        |typ| -> Result<_, DeserializationError> {
225                            let raw = if frame_slice.is_empty() {
226                                // Special case: if there are no bytes left to read, consider the tuple element as null.
227                                // This is needed to handle tuples with fewer elements than expected
228                                // (see https://github.com/scylladb/scylla-rust-driver/issues/1452 for context).
229                                None
230                            } else {
231                                frame_slice.read_cql_bytes().map_err(|e| {
232                                    mk_deser_err::<CqlValue>(
233                                        typ,
234                                        BuiltinDeserializationErrorKind::RawCqlBytesReadError(e),
235                                    )
236                                })?
237                            };
238                            raw.map(|v| CqlValue::deserialize(typ, Some(v))).transpose()
239                        },
240                    ))?;
241                    CqlValue::Tuple(t)
242                }
243            },
244        )
245    }
246}
247
248// Option represents nullability of CQL values:
249// None corresponds to null,
250// Some(val) to non-null values.
251impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for Option<T>
252where
253    T: DeserializeValue<'frame, 'metadata>,
254{
255    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
256        T::type_check(typ).map_err(typck_error_replace_rust_name::<Self>)
257    }
258
259    fn deserialize(
260        typ: &'metadata ColumnType<'metadata>,
261        v: Option<FrameSlice<'frame>>,
262    ) -> Result<Self, DeserializationError> {
263        v.map(|_| T::deserialize(typ, v))
264            .transpose()
265            .map_err(deser_error_replace_rust_name::<Self>)
266    }
267}
268
269impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for MaybeEmpty<T>
270where
271    T: DeserializeValue<'frame, 'metadata> + Emptiable,
272{
273    #[inline]
274    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
275        <T as DeserializeValue<'frame, 'metadata>>::type_check(typ)
276            .map_err(typck_error_replace_rust_name::<Self>)
277    }
278
279    fn deserialize(
280        typ: &'metadata ColumnType<'metadata>,
281        v: Option<FrameSlice<'frame>>,
282    ) -> Result<Self, DeserializationError> {
283        let val = ensure_not_null_slice::<Self>(typ, v)?;
284        if val.is_empty() {
285            Ok(MaybeEmpty::Empty)
286        } else {
287            let v = <T as DeserializeValue<'frame, 'metadata>>::deserialize(typ, v)
288                .map_err(deser_error_replace_rust_name::<Self>)?;
289            Ok(MaybeEmpty::Value(v))
290        }
291    }
292}
293
294macro_rules! impl_strict_type {
295    ($t:ty, [$($cql:ident)|+], $conv:expr $(, $l:lifetime)?) => {
296        impl<$($l,)? 'frame, 'metadata> DeserializeValue<'frame, 'metadata> for $t
297        where
298            $('frame: $l)?
299        {
300            fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
301                // TODO: Format the CQL type names in the same notation
302                // that ScyllaDB/Cassandra uses internally and include them
303                // in such form in the error message
304                exact_type_check!(typ, $($cql),*);
305                Ok(())
306            }
307
308            // These bodies are a few instructions each once the error
309            // construction is outlined, and callers - in particular a
310            // collection's element loop - benefit a lot from inlining them.
311            #[inline]
312            fn deserialize(
313                typ: &'metadata ColumnType<'metadata>,
314                v: Option<FrameSlice<'frame>>,
315            ) -> Result<Self, DeserializationError> {
316                $conv(typ, v)
317            }
318        }
319    };
320
321    // Convenience pattern for omitting brackets if type-checking as single types.
322    ($t:ty, $cql:ident, $conv:expr $(, $l:lifetime)?) => {
323        impl_strict_type!($t, [$cql], $conv $(, $l)*);
324    };
325}
326
327// fixed numeric types
328
329macro_rules! impl_fixed_numeric_type {
330    ($t:ty, [$($cql:ident)|+]) => {
331        impl_strict_type!(
332            $t,
333            [$($cql)|*],
334            |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
335                const SIZE: usize = std::mem::size_of::<$t>();
336                let val = ensure_not_null_slice::<Self>(typ, v)?;
337                let arr = ensure_exact_length::<Self, SIZE>(typ, val)?;
338                Ok(<$t>::from_be_bytes(*arr))
339            }
340        );
341    };
342
343    // Convenience pattern for omitting brackets if type-checking as single types.
344    ($t:ty, $cql:ident) => {
345        impl_fixed_numeric_type!($t, [$cql]);
346    };
347}
348
349impl_strict_type!(
350    bool,
351    Boolean,
352    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
353        let val = ensure_not_null_slice::<Self>(typ, v)?;
354        let arr = ensure_exact_length::<Self, 1>(typ, val)?;
355        Ok(arr[0] != 0x00)
356    }
357);
358
359impl_fixed_numeric_type!(i8, TinyInt);
360impl_fixed_numeric_type!(i16, SmallInt);
361impl_fixed_numeric_type!(i32, Int);
362impl_fixed_numeric_type!(i64, BigInt);
363impl_fixed_numeric_type!(f32, Float);
364impl_fixed_numeric_type!(f64, Double);
365
366// other numeric types
367
368impl_strict_type!(
369    CqlVarint,
370    Varint,
371    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
372        let val = ensure_not_null_slice::<Self>(typ, v)?;
373        let val = ensure_not_empty::<Self>(typ, val)?;
374        Ok(CqlVarint::from_signed_bytes_be_slice(val))
375    }
376);
377
378impl_strict_type!(
379    CqlVarintBorrowed<'b>,
380    Varint,
381    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
382        let val = ensure_not_null_slice::<Self>(typ, v)?;
383        let val = ensure_not_empty::<Self>(typ, val)?;
384        Ok(CqlVarintBorrowed::from_signed_bytes_be_slice(val))
385    },
386    'b
387);
388
389#[cfg(feature = "num-bigint-03")]
390impl_strict_type!(
391    num_bigint_03::BigInt,
392    Varint,
393    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
394        let val = ensure_not_null_slice::<Self>(typ, v)?;
395        let val = ensure_not_empty::<Self>(typ, val)?;
396        Ok(num_bigint_03::BigInt::from_signed_bytes_be(val))
397    }
398);
399
400#[cfg(feature = "num-bigint-04")]
401impl_strict_type!(
402    num_bigint_04::BigInt,
403    Varint,
404    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
405        let val = ensure_not_null_slice::<Self>(typ, v)?;
406        let val = ensure_not_empty::<Self>(typ, val)?;
407        Ok(num_bigint_04::BigInt::from_signed_bytes_be(val))
408    }
409);
410
411fn get_unscaled_and_scale_from_decimal_column<'frame, T>(
412    typ: &ColumnType,
413    v: Option<FrameSlice<'frame>>,
414) -> Result<(&'frame [u8], i32), DeserializationError> {
415    let val = ensure_not_null_slice::<T>(typ, v)?;
416    let mut val = ensure_not_empty::<T>(typ, val)?;
417    let scale = types::read_int(&mut val).map_err(|err| {
418        mk_deser_err::<T>(
419            typ,
420            BuiltinDeserializationErrorKind::BadDecimalScale(err.into()),
421        )
422    })?;
423    // Such a decimal is malformed: the database accepts it on write,
424    // but fails to interpret it later.
425    if val.is_empty() {
426        return Err(mk_deser_err::<T>(
427            typ,
428            BuiltinDeserializationErrorKind::EmptyDecimalUnscaledValue,
429        ));
430    }
431    Ok((val, scale))
432}
433
434impl_strict_type!(
435    CqlDecimal,
436    Decimal,
437    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
438        let (unscaled, scale) = get_unscaled_and_scale_from_decimal_column::<Self>(typ, v)?;
439        Ok(CqlDecimal::from_signed_be_bytes_slice_and_exponent(
440            unscaled, scale,
441        ))
442    }
443);
444
445impl_strict_type!(
446    CqlDecimalBorrowed<'b>,
447    Decimal,
448    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
449        let (unscaled, scale) = get_unscaled_and_scale_from_decimal_column::<Self>(typ, v)?;
450        Ok(CqlDecimalBorrowed::from_signed_be_bytes_slice_and_exponent(
451            unscaled, scale,
452        ))
453    },
454    'b
455);
456
457#[cfg(feature = "bigdecimal-04")]
458impl_strict_type!(
459    bigdecimal_04::BigDecimal,
460    Decimal,
461    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
462        let (unscaled, scale) = get_unscaled_and_scale_from_decimal_column::<Self>(typ, v)?;
463        let int_value = bigdecimal_04::num_bigint::BigInt::from_signed_bytes_be(unscaled);
464        Ok(bigdecimal_04::BigDecimal::from((int_value, scale as i64)))
465    }
466);
467
468// blob
469
470impl_strict_type!(
471    &'a [u8],
472    Blob,
473    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
474        let val = ensure_not_null_slice::<Self>(typ, v)?;
475        Ok(val)
476    },
477    'a
478);
479impl_strict_type!(
480    Vec<u8>,
481    Blob,
482    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
483        let val = ensure_not_null_slice::<Self>(typ, v)?;
484        Ok(val.to_vec())
485    }
486);
487impl_strict_type!(
488    Bytes,
489    Blob,
490    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
491        let val = ensure_not_null_owned::<Self>(typ, v)?;
492        Ok(val)
493    }
494);
495
496// string
497
498macro_rules! impl_string_type {
499    ($t:ty, $conv:expr $(, $l:lifetime)?) => {
500        impl_strict_type!(
501            $t,
502            [Ascii | Text],
503            $conv
504            $(, $l)?
505        );
506    }
507}
508
509fn check_ascii<T>(typ: &ColumnType, s: &[u8]) -> Result<(), DeserializationError> {
510    if matches!(typ, ColumnType::Native(NativeType::Ascii)) && !s.is_ascii() {
511        return Err(mk_deser_err::<T>(
512            typ,
513            BuiltinDeserializationErrorKind::ExpectedAscii,
514        ));
515    }
516    Ok(())
517}
518
519impl_string_type!(
520    &'a str,
521    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
522        let val = ensure_not_null_slice::<Self>(typ, v)?;
523        check_ascii::<&str>(typ, val)?;
524        let s = std::str::from_utf8(val).map_err(|err| {
525            mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::InvalidUtf8(err))
526        })?;
527        Ok(s)
528    },
529    'a
530);
531impl_string_type!(
532    String,
533    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
534        let val = ensure_not_null_slice::<Self>(typ, v)?;
535        check_ascii::<String>(typ, val)?;
536        let s = std::str::from_utf8(val).map_err(|err| {
537            mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::InvalidUtf8(err))
538        })?;
539        Ok(s.to_string())
540    }
541);
542
543// TODO: Consider support for deserialization of string::String<Bytes>
544
545// counter
546
547impl_strict_type!(
548    Counter,
549    Counter,
550    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
551        let val = ensure_not_null_slice::<Self>(typ, v)?;
552        let arr = ensure_exact_length::<Self, 8>(typ, val)?;
553        let counter = i64::from_be_bytes(*arr);
554        Ok(Counter(counter))
555    }
556);
557
558// date and time types
559
560// duration
561impl_strict_type!(
562    CqlDuration,
563    Duration,
564    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
565        let mut val = ensure_not_null_slice::<Self>(typ, v)?;
566
567        macro_rules! mk_err {
568            ($err: expr) => {
569                mk_deser_err::<Self>(typ, $err)
570            };
571        }
572
573        let months_i64 = types::vint_decode(&mut val).map_err(|err| {
574            mk_err!(BuiltinDeserializationErrorKind::BadDate {
575                date_field: "months",
576                err: err.into()
577            })
578        })?;
579        let months = i32::try_from(months_i64)
580            .map_err(|_| mk_err!(BuiltinDeserializationErrorKind::ValueOverflow))?;
581
582        let days_i64 = types::vint_decode(&mut val).map_err(|err| {
583            mk_err!(BuiltinDeserializationErrorKind::BadDate {
584                date_field: "days",
585                err: err.into()
586            })
587        })?;
588        let days = i32::try_from(days_i64)
589            .map_err(|_| mk_err!(BuiltinDeserializationErrorKind::ValueOverflow))?;
590
591        let nanoseconds = types::vint_decode(&mut val).map_err(|err| {
592            mk_err!(BuiltinDeserializationErrorKind::BadDate {
593                date_field: "nanoseconds",
594                err: err.into()
595            })
596        })?;
597
598        Ok(CqlDuration {
599            months,
600            days,
601            nanoseconds,
602        })
603    }
604);
605
606impl_strict_type!(
607    CqlDate,
608    Date,
609    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
610        let val = ensure_not_null_slice::<Self>(typ, v)?;
611        let arr = ensure_exact_length::<Self, 4>(typ, val)?;
612        let days = u32::from_be_bytes(*arr);
613        Ok(CqlDate(days))
614    }
615);
616
617#[cfg(any(feature = "chrono-04", feature = "time-03"))]
618fn get_days_since_epoch_from_date_column<T>(
619    typ: &ColumnType,
620    v: Option<FrameSlice<'_>>,
621) -> Result<i64, DeserializationError> {
622    let val = ensure_not_null_slice::<T>(typ, v)?;
623    let arr = ensure_exact_length::<T, 4>(typ, val)?;
624    let days = u32::from_be_bytes(*arr);
625    let days_since_epoch = days as i64 - (1i64 << 31);
626    Ok(days_since_epoch)
627}
628
629#[cfg(feature = "chrono-04")]
630impl_strict_type!(chrono_04::NaiveDate, Date, |typ: &'metadata ColumnType<
631    'metadata,
632>,
633                                               v: Option<
634    FrameSlice<'frame>,
635>| {
636    let fail = || mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::ValueOverflow);
637    let days_since_epoch =
638        chrono_04::Duration::try_days(get_days_since_epoch_from_date_column::<Self>(typ, v)?)
639            .ok_or_else(fail)?;
640    chrono_04::NaiveDate::from_ymd_opt(1970, 1, 1)
641        .unwrap()
642        .checked_add_signed(days_since_epoch)
643        .ok_or_else(fail)
644});
645
646#[cfg(feature = "time-03")]
647impl_strict_type!(
648    time_03::Date,
649    Date,
650    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
651        let days_since_epoch =
652            time_03::Duration::days(get_days_since_epoch_from_date_column::<Self>(typ, v)?);
653        time_03::Date::from_calendar_date(1970, time_03::Month::January, 1)
654            .unwrap()
655            .checked_add(days_since_epoch)
656            .ok_or_else(|| {
657                mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::ValueOverflow)
658            })
659    }
660);
661
662fn get_nanos_from_time_column<T>(
663    typ: &ColumnType,
664    v: Option<FrameSlice<'_>>,
665) -> Result<i64, DeserializationError> {
666    let val = ensure_not_null_slice::<T>(typ, v)?;
667    let arr = ensure_exact_length::<T, 8>(typ, val)?;
668    let nanoseconds = i64::from_be_bytes(*arr);
669
670    // Valid values are in the range 0 to 86399999999999
671    if !(0..=86399999999999).contains(&nanoseconds) {
672        return Err(mk_deser_err::<T>(
673            typ,
674            BuiltinDeserializationErrorKind::ValueOverflow,
675        ));
676    }
677
678    Ok(nanoseconds)
679}
680
681impl_strict_type!(
682    CqlTime,
683    Time,
684    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
685        let nanoseconds = get_nanos_from_time_column::<Self>(typ, v)?;
686
687        Ok(CqlTime(nanoseconds))
688    }
689);
690
691#[cfg(feature = "chrono-04")]
692impl_strict_type!(chrono_04::NaiveTime, Time, |typ: &'metadata ColumnType<
693    'metadata,
694>,
695                                               v: Option<
696    FrameSlice<'frame>,
697>| {
698    let nanoseconds = get_nanos_from_time_column::<chrono_04::NaiveTime>(typ, v)?;
699
700    let naive_time: chrono_04::NaiveTime = CqlTime(nanoseconds)
701        .try_into()
702        .map_err(|_| mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::ValueOverflow))?;
703    Ok(naive_time)
704});
705
706#[cfg(feature = "time-03")]
707impl_strict_type!(
708    time_03::Time,
709    Time,
710    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
711        let nanoseconds = get_nanos_from_time_column::<time_03::Time>(typ, v)?;
712
713        let time: time_03::Time = CqlTime(nanoseconds).try_into().map_err(|_| {
714            mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::ValueOverflow)
715        })?;
716        Ok(time)
717    }
718);
719
720fn get_millis_from_timestamp_column<T>(
721    typ: &ColumnType,
722    v: Option<FrameSlice<'_>>,
723) -> Result<i64, DeserializationError> {
724    let val = ensure_not_null_slice::<T>(typ, v)?;
725    let arr = ensure_exact_length::<T, 8>(typ, val)?;
726    let millis = i64::from_be_bytes(*arr);
727
728    Ok(millis)
729}
730
731impl_strict_type!(
732    CqlTimestamp,
733    Timestamp,
734    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
735        let millis = get_millis_from_timestamp_column::<Self>(typ, v)?;
736        Ok(CqlTimestamp(millis))
737    }
738);
739
740#[cfg(feature = "chrono-04")]
741impl_strict_type!(
742    chrono_04::DateTime<chrono_04::Utc>,
743    Timestamp,
744    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
745        use chrono_04::TimeZone as _;
746
747        let millis = get_millis_from_timestamp_column::<Self>(typ, v)?;
748        match chrono_04::Utc.timestamp_millis_opt(millis) {
749            chrono_04::LocalResult::Single(datetime) => Ok(datetime),
750            _ => Err(mk_deser_err::<Self>(
751                typ,
752                BuiltinDeserializationErrorKind::ValueOverflow,
753            )),
754        }
755    }
756);
757
758#[cfg(feature = "time-03")]
759impl_strict_type!(
760    time_03::OffsetDateTime,
761    Timestamp,
762    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
763        let millis = get_millis_from_timestamp_column::<Self>(typ, v)?;
764        time_03::OffsetDateTime::from_unix_timestamp_nanos(millis as i128 * 1_000_000)
765            .map_err(|_| mk_deser_err::<Self>(typ, BuiltinDeserializationErrorKind::ValueOverflow))
766    }
767);
768
769// inet
770
771impl_strict_type!(
772    IpAddr,
773    Inet,
774    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
775        let val = ensure_not_null_slice::<Self>(typ, v)?;
776        if let Ok(ipv4) = <[u8; 4]>::try_from(val) {
777            Ok(IpAddr::from(ipv4))
778        } else if let Ok(ipv6) = <[u8; 16]>::try_from(val) {
779            Ok(IpAddr::from(ipv6))
780        } else {
781            Err(mk_deser_err::<Self>(
782                typ,
783                BuiltinDeserializationErrorKind::BadInetLength { got: val.len() },
784            ))
785        }
786    }
787);
788
789// uuid
790
791impl_strict_type!(
792    Uuid,
793    Uuid,
794    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
795        let val = ensure_not_null_slice::<Self>(typ, v)?;
796        let arr = ensure_exact_length::<Self, 16>(typ, val)?;
797        let i = u128::from_be_bytes(*arr);
798        Ok(uuid::Uuid::from_u128(i))
799    }
800);
801
802impl_strict_type!(
803    CqlTimeuuid,
804    Timeuuid,
805    |typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>| {
806        let val = ensure_not_null_slice::<Self>(typ, v)?;
807        let arr = ensure_exact_length::<Self, 16>(typ, val)?;
808        let i = u128::from_be_bytes(*arr);
809        Ok(CqlTimeuuid::from(uuid::Uuid::from_u128(i)))
810    }
811);
812
813// secrecy
814#[cfg(feature = "secrecy-08")]
815impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for secrecy_08::Secret<T>
816where
817    T: DeserializeValue<'frame, 'metadata> + secrecy_08::Zeroize,
818{
819    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
820        <T as DeserializeValue<'frame, 'metadata>>::type_check(typ)
821            .map_err(typck_error_replace_rust_name::<Self>)
822    }
823
824    fn deserialize(
825        typ: &'metadata ColumnType<'metadata>,
826        v: Option<FrameSlice<'frame>>,
827    ) -> Result<Self, DeserializationError> {
828        <T as DeserializeValue<'frame, 'metadata>>::deserialize(typ, v)
829            .map(secrecy_08::Secret::new)
830            .map_err(deser_error_replace_rust_name::<Self>)
831    }
832}
833
834#[cfg(feature = "secrecy-10")]
835impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for secrecy_10::SecretBox<T>
836where
837    T: DeserializeValue<'frame, 'metadata> + secrecy_10::zeroize::Zeroize,
838{
839    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
840        <T as DeserializeValue<'frame, 'metadata>>::type_check(typ)
841            .map_err(typck_error_replace_rust_name::<Self>)
842    }
843
844    fn deserialize(
845        typ: &'metadata ColumnType<'metadata>,
846        v: Option<FrameSlice<'frame>>,
847    ) -> Result<Self, DeserializationError> {
848        <T as DeserializeValue<'frame, 'metadata>>::deserialize(typ, v)
849            .map(|v| secrecy_10::SecretBox::new(Box::new(v)))
850            .map_err(deser_error_replace_rust_name::<Self>)
851    }
852}
853
854// Special implementation for SecretString (SecretBox<str>)
855#[cfg(feature = "secrecy-10")]
856impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for secrecy_10::SecretString {
857    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
858        <String as DeserializeValue<'frame, 'metadata>>::type_check(typ)
859            .map_err(typck_error_replace_rust_name::<Self>)
860    }
861
862    fn deserialize(
863        typ: &'metadata ColumnType<'metadata>,
864        v: Option<FrameSlice<'frame>>,
865    ) -> Result<Self, DeserializationError> {
866        <String as DeserializeValue<'frame, 'metadata>>::deserialize(typ, v)
867            .map(secrecy_10::SecretString::from)
868            .map_err(deser_error_replace_rust_name::<Self>)
869    }
870}
871
872// Special implementation for SecretSlice (SecretBox<[S]>)
873#[cfg(feature = "secrecy-10")]
874impl<'frame, 'metadata, S> DeserializeValue<'frame, 'metadata> for secrecy_10::SecretSlice<S>
875where
876    S: DeserializeValue<'frame, 'metadata> + secrecy_10::zeroize::Zeroize,
877    [S]: secrecy_10::zeroize::Zeroize,
878{
879    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
880        <Vec<S> as DeserializeValue<'frame, 'metadata>>::type_check(typ)
881            .map_err(typck_error_replace_rust_name::<Self>)
882    }
883
884    fn deserialize(
885        typ: &'metadata ColumnType<'metadata>,
886        v: Option<FrameSlice<'frame>>,
887    ) -> Result<Self, DeserializationError> {
888        <Vec<S> as DeserializeValue<'frame, 'metadata>>::deserialize(typ, v)
889            .map(secrecy_10::SecretSlice::from)
890            .map_err(deser_error_replace_rust_name::<Self>)
891    }
892}
893
894// collections
895
896make_error_replace_rust_name!(
897    /// Replaces the Rust type name in a [`BuiltinTypeCheckError`] wrapped inside
898    /// a [`TypeCheckError`] with the name of `RustT`.
899    ///
900    /// This is used to ensure that error messages report the correct Rust type name
901    /// even when the error originates from a helper/inner type used during deserialization,
902    /// rather than the top-level type being deserialized.
903    ///
904    /// # Assumptions
905    /// - This function should **only** be called inside a proper `type_check()` implementation.
906    /// - It should be called **before** the error is cloned, as it attempts to mutably access
907    ///   the inner error stored in `Arc`; if the `Arc` has already been cloned,
908    ///   a new [`BuiltinTypeCheckError`] will be allocated with the updated name instead.
909    pub(crate),
910    typck_error_replace_rust_name,
911    TypeCheckError,
912    BuiltinTypeCheckError
913);
914
915make_error_replace_rust_name!(
916    /// Replaces the Rust type name in a [`BuiltinDeserializationError`] wrapped inside
917    /// a [`DeserializationError`] with the name of `RustT`.
918    ///
919    /// This is used to ensure that error messages report the correct Rust type name
920    /// even when the error originates from a helper/inner type used during deserialization,
921    /// rather than the top-level type being deserialized.
922    ///
923    /// # Assumptions
924    /// - This function should **only** be called inside a proper `deserialize()` implementation.
925    /// - It should be called **before** the error is cloned, as it attempts to mutably access
926    ///   the inner error stored in `Arc`; if the `Arc` has already been cloned,
927    ///   a new [`BuiltinDeserializationError`] will be allocated with the updated name instead.
928    pub,
929    deser_error_replace_rust_name,
930    DeserializationError,
931    BuiltinDeserializationError
932);
933
934/// Collects a fallible iterator of known length into a `Vec`, allocating once.
935///
936/// `collect::<Result<Vec<_>, _>>()` would not: it goes through an adapter whose
937/// `size_hint` has a lower bound of 0, because iteration stops early on an
938/// error, and `Vec` sizes its allocation from the lower bound. The `Vec` is
939/// then grown geometrically from empty, which for a 1536-element vector means
940/// ten allocations instead of one.
941/// See <https://github.com/rust-lang/rust/issues/48994>.
942fn collect_exact_vec<T, E>(iter: impl ExactSizeIterator<Item = Result<T, E>>) -> Result<Vec<T>, E> {
943    let mut collected = Vec::with_capacity(iter.len());
944    for item in iter {
945        collected.push(item?);
946    }
947    Ok(collected)
948}
949
950// lists and sets
951
952/// An iterator over either a CQL set or list.
953#[derive(Debug, Clone)]
954pub struct ListlikeIterator<'frame, 'metadata, T> {
955    coll_typ: &'metadata ColumnType<'metadata>,
956    elem_typ: &'metadata ColumnType<'metadata>,
957    raw_iter: FixedLengthBytesSequenceIterator<'frame>,
958    phantom_data: std::marker::PhantomData<T>,
959}
960
961impl<'frame, 'metadata, T> ListlikeIterator<'frame, 'metadata, T> {
962    fn new(
963        coll_typ: &'metadata ColumnType<'metadata>,
964        elem_typ: &'metadata ColumnType<'metadata>,
965        count: usize,
966        slice: FrameSlice<'frame>,
967    ) -> Self {
968        Self {
969            coll_typ,
970            elem_typ,
971            raw_iter: FixedLengthBytesSequenceIterator::new(count, slice),
972            phantom_data: std::marker::PhantomData,
973        }
974    }
975
976    fn empty(
977        coll_typ: &'metadata ColumnType<'metadata>,
978        elem_typ: &'metadata ColumnType<'metadata>,
979    ) -> Self {
980        Self {
981            coll_typ,
982            elem_typ,
983            raw_iter: FixedLengthBytesSequenceIterator::empty(),
984            phantom_data: std::marker::PhantomData,
985        }
986    }
987}
988
989impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata>
990    for ListlikeIterator<'frame, 'metadata, T>
991where
992    T: DeserializeValue<'frame, 'metadata>,
993{
994    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
995        match typ {
996            ColumnType::Collection {
997                frozen: _,
998                typ: CollectionType::List(el_t),
999            }
1000            | ColumnType::Collection {
1001                frozen: _,
1002                typ: CollectionType::Set(el_t),
1003            } => <T as DeserializeValue<'frame, 'metadata>>::type_check(el_t).map_err(|err| {
1004                mk_typck_err::<Self>(
1005                    typ,
1006                    SetOrListTypeCheckErrorKind::ElementTypeCheckFailed(err),
1007                )
1008            }),
1009            _ => Err(mk_typck_err::<Self>(
1010                typ,
1011                BuiltinTypeCheckErrorKind::SetOrListError(
1012                    SetOrListTypeCheckErrorKind::NotSetOrList,
1013                ),
1014            )),
1015        }
1016    }
1017
1018    fn deserialize(
1019        typ: &'metadata ColumnType<'metadata>,
1020        v: Option<FrameSlice<'frame>>,
1021    ) -> Result<Self, DeserializationError> {
1022        let elem_typ = match typ {
1023            ColumnType::Collection {
1024                frozen: _,
1025                typ: CollectionType::List(elem_typ),
1026            }
1027            | ColumnType::Collection {
1028                frozen: _,
1029                typ: CollectionType::Set(elem_typ),
1030            } => elem_typ,
1031            _ => {
1032                unreachable!("Typecheck should have prevented this scenario!")
1033            }
1034        };
1035
1036        let mut v = if let Some(v) = v {
1037            v
1038        } else {
1039            return Ok(Self::empty(typ, elem_typ));
1040        };
1041
1042        let count = types::read_int_length(v.as_slice_mut()).map_err(|err| {
1043            mk_deser_err::<Self>(
1044                typ,
1045                SetOrListDeserializationErrorKind::LengthDeserializationFailed(
1046                    DeserializationError::new(err),
1047                ),
1048            )
1049        })?;
1050
1051        Ok(Self::new(typ, elem_typ, count, v))
1052    }
1053}
1054
1055impl<'frame, 'metadata, T> Iterator for ListlikeIterator<'frame, 'metadata, T>
1056where
1057    T: DeserializeValue<'frame, 'metadata>,
1058{
1059    type Item = Result<T, DeserializationError>;
1060
1061    #[inline]
1062    fn next(&mut self) -> Option<Self::Item> {
1063        let raw = self.raw_iter.next()?.map_err(|err| {
1064            mk_deser_err::<Self>(
1065                self.coll_typ,
1066                BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1067            )
1068        });
1069        Some(raw.and_then(|raw| {
1070            T::deserialize(self.elem_typ, raw).map_err(|err| {
1071                mk_deser_err::<Self>(
1072                    self.coll_typ,
1073                    SetOrListDeserializationErrorKind::ElementDeserializationFailed(err),
1074                )
1075            })
1076        }))
1077    }
1078
1079    // We only return `None` when underlying `FixedLengthBytesSequenceIterator` does.
1080    #[inline]
1081    fn size_hint(&self) -> (usize, Option<usize>) {
1082        self.raw_iter.size_hint()
1083    }
1084}
1085
1086// We only return `None` when underlying `FixedLengthBytesSequenceIterator` does.
1087// `FixedLengthBytesSequenceIterator` is ExactSize, so this can be too.
1088impl<'frame, 'metadata, T> ExactSizeIterator for ListlikeIterator<'frame, 'metadata, T> where
1089    T: DeserializeValue<'frame, 'metadata>
1090{
1091}
1092
1093impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for Vec<T>
1094where
1095    T: DeserializeValue<'frame, 'metadata>,
1096{
1097    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1098        // It makes sense for Set, List and Vector to deserialize to Vec.
1099        match typ {
1100            ColumnType::Collection {
1101                typ: CollectionType::List(_) | CollectionType::Set(_),
1102                ..
1103            } => ListlikeIterator::<'frame, 'metadata, T>::type_check(typ)
1104                .map_err(typck_error_replace_rust_name::<Self>),
1105            ColumnType::Vector { .. } => VectorIterator::<'frame, 'metadata, T>::type_check(typ)
1106                .map_err(typck_error_replace_rust_name::<Self>),
1107            _ => Err(mk_typck_err::<Self>(
1108                typ,
1109                BuiltinTypeCheckErrorKind::NotDeserializableToVec,
1110            )),
1111        }
1112    }
1113
1114    fn deserialize(
1115        typ: &'metadata ColumnType<'metadata>,
1116        v: Option<FrameSlice<'frame>>,
1117    ) -> Result<Self, DeserializationError> {
1118        match typ {
1119            ColumnType::Collection {
1120                typ: CollectionType::List(_) | CollectionType::Set(_),
1121                ..
1122            } => ListlikeIterator::<'frame, 'metadata, T>::deserialize(typ, v)
1123                .and_then(collect_exact_vec)
1124                .map_err(deser_error_replace_rust_name::<Self>),
1125            ColumnType::Vector { .. } => {
1126                VectorIterator::<'frame, 'metadata, T>::deserialize(typ, v)
1127                    .and_then(VectorIterator::into_vec)
1128                    .map_err(deser_error_replace_rust_name::<Self>)
1129            }
1130            _ => unreachable!("Should be prevented by typecheck"),
1131        }
1132    }
1133}
1134
1135impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for BTreeSet<T>
1136where
1137    T: DeserializeValue<'frame, 'metadata> + Ord,
1138{
1139    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1140        // It only makes sense for Set to deserialize to BTreeSet.
1141        // Deserializing List straight to BTreeSet would be lossy.
1142        match typ {
1143            ColumnType::Collection {
1144                frozen: _,
1145                typ: CollectionType::Set(_),
1146            } => ListlikeIterator::<'frame, 'metadata, T>::type_check(typ)
1147                .map_err(typck_error_replace_rust_name::<Self>),
1148            _ => Err(mk_typck_err::<Self>(
1149                typ,
1150                SetOrListTypeCheckErrorKind::NotSet,
1151            )),
1152        }
1153    }
1154
1155    fn deserialize(
1156        typ: &'metadata ColumnType<'metadata>,
1157        v: Option<FrameSlice<'frame>>,
1158    ) -> Result<Self, DeserializationError> {
1159        ListlikeIterator::<'frame, 'metadata, T>::deserialize(typ, v)
1160            .and_then(|it| it.collect::<Result<_, DeserializationError>>())
1161            .map_err(deser_error_replace_rust_name::<Self>)
1162    }
1163}
1164
1165impl<'frame, 'metadata, T, S> DeserializeValue<'frame, 'metadata> for HashSet<T, S>
1166where
1167    T: DeserializeValue<'frame, 'metadata> + Eq + Hash,
1168    S: BuildHasher + Default + 'frame,
1169{
1170    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1171        // It only makes sense for Set to deserialize to HashSet.
1172        // Deserializing List straight to HashSet would be lossy.
1173        match typ {
1174            ColumnType::Collection {
1175                frozen: _,
1176                typ: CollectionType::Set(_),
1177            } => ListlikeIterator::<'frame, 'metadata, T>::type_check(typ)
1178                .map_err(typck_error_replace_rust_name::<Self>),
1179            _ => Err(mk_typck_err::<Self>(
1180                typ,
1181                SetOrListTypeCheckErrorKind::NotSet,
1182            )),
1183        }
1184    }
1185
1186    fn deserialize(
1187        typ: &'metadata ColumnType<'metadata>,
1188        v: Option<FrameSlice<'frame>>,
1189    ) -> Result<Self, DeserializationError> {
1190        ListlikeIterator::<'frame, 'metadata, T>::deserialize(typ, v)
1191            .and_then(|it| {
1192                // Not `collect()`, for the reason described on `collect_exact_vec`.
1193                let mut set = HashSet::with_capacity_and_hasher(it.len(), S::default());
1194                for item in it {
1195                    set.insert(item?);
1196                }
1197                Ok(set)
1198            })
1199            .map_err(deser_error_replace_rust_name::<Self>)
1200    }
1201}
1202
1203/// A deserialization iterator over a CQL vector.
1204///
1205/// Deserialization of a vector is done in two ways, depending on the element type:
1206/// 1. If the element type is of a fixed-length, the iterator reads
1207///    a fixed, known number of bytes for each element and deserializes
1208///    according to the element type. The element count and element size
1209///    are not encoded as the count is known from the vector type
1210///    and the size is known from the element type.
1211///
1212/// 2. If the element type is of a variable-length, the iterator reads an vint
1213///    (variable-length integer) for each element, which indicates the number of bytes
1214///    to read for that element. Then, the iterator reads the specified number of bytes
1215///    and deserializes according to the element type. This, however, is in contradiction
1216///    with the CQL protocol, which specifies that the element count is encoded as a 4 byte int!
1217///    Alas, Cassandra does not respect the protocol, so ScyllaDB and this driver have to follow.
1218///
1219/// It would be nice to have a rule to determine if the element type is fixed-length or not,
1220/// however, we only have a heuristic. There are a few types that should, for all intents and purposes,
1221/// be considered fixed-length, but are not, e.g TinyInt. See ColumnType::type_size_for_vector() for the list.
1222#[derive(Debug, Clone)]
1223pub struct VectorIterator<'frame, 'metadata, T> {
1224    collection_type: &'metadata ColumnType<'metadata>,
1225    element_type: &'metadata ColumnType<'metadata>,
1226    remaining: usize,
1227    element_length: Option<usize>,
1228    slice: FrameSlice<'frame>,
1229    phantom_data: std::marker::PhantomData<T>,
1230}
1231
1232impl<'frame, 'metadata, T> VectorIterator<'frame, 'metadata, T> {
1233    fn new(
1234        collection_type: &'metadata ColumnType<'metadata>,
1235        element_type: &'metadata ColumnType<'metadata>,
1236        count: usize,
1237        element_length: Option<usize>,
1238        slice: FrameSlice<'frame>,
1239    ) -> Self {
1240        Self {
1241            collection_type,
1242            element_type,
1243            remaining: count,
1244            element_length,
1245            slice,
1246            phantom_data: std::marker::PhantomData,
1247        }
1248    }
1249}
1250
1251impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata>
1252    for VectorIterator<'frame, 'metadata, T>
1253where
1254    T: DeserializeValue<'frame, 'metadata>,
1255{
1256    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1257        match typ {
1258            ColumnType::Vector { typ: t, .. } => {
1259                <T as DeserializeValue<'frame, 'metadata>>::type_check(t).map_err(|err| {
1260                    mk_typck_err::<Self>(typ, VectorTypeCheckErrorKind::ElementTypeCheckFailed(err))
1261                })?;
1262                Ok(())
1263            }
1264            _ => Err(mk_typck_err::<Self>(
1265                typ,
1266                VectorTypeCheckErrorKind::NotVector,
1267            )),
1268        }
1269    }
1270
1271    fn deserialize(
1272        typ: &'metadata ColumnType<'metadata>,
1273        v: Option<FrameSlice<'frame>>,
1274    ) -> Result<Self, DeserializationError> {
1275        let (element_type, dimensions) = match typ {
1276            ColumnType::Vector {
1277                typ: element_type,
1278                dimensions,
1279            } => (element_type, dimensions),
1280            _ => {
1281                unreachable!("Typecheck should have prevented this scenario!")
1282            }
1283        };
1284
1285        let v = ensure_not_null_frame_slice::<Self>(typ, v)?;
1286
1287        Ok(Self::new(
1288            typ,
1289            element_type,
1290            *dimensions as usize,
1291            element_type.type_size_for_vector(),
1292            v,
1293        ))
1294    }
1295}
1296
1297impl<'frame, 'metadata, T> VectorIterator<'frame, 'metadata, T>
1298where
1299    T: DeserializeValue<'frame, 'metadata>,
1300{
1301    /// Deserializes the remaining elements into a `Vec`.
1302    ///
1303    /// Elements of a constant length occupy one contiguous run of bytes, so the
1304    /// run's length can be checked once instead of once per element. Going
1305    /// through `Iterator::next` instead costs, for every element, a bounds
1306    /// check and a `Result<Option<FrameSlice>>` to build and match - which for
1307    /// a 1536-dimension `vector<float>` is most of the work.
1308    pub fn into_vec(mut self) -> Result<Vec<T>, DeserializationError> {
1309        // A zero length would make `chunks_exact` panic, and `next` treats such
1310        // elements differently anyway (an empty slice reads as `None`).
1311        let Some(element_length) = self.element_length.filter(|&len| len > 0) else {
1312            return collect_exact_vec(self);
1313        };
1314
1315        let mut collected = Vec::with_capacity(self.remaining);
1316
1317        // Only the elements that are entirely present are taken in bulk.
1318        let bulk = (self.slice.as_slice().len() / element_length).min(self.remaining);
1319        let (run, rest) = self.slice.split_at(bulk * element_length);
1320        self.slice = rest;
1321        self.remaining -= bulk;
1322
1323        for raw in run.chunks_exact(element_length) {
1324            let elem = T::deserialize(self.element_type, Some(raw)).map_err(|err| {
1325                mk_deser_err::<Self>(
1326                    self.collection_type,
1327                    VectorDeserializationErrorKind::ElementDeserializationFailed(err),
1328                )
1329            })?;
1330            collected.push(elem);
1331        }
1332
1333        // Whatever the bulk pass did not cover - the elements of a truncated
1334        // frame - goes through `Iterator::next`, which reports the error
1335        // exactly as it would have without this fast path.
1336        for elem in self {
1337            collected.push(elem?);
1338        }
1339        Ok(collected)
1340    }
1341
1342    fn next_constant_length_elem(
1343        &mut self,
1344        element_length: usize,
1345    ) -> Option<<Self as Iterator>::Item> {
1346        self.remaining = self.remaining.checked_sub(1)?;
1347        let raw = self.slice.read_n_bytes(element_length).map_err(|err| {
1348            mk_deser_err::<Self>(
1349                self.collection_type,
1350                BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1351            )
1352        });
1353        Some(raw.and_then(|raw| {
1354            T::deserialize(self.element_type, raw).map_err(|err| {
1355                mk_deser_err::<Self>(
1356                    self.collection_type,
1357                    VectorDeserializationErrorKind::ElementDeserializationFailed(err),
1358                )
1359            })
1360        }))
1361    }
1362
1363    fn next_variable_length_elem(&mut self) -> Option<<Self as Iterator>::Item> {
1364        self.remaining = self.remaining.checked_sub(1)?;
1365        let size = types::unsigned_vint_decode(self.slice.as_slice_mut()).map_err(|err| {
1366            mk_deser_err::<Self>(
1367                self.collection_type,
1368                BuiltinDeserializationErrorKind::RawCqlBytesReadError(
1369                    LowLevelDeserializationError::IoError(Arc::new(err)),
1370                ),
1371            )
1372        });
1373        let raw = size
1374            .and_then(|size| {
1375                size.try_into().map_err(|_| {
1376                    mk_deser_err::<Self>(
1377                        self.collection_type,
1378                        BuiltinDeserializationErrorKind::ValueOverflow,
1379                    )
1380                })
1381            })
1382            .and_then(|size: usize| {
1383                self.slice.read_n_bytes(size).map_err(|err| {
1384                    mk_deser_err::<Self>(
1385                        self.collection_type,
1386                        BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1387                    )
1388                })
1389            });
1390
1391        Some(raw.and_then(|raw| {
1392            T::deserialize(self.element_type, raw).map_err(|err| {
1393                mk_deser_err::<Self>(
1394                    self.collection_type,
1395                    VectorDeserializationErrorKind::ElementDeserializationFailed(err),
1396                )
1397            })
1398        }))
1399    }
1400}
1401
1402impl<'frame, 'metadata, T> Iterator for VectorIterator<'frame, 'metadata, T>
1403where
1404    T: DeserializeValue<'frame, 'metadata>,
1405{
1406    type Item = Result<T, DeserializationError>;
1407
1408    fn next(&mut self) -> Option<Self::Item> {
1409        match self.element_length {
1410            Some(element_length) => self.next_constant_length_elem(element_length),
1411            None => self.next_variable_length_elem(),
1412        }
1413    }
1414
1415    #[inline]
1416    fn size_hint(&self) -> (usize, Option<usize>) {
1417        (self.remaining, Some(self.remaining))
1418    }
1419
1420    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1421        if let Some(element_length) = self.element_length {
1422            // Fast path: fixed-size elements — skip n elements by advancing the frame
1423            // slice by n * element_length bytes, without deserializing each skipped element.
1424            if n >= self.remaining {
1425                self.remaining = 0;
1426                return None;
1427            }
1428            if n > 0 {
1429                let bytes_to_skip = n * element_length;
1430                if let Err(err) = self.slice.read_n_bytes(bytes_to_skip) {
1431                    // We checked that `n < self.remaining`, so this won't cause
1432                    // negative overflow.
1433                    self.remaining -= n + 1;
1434                    return Some(Err(mk_deser_err::<Self>(
1435                        self.collection_type,
1436                        BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1437                    )));
1438                }
1439                self.remaining -= n;
1440            }
1441            self.next_constant_length_elem(element_length)
1442        } else {
1443            // Variable-length elements: fall back to the default sequential behaviour.
1444            for _ in 0..n {
1445                // Discard the item (which may be Ok or Err); only stop on exhaustion.
1446                let _ = self.next_variable_length_elem()?;
1447            }
1448            self.next_variable_length_elem()
1449        }
1450    }
1451}
1452
1453// This iterator always returns exactly `self.remaining` elements.
1454impl<'frame, 'metadata, T> ExactSizeIterator for VectorIterator<'frame, 'metadata, T> where
1455    T: DeserializeValue<'frame, 'metadata>
1456{
1457}
1458
1459/// An iterator over a CQL map.
1460#[derive(Debug, Clone)]
1461pub struct MapIterator<'frame, 'metadata, K, V> {
1462    coll_typ: &'metadata ColumnType<'metadata>,
1463    k_typ: &'metadata ColumnType<'metadata>,
1464    v_typ: &'metadata ColumnType<'metadata>,
1465    raw_iter: FixedLengthBytesSequenceIterator<'frame>,
1466    phantom_data_k: std::marker::PhantomData<K>,
1467    phantom_data_v: std::marker::PhantomData<V>,
1468}
1469
1470impl<'frame, 'metadata, K, V> MapIterator<'frame, 'metadata, K, V> {
1471    fn new(
1472        coll_typ: &'metadata ColumnType<'metadata>,
1473        k_typ: &'metadata ColumnType<'metadata>,
1474        v_typ: &'metadata ColumnType<'metadata>,
1475        count: usize,
1476        slice: FrameSlice<'frame>,
1477    ) -> Self {
1478        Self {
1479            coll_typ,
1480            k_typ,
1481            v_typ,
1482            raw_iter: FixedLengthBytesSequenceIterator::new(count, slice),
1483            phantom_data_k: std::marker::PhantomData,
1484            phantom_data_v: std::marker::PhantomData,
1485        }
1486    }
1487
1488    fn empty(
1489        coll_typ: &'metadata ColumnType<'metadata>,
1490        k_typ: &'metadata ColumnType<'metadata>,
1491        v_typ: &'metadata ColumnType<'metadata>,
1492    ) -> Self {
1493        Self {
1494            coll_typ,
1495            k_typ,
1496            v_typ,
1497            raw_iter: FixedLengthBytesSequenceIterator::empty(),
1498            phantom_data_k: std::marker::PhantomData,
1499            phantom_data_v: std::marker::PhantomData,
1500        }
1501    }
1502}
1503
1504impl<'frame, 'metadata, K, V> DeserializeValue<'frame, 'metadata>
1505    for MapIterator<'frame, 'metadata, K, V>
1506where
1507    K: DeserializeValue<'frame, 'metadata>,
1508    V: DeserializeValue<'frame, 'metadata>,
1509{
1510    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1511        match typ {
1512            ColumnType::Collection {
1513                frozen: _,
1514                typ: CollectionType::Map(k_t, v_t),
1515            } => {
1516                <K as DeserializeValue<'frame, 'metadata>>::type_check(k_t).map_err(|err| {
1517                    mk_typck_err::<Self>(typ, MapTypeCheckErrorKind::KeyTypeCheckFailed(err))
1518                })?;
1519                <V as DeserializeValue<'frame, 'metadata>>::type_check(v_t).map_err(|err| {
1520                    mk_typck_err::<Self>(typ, MapTypeCheckErrorKind::ValueTypeCheckFailed(err))
1521                })?;
1522                Ok(())
1523            }
1524            _ => Err(mk_typck_err::<Self>(typ, MapTypeCheckErrorKind::NotMap)),
1525        }
1526    }
1527
1528    fn deserialize(
1529        typ: &'metadata ColumnType<'metadata>,
1530        v: Option<FrameSlice<'frame>>,
1531    ) -> Result<Self, DeserializationError> {
1532        let (k_typ, v_typ) = match typ {
1533            ColumnType::Collection {
1534                frozen: _,
1535                typ: CollectionType::Map(k_t, v_t),
1536            } => (k_t, v_t),
1537            _ => {
1538                unreachable!("Typecheck should have prevented this scenario!")
1539            }
1540        };
1541
1542        let mut v = if let Some(v) = v {
1543            v
1544        } else {
1545            return Ok(Self::empty(typ, k_typ, v_typ));
1546        };
1547
1548        let count = types::read_int_length(v.as_slice_mut()).map_err(|err| {
1549            mk_deser_err::<Self>(
1550                typ,
1551                MapDeserializationErrorKind::LengthDeserializationFailed(
1552                    DeserializationError::new(err),
1553                ),
1554            )
1555        })?;
1556
1557        Ok(Self::new(typ, k_typ, v_typ, 2 * count, v))
1558    }
1559}
1560
1561impl<'frame, 'metadata, K, V> Iterator for MapIterator<'frame, 'metadata, K, V>
1562where
1563    K: DeserializeValue<'frame, 'metadata>,
1564    V: DeserializeValue<'frame, 'metadata>,
1565{
1566    type Item = Result<(K, V), DeserializationError>;
1567
1568    // Inlined together with `FixedLengthBytesSequenceIterator::next`, which this
1569    // calls twice: inlining only that one leaves this body too big to inline
1570    // itself, which costs more than it saves.
1571    #[inline]
1572    fn next(&mut self) -> Option<Self::Item> {
1573        // Note the lack of `?` - we want each call to `next()` to consume EXACTLY two items
1574        // from the inner iterator. This is necessary for correct and precise
1575        // `size_hint`, and thus the implementation of `ExactSizeIterator`.
1576        let raw_k_result = self.raw_iter.next();
1577        let raw_v_result = self.raw_iter.next();
1578        let raw_k = match raw_k_result {
1579            Some(Ok(raw_k)) => raw_k,
1580            Some(Err(err)) => {
1581                return Some(Err(mk_deser_err::<Self>(
1582                    self.coll_typ,
1583                    BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1584                )));
1585            }
1586            None => return None,
1587        };
1588        let raw_v = match raw_v_result {
1589            Some(Ok(raw_v)) => raw_v,
1590            Some(Err(err)) => {
1591                return Some(Err(mk_deser_err::<Self>(
1592                    self.coll_typ,
1593                    BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1594                )));
1595            }
1596            None => return None,
1597        };
1598
1599        let do_next = || -> Result<(K, V), DeserializationError> {
1600            let k = K::deserialize(self.k_typ, raw_k).map_err(|err| {
1601                mk_deser_err::<Self>(
1602                    self.coll_typ,
1603                    MapDeserializationErrorKind::KeyDeserializationFailed(err),
1604                )
1605            })?;
1606            let v = V::deserialize(self.v_typ, raw_v).map_err(|err| {
1607                mk_deser_err::<Self>(
1608                    self.coll_typ,
1609                    MapDeserializationErrorKind::ValueDeserializationFailed(err),
1610                )
1611            })?;
1612            Ok((k, v))
1613        };
1614        Some(do_next())
1615    }
1616
1617    fn size_hint(&self) -> (usize, Option<usize>) {
1618        // Each call to `next()` consumes exactly two items from the iterator.
1619        // If, and only if, both are `Some`, this iterator returns `Some`.
1620        // This makes its item number precise, given that the inner iterator
1621        // is ExactSizeIterator.
1622        let len = self.raw_iter.len() / 2;
1623        (len, Some(len))
1624    }
1625}
1626
1627impl<'frame, 'metadata, K, V> ExactSizeIterator for MapIterator<'frame, 'metadata, K, V>
1628where
1629    K: DeserializeValue<'frame, 'metadata>,
1630    V: DeserializeValue<'frame, 'metadata>,
1631{
1632}
1633
1634impl<'frame, 'metadata, K, V> DeserializeValue<'frame, 'metadata> for BTreeMap<K, V>
1635where
1636    K: DeserializeValue<'frame, 'metadata> + Ord,
1637    V: DeserializeValue<'frame, 'metadata>,
1638{
1639    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1640        MapIterator::<'frame, 'metadata, K, V>::type_check(typ)
1641            .map_err(typck_error_replace_rust_name::<Self>)
1642    }
1643
1644    fn deserialize(
1645        typ: &'metadata ColumnType<'metadata>,
1646        v: Option<FrameSlice<'frame>>,
1647    ) -> Result<Self, DeserializationError> {
1648        MapIterator::<'frame, 'metadata, K, V>::deserialize(typ, v)
1649            .and_then(|it| it.collect::<Result<_, DeserializationError>>())
1650            .map_err(deser_error_replace_rust_name::<Self>)
1651    }
1652}
1653
1654impl<'frame, 'metadata, K, V, S> DeserializeValue<'frame, 'metadata> for HashMap<K, V, S>
1655where
1656    K: DeserializeValue<'frame, 'metadata> + Eq + Hash,
1657    V: DeserializeValue<'frame, 'metadata>,
1658    S: BuildHasher + Default + 'frame,
1659{
1660    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1661        MapIterator::<'frame, 'metadata, K, V>::type_check(typ)
1662            .map_err(typck_error_replace_rust_name::<Self>)
1663    }
1664
1665    fn deserialize(
1666        typ: &'metadata ColumnType<'metadata>,
1667        v: Option<FrameSlice<'frame>>,
1668    ) -> Result<Self, DeserializationError> {
1669        MapIterator::<'frame, 'metadata, K, V>::deserialize(typ, v)
1670            .and_then(|it| {
1671                // Not `collect()`, for the reason described on `collect_exact_vec`.
1672                let mut map = HashMap::with_capacity_and_hasher(it.len(), S::default());
1673                for item in it {
1674                    let (key, value) = item?;
1675                    map.insert(key, value);
1676                }
1677                Ok(map)
1678            })
1679            .map_err(deser_error_replace_rust_name::<Self>)
1680    }
1681}
1682
1683/// A type that pairs a frame slice with its column metadata during deserialization.
1684/// This is useful when you need both the raw serialized data and the type information
1685/// to properly interpret or further deserialize the value.
1686pub struct FrameSliceWithMetadata<'frame, 'metadata> {
1687    pub frame_slice: Option<FrameSlice<'frame>>,
1688    pub column_type: &'metadata ColumnType<'metadata>,
1689}
1690
1691/// What is the purpose of implementing DeserializeValue for FrameSliceWithMetadata<'_, '_>?
1692///
1693/// Sometimes users might be interested in getting both the raw frame slice and the column
1694/// metadata together during deserialization. This allows deferred or custom deserialization
1695/// where the user needs access to the type information alongside the serialized bytes.
1696/// Implementing DeserializeValue for FrameSliceWithMetadata<'_, '_> allows us to
1697/// simplify our interface and provide this capability directly.
1698impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata>
1699    for FrameSliceWithMetadata<'frame, 'metadata>
1700{
1701    fn type_check(_typ: &ColumnType) -> Result<(), TypeCheckError> {
1702        Ok(())
1703    }
1704
1705    fn deserialize(
1706        typ: &'metadata ColumnType<'metadata>,
1707        v: Option<FrameSlice<'frame>>,
1708    ) -> Result<Self, DeserializationError> {
1709        Ok(FrameSliceWithMetadata {
1710            frame_slice: v,
1711            column_type: typ,
1712        })
1713    }
1714}
1715
1716// tuples
1717
1718// Implements tuple deserialization.
1719// The generated impl expects that the serialized data contains exactly the given amount of values.
1720macro_rules! impl_tuple {
1721    ($($Ti:ident),*; $($idx:literal),*; $($idf:ident),*) => {
1722        impl<'frame, 'metadata, $($Ti),*> DeserializeValue<'frame, 'metadata> for ($($Ti,)*)
1723        where
1724            $($Ti: DeserializeValue<'frame, 'metadata>),*
1725        {
1726            fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1727                const TUPLE_LEN: usize = (&[$($idx),*] as &[i32]).len();
1728                let [$($idf),*] = ensure_tuple_type::<($($Ti,)*), TUPLE_LEN>(typ)?;
1729                $(
1730                    <$Ti>::type_check($idf).map_err(|err| mk_typck_err::<Self>(
1731                        typ,
1732                        TupleTypeCheckErrorKind::FieldTypeCheckFailed {
1733                            position: $idx,
1734                            err,
1735                        }
1736                    ))?;
1737                )*
1738                Ok(())
1739            }
1740
1741            fn deserialize(typ: &'metadata ColumnType<'metadata>, v: Option<FrameSlice<'frame>>) -> Result<Self, DeserializationError> {
1742                const TUPLE_LEN: usize = (&[$($idx),*] as &[i32]).len();
1743                // Safety: we are allowed to assume that type_check() was already called.
1744                let [$($idf),*] = ensure_tuple_type::<($($Ti,)*), TUPLE_LEN>(typ)
1745                    .expect("Type check should have prevented this!");
1746
1747                // Ignore the warning for the zero-sized tuple
1748                #[allow(unused)]
1749                let mut v = ensure_not_null_frame_slice::<Self>(typ, v)?;
1750                let ret = (
1751                    $(
1752                        {
1753                            let cql_bytes = if v.is_empty() {
1754                                // Special case: if there are no bytes left to read, consider the tuple element as null.
1755                                // This is needed to handle tuples with fewer elements than expected
1756                                // (see https://github.com/scylladb/scylla-rust-driver/issues/1452 for context).
1757                                None
1758                            } else {
1759                                v.read_cql_bytes().map_err(|err| DeserializationError::new(err))?
1760                            };
1761
1762                            <$Ti>::deserialize($idf, cql_bytes)
1763                                .map_err(|err| mk_deser_err::<Self>(
1764                                    typ,
1765                                    TupleDeserializationErrorKind::FieldDeserializationFailed {
1766                                        position: $idx,
1767                                        err,
1768                                    }
1769                                )
1770                            )?
1771                        },
1772                    )*
1773                );
1774                Ok(ret)
1775            }
1776        }
1777    }
1778}
1779
1780// Implements tuple deserialization for all tuple sizes up to predefined size.
1781// Accepts 3 lists, (see usage below the definition):
1782// - type parameters for the consecutive fields,
1783// - indices of the consecutive fields,
1784// - consecutive names for variables corresponding to each field.
1785//
1786// The idea is to recursively build prefixes of those lists (starting with an empty prefix)
1787// and for each prefix, implement deserialization for generic tuple represented by it.
1788// The < > brackets aid syntactically to separate the prefixes (positioned inside them)
1789// from the remaining suffixes (positioned beyond them).
1790macro_rules! impl_tuple_multiple {
1791    // The entry point to the macro.
1792    // Begins with implementing deserialization for (), then proceeds to the main recursive call.
1793    ($($Ti:ident),*; $($idx:literal),*; $($idf:ident),*) => {
1794        impl_tuple!(;;);
1795        impl_tuple_multiple!(
1796            $($Ti),* ; < > ;
1797            $($idx),*; < > ;
1798            $($idf),*; < >
1799        );
1800    };
1801
1802    // The termination condition. No more fields given to extend the tuple with.
1803    (;< $($Ti:ident,)* >;;< $($idx:literal,)* >;;< $($idf:ident,)* >) => {};
1804
1805    // The recursion. Upon each call, a new field is appended to the tuple
1806    // and deserialization is implemented for it.
1807    (
1808        $T_head:ident $(,$T_suffix:ident)*; < $($T_prefix:ident,)* > ;
1809        $idx_head:literal $(,$idx_suffix:literal)*; < $($idx_prefix:literal,)* >;
1810        $idf_head:ident $(,$idf_suffix:ident)* ; <$($idf_prefix:ident,)*>
1811    ) => {
1812        impl_tuple!(
1813            $($T_prefix,)* $T_head;
1814            $($idx_prefix, )* $idx_head;
1815            $($idf_prefix, )* $idf_head
1816        );
1817        impl_tuple_multiple!(
1818            $($T_suffix),* ; < $($T_prefix,)* $T_head, > ;
1819            $($idx_suffix),*; < $($idx_prefix, )* $idx_head, > ;
1820            $($idf_suffix),*; < $($idf_prefix, )* $idf_head, >
1821        );
1822    }
1823}
1824
1825pub(super) use impl_tuple_multiple;
1826
1827// Implements tuple deserialization for all tuple sizes up to 16.
1828impl_tuple_multiple!(
1829    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15;
1830    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15;
1831    t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15
1832);
1833
1834// udts
1835
1836/// An iterator over fields of a User Defined Type.
1837///
1838/// # Note
1839///
1840/// A serialized UDT will generally have one value for each field, but it is
1841/// allowed to have fewer. This iterator differentiates null values
1842/// from non-existent values in the following way:
1843///
1844/// - `None` - missing from the serialized form
1845/// - `Some(None)` - present, but null
1846/// - `Some(Some(...))` - non-null, present value
1847#[derive(Debug, Clone)]
1848pub struct UdtIterator<'frame, 'metadata> {
1849    all_fields: &'metadata [(Cow<'metadata, str>, ColumnType<'metadata>)],
1850    type_name: &'metadata str,
1851    keyspace: &'metadata str,
1852    remaining_fields: &'metadata [(Cow<'metadata, str>, ColumnType<'metadata>)],
1853    raw_iter: BytesSequenceIterator<'frame>,
1854}
1855
1856impl<'frame, 'metadata> UdtIterator<'frame, 'metadata> {
1857    fn new(
1858        fields: &'metadata [(Cow<'metadata, str>, ColumnType<'metadata>)],
1859        type_name: &'metadata str,
1860        keyspace: &'metadata str,
1861        slice: FrameSlice<'frame>,
1862    ) -> Self {
1863        Self {
1864            all_fields: fields,
1865            remaining_fields: fields,
1866            type_name,
1867            keyspace,
1868            raw_iter: BytesSequenceIterator::new(slice),
1869        }
1870    }
1871
1872    /// Returns remaining (i.e., not yet deserialized) fields of the UDT.
1873    #[inline]
1874    pub fn fields(&self) -> &'metadata [(Cow<'metadata, str>, ColumnType<'metadata>)] {
1875        self.remaining_fields
1876    }
1877}
1878
1879impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for UdtIterator<'frame, 'metadata> {
1880    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1881        match typ {
1882            ColumnType::UserDefinedType { .. } => Ok(()),
1883            _ => Err(mk_typck_err::<Self>(typ, UdtTypeCheckErrorKind::NotUdt)),
1884        }
1885    }
1886
1887    fn deserialize(
1888        typ: &'metadata ColumnType<'metadata>,
1889        v: Option<FrameSlice<'frame>>,
1890    ) -> Result<Self, DeserializationError> {
1891        let v = ensure_not_null_frame_slice::<Self>(typ, v)?;
1892        let (fields, type_name, keyspace) = match typ {
1893            ColumnType::UserDefinedType {
1894                definition: udt, ..
1895            } => (
1896                udt.field_types.as_ref(),
1897                udt.name.as_ref(),
1898                udt.keyspace.as_ref(),
1899            ),
1900            _ => {
1901                unreachable!("Typecheck should have prevented this scenario!")
1902            }
1903        };
1904        Ok(Self::new(fields, type_name, keyspace, v))
1905    }
1906}
1907
1908impl<'frame, 'metadata> Iterator for UdtIterator<'frame, 'metadata> {
1909    type Item = (
1910        &'metadata (Cow<'metadata, str>, ColumnType<'metadata>),
1911        Result<Option<Option<FrameSlice<'frame>>>, DeserializationError>,
1912    );
1913
1914    #[inline]
1915    fn next(&mut self) -> Option<Self::Item> {
1916        let (head, fields) = self.remaining_fields.split_first()?;
1917        self.remaining_fields = fields;
1918        let raw_res = match self.raw_iter.next() {
1919            // The field is there and it was parsed correctly
1920            Some(Ok(raw)) => Ok(Some(raw)),
1921
1922            // There were some bytes but they didn't parse as correct field value
1923            Some(Err(err)) => Err(mk_deser_err::<Self>(
1924                &ColumnType::UserDefinedType {
1925                    frozen: false,
1926                    definition: Arc::new(UserDefinedType {
1927                        name: self.type_name.into(),
1928                        keyspace: self.keyspace.into(),
1929                        field_types: self.all_fields.to_owned(),
1930                    }),
1931                },
1932                BuiltinDeserializationErrorKind::RawCqlBytesReadError(err),
1933            )),
1934
1935            // The field is just missing from the serialized form
1936            None => Ok(None),
1937        };
1938        Some((head, raw_res))
1939    }
1940
1941    fn size_hint(&self) -> (usize, Option<usize>) {
1942        // The iterator yields exactly one item per remaining field, regardless of whether
1943        // the serialized form contains a value for that field or not (missing fields are
1944        // reported as `Ok(None)`).
1945        let len = self.remaining_fields.len();
1946        (len, Some(len))
1947    }
1948}
1949
1950// The iterator yields exactly one item per remaining field, regardless of whether
1951// the serialized form contains a value for that field or not (missing fields are
1952// reported as `Ok(None)`).
1953impl<'frame, 'metadata> ExactSizeIterator for UdtIterator<'frame, 'metadata> {}
1954
1955// Container implementations
1956
1957impl<'frame, 'metadata, T: DeserializeValue<'frame, 'metadata>> DeserializeValue<'frame, 'metadata>
1958    for Box<T>
1959{
1960    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1961        T::type_check(typ).map_err(typck_error_replace_rust_name::<Self>)
1962    }
1963
1964    fn deserialize(
1965        typ: &'metadata ColumnType<'metadata>,
1966        v: Option<FrameSlice<'frame>>,
1967    ) -> Result<Self, DeserializationError> {
1968        T::deserialize(typ, v)
1969            .map(Box::new)
1970            .map_err(deser_error_replace_rust_name::<Self>)
1971    }
1972}
1973
1974impl<'frame, 'metadata, T: DeserializeValue<'frame, 'metadata>> DeserializeValue<'frame, 'metadata>
1975    for Arc<T>
1976{
1977    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1978        T::type_check(typ).map_err(typck_error_replace_rust_name::<Self>)
1979    }
1980
1981    fn deserialize(
1982        typ: &'metadata ColumnType<'metadata>,
1983        v: Option<FrameSlice<'frame>>,
1984    ) -> Result<Self, DeserializationError> {
1985        T::deserialize(typ, v)
1986            .map(Arc::new)
1987            .map_err(deser_error_replace_rust_name::<Self>)
1988    }
1989}
1990
1991impl<'frame, 'metadata, T: 'frame + ToOwned + ?Sized> DeserializeValue<'frame, 'metadata>
1992    for Cow<'frame, T>
1993where
1994    &'frame T: DeserializeValue<'frame, 'metadata>,
1995{
1996    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
1997        <&T>::type_check(typ).map_err(typck_error_replace_rust_name::<Self>)
1998    }
1999
2000    fn deserialize(
2001        typ: &'metadata ColumnType<'metadata>,
2002        v: Option<FrameSlice<'frame>>,
2003    ) -> Result<Self, DeserializationError> {
2004        <&T>::deserialize(typ, v)
2005            .map(Cow::Borrowed)
2006            .map_err(deser_error_replace_rust_name::<Self>)
2007    }
2008}
2009
2010// Special cases for Box<str> and Arc<str>
2011// The generic implementations above don't work for str. This is because
2012// DeserializeValue is implemented for &str, but not for str. We can't change this:
2013// the type for DeserializeValue must be Sized because it is returned from deserialize method.
2014
2015impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for Box<str> {
2016    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
2017        <String as DeserializeValue>::type_check(typ).map_err(typck_error_replace_rust_name::<Self>)
2018    }
2019
2020    fn deserialize(
2021        typ: &'metadata ColumnType<'metadata>,
2022        v: Option<FrameSlice<'frame>>,
2023    ) -> Result<Self, DeserializationError> {
2024        String::deserialize(typ, v)
2025            .map(String::into_boxed_str)
2026            .map_err(deser_error_replace_rust_name::<Self>)
2027    }
2028}
2029
2030impl<'frame, 'metadata> DeserializeValue<'frame, 'metadata> for Arc<str> {
2031    fn type_check(typ: &ColumnType) -> Result<(), TypeCheckError> {
2032        <&str as DeserializeValue>::type_check(typ).map_err(typck_error_replace_rust_name::<Self>)
2033    }
2034
2035    fn deserialize(
2036        typ: &'metadata ColumnType<'metadata>,
2037        v: Option<FrameSlice<'frame>>,
2038    ) -> Result<Self, DeserializationError> {
2039        <&str as DeserializeValue>::deserialize(typ, v)
2040            .map(Into::<Arc<str>>::into)
2041            .map_err(deser_error_replace_rust_name::<Self>)
2042    }
2043}
2044
2045// Utilities
2046
2047fn ensure_not_null_frame_slice<'frame, T>(
2048    typ: &ColumnType,
2049    v: Option<FrameSlice<'frame>>,
2050) -> Result<FrameSlice<'frame>, DeserializationError> {
2051    v.ok_or_else(|| mk_deser_err::<T>(typ, BuiltinDeserializationErrorKind::ExpectedNonNull))
2052}
2053
2054fn ensure_not_null_slice<'frame, T>(
2055    typ: &ColumnType,
2056    v: Option<FrameSlice<'frame>>,
2057) -> Result<&'frame [u8], DeserializationError> {
2058    ensure_not_null_frame_slice::<T>(typ, v).map(|frame_slice| frame_slice.as_slice())
2059}
2060
2061fn ensure_not_null_owned<T>(
2062    typ: &ColumnType,
2063    v: Option<FrameSlice>,
2064) -> Result<Bytes, DeserializationError> {
2065    ensure_not_null_frame_slice::<T>(typ, v).map(|frame_slice| frame_slice.to_bytes())
2066}
2067
2068fn ensure_not_empty<'frame, T>(
2069    typ: &ColumnType,
2070    v: &'frame [u8],
2071) -> Result<&'frame [u8], DeserializationError> {
2072    if v.is_empty() {
2073        return Err(mk_deser_err::<T>(
2074            typ,
2075            BuiltinDeserializationErrorKind::ExpectedNonEmpty,
2076        ));
2077    }
2078    Ok(v)
2079}
2080
2081fn ensure_exact_length<'frame, T, const SIZE: usize>(
2082    typ: &ColumnType,
2083    v: &'frame [u8],
2084) -> Result<&'frame [u8; SIZE], DeserializationError> {
2085    v.try_into().map_err(|_| {
2086        mk_deser_err::<T>(
2087            typ,
2088            BuiltinDeserializationErrorKind::ByteLengthMismatch {
2089                expected: SIZE,
2090                got: v.len(),
2091            },
2092        )
2093    })
2094}
2095
2096fn ensure_tuple_type<'a, 'b, T, const SIZE: usize>(
2097    typ: &'b ColumnType<'a>,
2098) -> Result<&'b [ColumnType<'a>; SIZE], TypeCheckError> {
2099    if let ColumnType::Tuple(typs_v) = typ {
2100        typs_v.as_slice().try_into().map_err(|_| {
2101            BuiltinTypeCheckErrorKind::TupleError(TupleTypeCheckErrorKind::WrongElementCount {
2102                rust_type_el_count: SIZE,
2103                cql_type_el_count: typs_v.len(),
2104            })
2105        })
2106    } else {
2107        Err(BuiltinTypeCheckErrorKind::TupleError(
2108            TupleTypeCheckErrorKind::NotTuple,
2109        ))
2110    }
2111    .map_err(|kind| mk_typck_err::<T>(typ, kind))
2112}
2113
2114// Helper iterators
2115
2116/// Iterates over a sequence of `[bytes]` items from a frame subslice, expecting
2117/// a particular number of items.
2118///
2119/// The iterator does not consider it to be an error if there are some bytes
2120/// remaining in the slice after parsing requested amount of items.
2121#[derive(Clone, Copy, Debug)]
2122pub struct FixedLengthBytesSequenceIterator<'frame> {
2123    slice: FrameSlice<'frame>,
2124    remaining: usize,
2125}
2126
2127impl<'frame> FixedLengthBytesSequenceIterator<'frame> {
2128    fn new(count: usize, slice: FrameSlice<'frame>) -> Self {
2129        Self {
2130            slice,
2131            remaining: count,
2132        }
2133    }
2134
2135    fn empty() -> Self {
2136        Self {
2137            slice: FrameSlice::new_empty(),
2138            remaining: 0,
2139        }
2140    }
2141}
2142
2143impl<'frame> Iterator for FixedLengthBytesSequenceIterator<'frame> {
2144    type Item = Result<Option<FrameSlice<'frame>>, LowLevelDeserializationError>;
2145
2146    // Not generic, so without this its body is not available for inlining into
2147    // the collection iterators wrapping it, in this crate or any other.
2148    #[inline]
2149    fn next(&mut self) -> Option<Self::Item> {
2150        self.remaining = self.remaining.checked_sub(1)?;
2151        Some(self.slice.read_cql_bytes())
2152    }
2153
2154    // Always yields exactly the requested number of elements.
2155    // Some of them may be errors, but it is irrelevant for `size_hint`.
2156    fn size_hint(&self) -> (usize, Option<usize>) {
2157        (self.remaining, Some(self.remaining))
2158    }
2159}
2160
2161// Always yields exactly the requested number of elements.
2162// Some of them may be errors, but it is irrelevant here.
2163impl<'frame> ExactSizeIterator for FixedLengthBytesSequenceIterator<'frame> {}
2164
2165/// Iterates over a sequence of `[bytes]` items from a frame subslice.
2166///
2167/// The `[bytes]` items are parsed until the end of subslice is reached.
2168#[derive(Clone, Copy, Debug)]
2169pub struct BytesSequenceIterator<'frame> {
2170    slice: FrameSlice<'frame>,
2171}
2172
2173impl<'frame> BytesSequenceIterator<'frame> {
2174    fn new(slice: FrameSlice<'frame>) -> Self {
2175        Self { slice }
2176    }
2177}
2178
2179impl<'frame> From<FrameSlice<'frame>> for BytesSequenceIterator<'frame> {
2180    #[inline]
2181    fn from(slice: FrameSlice<'frame>) -> Self {
2182        Self::new(slice)
2183    }
2184}
2185
2186impl<'frame> Iterator for BytesSequenceIterator<'frame> {
2187    type Item = Result<Option<FrameSlice<'frame>>, LowLevelDeserializationError>;
2188
2189    #[inline]
2190    fn next(&mut self) -> Option<Self::Item> {
2191        if self.slice.as_slice().is_empty() {
2192            None
2193        } else {
2194            Some(self.slice.read_cql_bytes())
2195        }
2196    }
2197}
2198
2199// Error facilities
2200
2201/// Type checking of one of the built-in types failed.
2202#[derive(Debug, Error, Clone)]
2203#[error("Failed to type check Rust type {rust_name} against CQL type {cql_type:?}: {kind}")]
2204pub struct BuiltinTypeCheckError {
2205    /// Name of the Rust type being deserialized.
2206    pub rust_name: &'static str,
2207
2208    /// The CQL type that the Rust type was being deserialized from.
2209    pub cql_type: ColumnType<'static>,
2210
2211    /// Detailed information about the failure.
2212    pub kind: BuiltinTypeCheckErrorKind,
2213}
2214
2215/// Creates a [`BuiltinTypeCheckError`] with the given kind.
2216pub fn mk_typck_err<T>(
2217    cql_type: &ColumnType,
2218    kind: impl Into<BuiltinTypeCheckErrorKind>,
2219) -> TypeCheckError {
2220    mk_typck_err_named(std::any::type_name::<T>(), cql_type, kind)
2221}
2222
2223// Outlined and cold: building the error deep-clones the `ColumnType` and
2224// allocates, which would otherwise bloat every `deserialize` body enough to
2225// stop it being inlined into a collection's element loop.
2226#[cold]
2227#[inline(never)]
2228fn mk_typck_err_named(
2229    name: &'static str,
2230    cql_type: &ColumnType,
2231    kind: impl Into<BuiltinTypeCheckErrorKind>,
2232) -> TypeCheckError {
2233    TypeCheckError::new(BuiltinTypeCheckError {
2234        rust_name: name,
2235        cql_type: cql_type.clone().into_owned(),
2236        kind: kind.into(),
2237    })
2238}
2239
2240macro_rules! exact_type_check {
2241    ($typ:ident, $($cql:tt),*) => {
2242        match $typ {
2243            $(ColumnType::Native(NativeType::$cql))|* => {},
2244            _ => return Err(mk_typck_err::<Self>(
2245                $typ,
2246                BuiltinTypeCheckErrorKind::MismatchedType {
2247                    expected: &[$(ColumnType::Native(NativeType::$cql)),*],
2248                }
2249            ))
2250        }
2251    };
2252}
2253use exact_type_check;
2254
2255/// Describes why type checking some of the built-in types failed.
2256#[derive(Debug, Clone)]
2257#[non_exhaustive]
2258pub enum BuiltinTypeCheckErrorKind {
2259    /// Expected one from a list of particular types.
2260    MismatchedType {
2261        /// The list of types that the Rust type can deserialize from.
2262        expected: &'static [ColumnType<'static>],
2263    },
2264
2265    /// A type check failure specific to a CQL set or list.
2266    SetOrListError(SetOrListTypeCheckErrorKind),
2267
2268    /// A type check failure specific to a CQL vector.
2269    VectorError(VectorTypeCheckErrorKind),
2270
2271    /// A type check failure specific to a CQL map.
2272    MapError(MapTypeCheckErrorKind),
2273
2274    /// A type check failure specific to a CQL tuple.
2275    TupleError(TupleTypeCheckErrorKind),
2276
2277    /// A type check failure specific to a CQL UDT.
2278    UdtError(UdtTypeCheckErrorKind),
2279
2280    /// A type check detected type not deserializable to a vector.
2281    NotDeserializableToVec,
2282}
2283
2284impl From<SetOrListTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
2285    #[inline]
2286    fn from(value: SetOrListTypeCheckErrorKind) -> Self {
2287        BuiltinTypeCheckErrorKind::SetOrListError(value)
2288    }
2289}
2290
2291impl From<VectorTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
2292    #[inline]
2293    fn from(value: VectorTypeCheckErrorKind) -> Self {
2294        BuiltinTypeCheckErrorKind::VectorError(value)
2295    }
2296}
2297
2298impl From<MapTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
2299    #[inline]
2300    fn from(value: MapTypeCheckErrorKind) -> Self {
2301        BuiltinTypeCheckErrorKind::MapError(value)
2302    }
2303}
2304
2305impl From<TupleTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
2306    #[inline]
2307    fn from(value: TupleTypeCheckErrorKind) -> Self {
2308        BuiltinTypeCheckErrorKind::TupleError(value)
2309    }
2310}
2311
2312impl From<UdtTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
2313    #[inline]
2314    fn from(value: UdtTypeCheckErrorKind) -> Self {
2315        BuiltinTypeCheckErrorKind::UdtError(value)
2316    }
2317}
2318
2319impl Display for BuiltinTypeCheckErrorKind {
2320    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2321        match self {
2322            BuiltinTypeCheckErrorKind::MismatchedType { expected } => {
2323                write!(f, "expected one of the CQL types: {expected:?}")
2324            }
2325            BuiltinTypeCheckErrorKind::SetOrListError(err) => err.fmt(f),
2326            BuiltinTypeCheckErrorKind::VectorError(err) => err.fmt(f),
2327            BuiltinTypeCheckErrorKind::MapError(err) => err.fmt(f),
2328            BuiltinTypeCheckErrorKind::TupleError(err) => err.fmt(f),
2329            BuiltinTypeCheckErrorKind::UdtError(err) => err.fmt(f),
2330            BuiltinTypeCheckErrorKind::NotDeserializableToVec => {
2331                f.write_str("the CQL type is not deserializable to a vector")
2332            }
2333        }
2334    }
2335}
2336
2337/// Describes why type checking of a set or list type failed.
2338#[derive(Debug, Clone)]
2339#[non_exhaustive]
2340pub enum SetOrListTypeCheckErrorKind {
2341    /// The CQL type is neither a set not a list.
2342    NotSetOrList,
2343    /// The CQL type is not a set.
2344    NotSet,
2345    /// Incompatible element types.
2346    ElementTypeCheckFailed(TypeCheckError),
2347}
2348
2349impl Display for SetOrListTypeCheckErrorKind {
2350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2351        match self {
2352            SetOrListTypeCheckErrorKind::NotSetOrList => {
2353                f.write_str("the CQL type the Rust type was attempted to be type checked against was neither a set nor a list")
2354            }
2355            SetOrListTypeCheckErrorKind::NotSet => {
2356                f.write_str("the CQL type the Rust type was attempted to be type checked against was not a set")
2357            }
2358            SetOrListTypeCheckErrorKind::ElementTypeCheckFailed(err) => {
2359                write!(f, "the set or list element types between the CQL type and the Rust type failed to type check against each other: {err}")
2360            }
2361        }
2362    }
2363}
2364
2365/// Describes why type checking a vector type failed.
2366#[derive(Error, Debug, Clone)]
2367#[non_exhaustive]
2368pub enum VectorTypeCheckErrorKind {
2369    /// The CQL type is not a vector.
2370    #[error("the CQL type the Rust type was attempted to be type checked against was not a vector")]
2371    NotVector,
2372    /// Incompatible element types.
2373    #[error(
2374        "the vector element types between the CQL type and the Rust type failed to type check against each other: {0}"
2375    )]
2376    ElementTypeCheckFailed(TypeCheckError),
2377}
2378
2379/// Describes why type checking of a map type failed.
2380#[derive(Debug, Clone)]
2381#[non_exhaustive]
2382pub enum MapTypeCheckErrorKind {
2383    /// The CQL type is not a map.
2384    NotMap,
2385    /// Incompatible key types.
2386    KeyTypeCheckFailed(TypeCheckError),
2387    /// Incompatible value types.
2388    ValueTypeCheckFailed(TypeCheckError),
2389}
2390
2391impl Display for MapTypeCheckErrorKind {
2392    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2393        match self {
2394            MapTypeCheckErrorKind::NotMap => {
2395                f.write_str("the CQL type the Rust type was attempted to be type checked against was neither a map")
2396            }
2397            MapTypeCheckErrorKind::KeyTypeCheckFailed(err) => {
2398                write!(f, "the map key types between the CQL type and the Rust type failed to type check against each other: {err}")
2399            },
2400            MapTypeCheckErrorKind::ValueTypeCheckFailed(err) => {
2401                write!(f, "the map value types between the CQL type and the Rust type failed to type check against each other: {err}")
2402            },
2403        }
2404    }
2405}
2406
2407/// Describes why type checking of a tuple failed.
2408#[derive(Debug, Clone)]
2409#[non_exhaustive]
2410pub enum TupleTypeCheckErrorKind {
2411    /// The CQL type is not a tuple.
2412    NotTuple,
2413
2414    /// The tuple has the wrong element count.
2415    WrongElementCount {
2416        /// The number of elements that the Rust tuple has.
2417        rust_type_el_count: usize,
2418
2419        /// The number of elements that the CQL tuple type has.
2420        cql_type_el_count: usize,
2421    },
2422
2423    /// The CQL type and the Rust type of a tuple field failed to type check against each other.
2424    FieldTypeCheckFailed {
2425        /// The index of the field whose type check failed.
2426        position: usize,
2427
2428        /// The type check error that occurred.
2429        err: TypeCheckError,
2430    },
2431}
2432
2433impl Display for TupleTypeCheckErrorKind {
2434    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2435        match self {
2436            TupleTypeCheckErrorKind::NotTuple => write!(
2437                f,
2438                "the CQL type the tuple was attempted to be serialized to is not a tuple"
2439            ),
2440            TupleTypeCheckErrorKind::WrongElementCount {
2441                rust_type_el_count,
2442                cql_type_el_count,
2443            } => write!(
2444                f,
2445                "wrong tuple element count: CQL type has {cql_type_el_count}, the Rust tuple has {rust_type_el_count}"
2446            ),
2447
2448            TupleTypeCheckErrorKind::FieldTypeCheckFailed { position, err } => write!(
2449                f,
2450                "the CQL type and the Rust type of the tuple field {position} failed to type check against each other: {err}"
2451            ),
2452        }
2453    }
2454}
2455
2456/// Describes why type checking of a user defined type failed.
2457#[derive(Debug, Clone)]
2458#[non_exhaustive]
2459pub enum UdtTypeCheckErrorKind {
2460    /// The CQL type is not a user defined type.
2461    NotUdt,
2462
2463    /// The CQL UDT type does not have some fields that is required in the Rust struct.
2464    ValuesMissingForUdtFields {
2465        /// Names of fields that the Rust struct requires but are missing in the CQL UDT.
2466        field_names: Vec<&'static str>,
2467    },
2468
2469    /// A different field name was expected at given position.
2470    FieldNameMismatch {
2471        /// Index of the field in the Rust struct.
2472        position: usize,
2473
2474        /// The name of the Rust field.
2475        rust_field_name: String,
2476
2477        /// The name of the CQL UDT field.
2478        db_field_name: String,
2479    },
2480
2481    /// UDT contains an excess field, which does not correspond to any Rust struct's field.
2482    ExcessFieldInUdt {
2483        /// The name of the CQL UDT field.
2484        db_field_name: String,
2485    },
2486
2487    /// Duplicated field in serialized data.
2488    DuplicatedField {
2489        /// The name of the duplicated field.
2490        field_name: String,
2491    },
2492
2493    /// Fewer fields present in the UDT than required by the Rust type.
2494    TooFewFields {
2495        // TODO: decide whether we are OK with restricting to `&'static str` here.
2496        required_fields: Vec<&'static str>,
2497        present_fields: Vec<String>,
2498    },
2499
2500    /// Type check failed between UDT and Rust type field.
2501    FieldTypeCheckFailed {
2502        /// The name of the field whose type check failed.
2503        field_name: String,
2504
2505        /// Inner type check error that occurred.
2506        err: TypeCheckError,
2507    },
2508}
2509
2510impl Display for UdtTypeCheckErrorKind {
2511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2512        match self {
2513            UdtTypeCheckErrorKind::NotUdt => write!(
2514                f,
2515                "the CQL type the Rust type was attempted to be type checked against is not a UDT"
2516            ),
2517            UdtTypeCheckErrorKind::ValuesMissingForUdtFields { field_names } => {
2518                write!(
2519                    f,
2520                    "the fields {field_names:?} are missing from the DB data but are required by the Rust type"
2521                )
2522            }
2523            UdtTypeCheckErrorKind::FieldNameMismatch {
2524                rust_field_name,
2525                db_field_name,
2526                position,
2527            } => write!(
2528                f,
2529                "expected field with name {db_field_name} at position {position}, but the Rust field name is {rust_field_name}"
2530            ),
2531            UdtTypeCheckErrorKind::ExcessFieldInUdt { db_field_name } => write!(
2532                f,
2533                "UDT contains an excess field {db_field_name}, which does not correspond to any Rust struct's field."
2534            ),
2535            UdtTypeCheckErrorKind::DuplicatedField { field_name } => write!(
2536                f,
2537                "field {field_name} occurs more than once in CQL UDT type"
2538            ),
2539            UdtTypeCheckErrorKind::TooFewFields {
2540                required_fields,
2541                present_fields,
2542            } => write!(
2543                f,
2544                "fewer fields present in the UDT than required by the Rust type: UDT has {present_fields:?}, Rust type requires {required_fields:?}",
2545            ),
2546            UdtTypeCheckErrorKind::FieldTypeCheckFailed { field_name, err } => write!(
2547                f,
2548                "the UDT field {field_name} types between the CQL type and the Rust type failed to type check against each other: {err}"
2549            ),
2550        }
2551    }
2552}
2553
2554/// Deserialization of one of the built-in types failed.
2555#[derive(Debug, Error, Clone)]
2556#[error("Failed to deserialize Rust type {rust_name} from CQL type {cql_type:?}: {kind}")]
2557pub struct BuiltinDeserializationError {
2558    /// Name of the Rust type being deserialized.
2559    pub rust_name: &'static str,
2560
2561    /// The CQL type that the Rust type was being deserialized from.
2562    pub cql_type: ColumnType<'static>,
2563
2564    /// Detailed information about the failure.
2565    pub kind: BuiltinDeserializationErrorKind,
2566}
2567
2568/// Creates a [`BuiltinDeserializationError`] with the given kind.
2569pub fn mk_deser_err<T>(
2570    cql_type: &ColumnType,
2571    kind: impl Into<BuiltinDeserializationErrorKind>,
2572) -> DeserializationError {
2573    mk_deser_err_named(std::any::type_name::<T>(), cql_type, kind)
2574}
2575
2576// Outlined and cold: building the error deep-clones the `ColumnType` and
2577// allocates, which would otherwise bloat every `deserialize` body enough to
2578// stop it being inlined into a collection's element loop.
2579#[cold]
2580#[inline(never)]
2581fn mk_deser_err_named(
2582    name: &'static str,
2583    cql_type: &ColumnType,
2584    kind: impl Into<BuiltinDeserializationErrorKind>,
2585) -> DeserializationError {
2586    DeserializationError::new(BuiltinDeserializationError {
2587        rust_name: name,
2588        cql_type: cql_type.clone().into_owned(),
2589        kind: kind.into(),
2590    })
2591}
2592
2593/// Describes why deserialization of some of the built-in types failed.
2594#[derive(Debug, Clone)]
2595#[non_exhaustive]
2596pub enum BuiltinDeserializationErrorKind {
2597    /// Failed to deserialize one of date's fields.
2598    BadDate {
2599        date_field: &'static str,
2600        err: LowLevelDeserializationError,
2601    },
2602
2603    /// Failed to deserialize decimal's scale.
2604    BadDecimalScale(LowLevelDeserializationError),
2605
2606    /// Decimal has a scale, but its unscaled value is empty.
2607    EmptyDecimalUnscaledValue,
2608
2609    /// Failed to deserialize raw bytes of cql value.
2610    RawCqlBytesReadError(LowLevelDeserializationError),
2611
2612    /// Expected non-null value, got null.
2613    ExpectedNonNull,
2614
2615    /// Expected non-empty value, got empty.
2616    ExpectedNonEmpty,
2617
2618    /// The length of read value in bytes is different than expected for the Rust type.
2619    ByteLengthMismatch { expected: usize, got: usize },
2620
2621    /// Expected valid ASCII string.
2622    ExpectedAscii,
2623
2624    /// Invalid UTF-8 string.
2625    InvalidUtf8(std::str::Utf8Error),
2626
2627    /// The read value is out of range supported by the Rust type.
2628    // TODO: consider storing additional info here (what exactly did not fit and why)
2629    ValueOverflow,
2630
2631    /// The length of read value in bytes is not suitable for IP address.
2632    BadInetLength { got: usize },
2633
2634    /// A deserialization failure specific to a CQL set or list.
2635    SetOrListError(SetOrListDeserializationErrorKind),
2636
2637    /// A deserialization failure specific to a CQL vector.
2638    VectorError(VectorDeserializationErrorKind),
2639
2640    /// A deserialization failure specific to a CQL map.
2641    MapError(MapDeserializationErrorKind),
2642
2643    /// A deserialization failure specific to a CQL tuple.
2644    TupleError(TupleDeserializationErrorKind),
2645
2646    /// A deserialization failure specific to a CQL UDT.
2647    UdtError(UdtDeserializationErrorKind),
2648
2649    /// Deserialization of this CQL type is not supported by the driver.
2650    Unsupported,
2651}
2652
2653impl Display for BuiltinDeserializationErrorKind {
2654    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2655        match self {
2656            BuiltinDeserializationErrorKind::BadDate { date_field, err } => write!(
2657                f,
2658                "malformed {date_field} during 'date' deserialization: {err}"
2659            ),
2660            BuiltinDeserializationErrorKind::BadDecimalScale(err) => {
2661                write!(f, "malformed decimal's scale: {err}")
2662            }
2663            BuiltinDeserializationErrorKind::EmptyDecimalUnscaledValue => {
2664                f.write_str("decimal's unscaled value is empty")
2665            }
2666            BuiltinDeserializationErrorKind::RawCqlBytesReadError(err) => {
2667                write!(f, "failed to read raw cql value bytes: {err}")
2668            }
2669            BuiltinDeserializationErrorKind::ExpectedNonNull => {
2670                f.write_str("expected a non-null value, got null")
2671            }
2672            BuiltinDeserializationErrorKind::ExpectedNonEmpty => {
2673                f.write_str("expected a non-empty value, got empty")
2674            }
2675            BuiltinDeserializationErrorKind::ByteLengthMismatch { expected, got } => {
2676                write!(f, "the CQL type requires {expected} bytes, but got {got}",)
2677            }
2678            BuiltinDeserializationErrorKind::ExpectedAscii => {
2679                f.write_str("expected a valid ASCII string")
2680            }
2681            BuiltinDeserializationErrorKind::InvalidUtf8(err) => err.fmt(f),
2682            BuiltinDeserializationErrorKind::ValueOverflow => {
2683                // TODO: consider storing Arc<dyn Display/Debug> of the offending value
2684                // inside this variant for debug purposes.
2685                f.write_str("read value is out of representable range")
2686            }
2687            BuiltinDeserializationErrorKind::BadInetLength { got } => write!(
2688                f,
2689                "the length of read value in bytes ({got}) is not suitable for IP address; expected 4 or 16"
2690            ),
2691            BuiltinDeserializationErrorKind::SetOrListError(err) => err.fmt(f),
2692            BuiltinDeserializationErrorKind::VectorError(err) => err.fmt(f),
2693            BuiltinDeserializationErrorKind::MapError(err) => err.fmt(f),
2694            BuiltinDeserializationErrorKind::TupleError(err) => err.fmt(f),
2695            BuiltinDeserializationErrorKind::UdtError(err) => err.fmt(f),
2696            BuiltinDeserializationErrorKind::Unsupported => {
2697                f.write_str("deserialization of this CQL type is not supported by the driver")
2698            }
2699        }
2700    }
2701}
2702
2703/// Describes why deserialization of a set or list type failed.
2704#[derive(Debug, Clone)]
2705#[non_exhaustive]
2706pub enum SetOrListDeserializationErrorKind {
2707    /// Failed to deserialize set or list's length.
2708    LengthDeserializationFailed(DeserializationError),
2709
2710    /// One of the elements of the set/list failed to deserialize.
2711    ElementDeserializationFailed(DeserializationError),
2712}
2713
2714impl Display for SetOrListDeserializationErrorKind {
2715    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2716        match self {
2717            SetOrListDeserializationErrorKind::LengthDeserializationFailed(err) => {
2718                write!(f, "failed to deserialize set or list's length: {err}")
2719            }
2720            SetOrListDeserializationErrorKind::ElementDeserializationFailed(err) => {
2721                write!(f, "failed to deserialize one of the elements: {err}")
2722            }
2723        }
2724    }
2725}
2726
2727impl From<SetOrListDeserializationErrorKind> for BuiltinDeserializationErrorKind {
2728    #[inline]
2729    fn from(err: SetOrListDeserializationErrorKind) -> Self {
2730        Self::SetOrListError(err)
2731    }
2732}
2733
2734/// Describes why deserialization of a vector type failed.
2735#[derive(Error, Debug, Clone)]
2736#[non_exhaustive]
2737pub enum VectorDeserializationErrorKind {
2738    /// One of the elements of the vector failed to deserialize.
2739    #[error("failed to deserialize one of the elements: {0}")]
2740    ElementDeserializationFailed(DeserializationError),
2741}
2742
2743impl From<VectorDeserializationErrorKind> for BuiltinDeserializationErrorKind {
2744    #[inline]
2745    fn from(err: VectorDeserializationErrorKind) -> Self {
2746        Self::VectorError(err)
2747    }
2748}
2749
2750/// Describes why deserialization of a map type failed.
2751#[derive(Debug, Clone)]
2752#[non_exhaustive]
2753// Check triggers because all variants end with "DeserializationFailed".
2754// TODO(2.0): Remove the "DeserializationFailed" postfix from variants.
2755#[expect(clippy::enum_variant_names)]
2756pub enum MapDeserializationErrorKind {
2757    /// Failed to deserialize map's length.
2758    LengthDeserializationFailed(DeserializationError),
2759
2760    /// One of the keys in the map failed to deserialize.
2761    KeyDeserializationFailed(DeserializationError),
2762
2763    /// One of the values in the map failed to deserialize.
2764    ValueDeserializationFailed(DeserializationError),
2765}
2766
2767impl Display for MapDeserializationErrorKind {
2768    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2769        match self {
2770            MapDeserializationErrorKind::LengthDeserializationFailed(err) => {
2771                write!(f, "failed to deserialize map's length: {err}")
2772            }
2773            MapDeserializationErrorKind::KeyDeserializationFailed(err) => {
2774                write!(f, "failed to deserialize one of the keys: {err}")
2775            }
2776            MapDeserializationErrorKind::ValueDeserializationFailed(err) => {
2777                write!(f, "failed to deserialize one of the values: {err}")
2778            }
2779        }
2780    }
2781}
2782
2783impl From<MapDeserializationErrorKind> for BuiltinDeserializationErrorKind {
2784    fn from(err: MapDeserializationErrorKind) -> Self {
2785        Self::MapError(err)
2786    }
2787}
2788
2789/// Describes why deserialization of a tuple failed.
2790#[derive(Debug, Clone)]
2791#[non_exhaustive]
2792pub enum TupleDeserializationErrorKind {
2793    /// One of the tuple fields failed to deserialize.
2794    FieldDeserializationFailed {
2795        /// Index of the tuple field that failed to deserialize.
2796        position: usize,
2797
2798        /// The error that caused the tuple field deserialization to fail.
2799        err: DeserializationError,
2800    },
2801}
2802
2803impl Display for TupleDeserializationErrorKind {
2804    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2805        match self {
2806            TupleDeserializationErrorKind::FieldDeserializationFailed {
2807                position: index,
2808                err,
2809            } => {
2810                write!(f, "field no. {index} failed to deserialize: {err}")
2811            }
2812        }
2813    }
2814}
2815
2816impl From<TupleDeserializationErrorKind> for BuiltinDeserializationErrorKind {
2817    fn from(err: TupleDeserializationErrorKind) -> Self {
2818        Self::TupleError(err)
2819    }
2820}
2821
2822/// Describes why deserialization of a user defined type failed.
2823#[derive(Debug, Clone)]
2824#[non_exhaustive]
2825pub enum UdtDeserializationErrorKind {
2826    /// One of the fields failed to deserialize.
2827    FieldDeserializationFailed {
2828        /// Name of the field which failed to deserialize.
2829        field_name: String,
2830
2831        /// The error that caused the UDT field deserialization to fail.
2832        err: DeserializationError,
2833    },
2834}
2835
2836impl Display for UdtDeserializationErrorKind {
2837    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2838        match self {
2839            UdtDeserializationErrorKind::FieldDeserializationFailed { field_name, err } => {
2840                write!(f, "field {field_name} failed to deserialize: {err}")
2841            }
2842        }
2843    }
2844}
2845
2846impl From<UdtDeserializationErrorKind> for BuiltinDeserializationErrorKind {
2847    fn from(err: UdtDeserializationErrorKind) -> Self {
2848        Self::UdtError(err)
2849    }
2850}
2851
2852#[cfg(test)]
2853#[path = "value_tests.rs"]
2854pub(crate) mod tests;