Skip to main content

scylla_cql_core/serialize/
value.rs

1//! Contains the [`SerializeValue`] trait and its implementations.
2
3// Note: When editing above doc-comment edit the corresponding comment on
4// re-export module in scylla crate too.
5
6use std::borrow::Cow;
7use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
8use std::fmt::Display;
9use std::hash::BuildHasher;
10use std::iter::Peekable;
11use std::net::IpAddr;
12use std::sync::Arc;
13
14use bytes::Bytes;
15use thiserror::Error;
16use uuid::Uuid;
17
18use crate::frame::response::result::{CollectionType, ColumnType, NativeType};
19use crate::frame::types::vint_encode;
20use crate::value::{
21    Counter, CqlDate, CqlDecimal, CqlDecimalBorrowed, CqlDuration, CqlTime, CqlTimestamp,
22    CqlTimeuuid, CqlValue, CqlVarint, CqlVarintBorrowed, Emptiable, MaybeEmpty, MaybeUnset, Unset,
23};
24
25#[cfg(feature = "chrono-04")]
26use crate::value::ValueOverflow;
27
28use super::writers::WrittenCellProof;
29use super::{CellValueBuilder, CellWriter, SerializationError};
30
31/// A type that can be serialized and sent along with a CQL statement.
32///
33/// This is a low-level trait that is exposed to the specifics to the CQL
34/// protocol and usually does not have to be implemented directly. See the
35/// chapter on "Query Values" in the driver docs for information about how
36/// this trait is supposed to be used.
37pub trait SerializeValue {
38    /// Serializes the value to given CQL type.
39    ///
40    /// The value should produce a `[value]`, according to the [CQL protocol
41    /// specification](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec),
42    /// containing the serialized value. See section 6 of the document on how
43    /// the contents of the `[value]` should look like.
44    ///
45    /// The value produced should match the type provided by `typ`. If the
46    /// value cannot be serialized to that type, an error should be returned.
47    ///
48    /// The [`CellWriter`] provided to the method ensures that the value produced
49    /// will be properly framed (i.e. incorrectly written value should not
50    /// cause the rest of the request to be misinterpreted), but otherwise
51    /// the implementor of the trait is responsible for producing the value
52    /// in a correct format.
53    fn serialize<'b>(
54        &self,
55        typ: &ColumnType,
56        writer: CellWriter<'b>,
57    ) -> Result<WrittenCellProof<'b>, SerializationError>;
58}
59
60macro_rules! exact_type_check {
61    ($typ:ident, $($cql:tt),*) => {
62        match $typ {
63            $(ColumnType::Native(NativeType::$cql))|* => {},
64            _ => return Err(mk_typck_err::<Self>(
65                $typ,
66                BuiltinTypeCheckErrorKind::MismatchedType {
67                    expected: &[$(ColumnType::Native(NativeType::$cql)),*],
68                }
69            ))
70        }
71    };
72}
73
74macro_rules! impl_serialize_via_writer {
75    (|$me:ident, $writer:ident| $e:expr) => {
76        impl_serialize_via_writer!(|$me, _typ, $writer| $e);
77    };
78    (|$me:ident, $typ:ident, $writer:ident| $e:expr) => {
79        // Most of these bodies are a few instructions each once the error
80        // construction is outlined, and callers - in particular a
81        // collection's element loop - benefit a lot from inlining them.
82        #[inline]
83        fn serialize<'b>(
84            &self,
85            typ: &ColumnType,
86            writer: CellWriter<'b>,
87        ) -> Result<WrittenCellProof<'b>, SerializationError> {
88            let $writer = writer;
89            let $typ = typ;
90            let $me = self;
91            let proof = $e;
92            Ok(proof)
93        }
94    };
95}
96
97impl SerializeValue for i8 {
98    impl_serialize_via_writer!(|me, typ, writer| {
99        exact_type_check!(typ, TinyInt);
100        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
101    });
102}
103impl SerializeValue for i16 {
104    impl_serialize_via_writer!(|me, typ, writer| {
105        exact_type_check!(typ, SmallInt);
106        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
107    });
108}
109impl SerializeValue for i32 {
110    impl_serialize_via_writer!(|me, typ, writer| {
111        exact_type_check!(typ, Int);
112        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
113    });
114}
115impl SerializeValue for i64 {
116    impl_serialize_via_writer!(|me, typ, writer| {
117        exact_type_check!(typ, BigInt);
118        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
119    });
120}
121impl SerializeValue for CqlDecimal {
122    impl_serialize_via_writer!(|me, typ, writer| {
123        exact_type_check!(typ, Decimal);
124        let mut builder = writer.into_value_builder();
125        let (bytes, scale) = me.as_signed_be_bytes_slice_and_exponent();
126        builder.append_bytes(&scale.to_be_bytes());
127        builder.append_bytes(bytes);
128        builder
129            .finish()
130            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
131    });
132}
133impl SerializeValue for CqlDecimalBorrowed<'_> {
134    impl_serialize_via_writer!(|me, typ, writer| {
135        exact_type_check!(typ, Decimal);
136        let mut builder = writer.into_value_builder();
137        let (bytes, scale) = me.as_signed_be_bytes_slice_and_exponent();
138        builder.append_bytes(&scale.to_be_bytes());
139        builder.append_bytes(bytes);
140        builder
141            .finish()
142            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
143    });
144}
145#[cfg(feature = "bigdecimal-04")]
146impl SerializeValue for bigdecimal_04::BigDecimal {
147    impl_serialize_via_writer!(|me, typ, writer| {
148        exact_type_check!(typ, Decimal);
149        let mut builder = writer.into_value_builder();
150        let (value, scale) = me.as_bigint_and_exponent();
151        let scale: i32 = scale
152            .try_into()
153            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::ValueOverflow))?;
154        builder.append_bytes(&scale.to_be_bytes());
155        builder.append_bytes(&value.to_signed_bytes_be());
156        builder
157            .finish()
158            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
159    });
160}
161impl SerializeValue for CqlDate {
162    impl_serialize_via_writer!(|me, typ, writer| {
163        exact_type_check!(typ, Date);
164        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
165    });
166}
167impl SerializeValue for CqlTimestamp {
168    impl_serialize_via_writer!(|me, typ, writer| {
169        exact_type_check!(typ, Timestamp);
170        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
171    });
172}
173impl SerializeValue for CqlTime {
174    impl_serialize_via_writer!(|me, typ, writer| {
175        exact_type_check!(typ, Time);
176        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
177    });
178}
179#[cfg(feature = "chrono-04")]
180impl SerializeValue for chrono_04::NaiveDate {
181    impl_serialize_via_writer!(|me, typ, writer| {
182        exact_type_check!(typ, Date);
183        <CqlDate as SerializeValue>::serialize(&(*me).into(), typ, writer)?
184    });
185}
186#[cfg(feature = "chrono-04")]
187impl SerializeValue for chrono_04::DateTime<chrono_04::Utc> {
188    impl_serialize_via_writer!(|me, typ, writer| {
189        exact_type_check!(typ, Timestamp);
190        <CqlTimestamp as SerializeValue>::serialize(&(*me).into(), typ, writer)?
191    });
192}
193#[cfg(feature = "chrono-04")]
194impl SerializeValue for chrono_04::NaiveTime {
195    impl_serialize_via_writer!(|me, typ, writer| {
196        exact_type_check!(typ, Time);
197        let cql_time = CqlTime::try_from(*me).map_err(|_: ValueOverflow| {
198            mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::ValueOverflow)
199        })?;
200        <CqlTime as SerializeValue>::serialize(&cql_time, typ, writer)?
201    });
202}
203#[cfg(feature = "time-03")]
204impl SerializeValue for time_03::Date {
205    impl_serialize_via_writer!(|me, typ, writer| {
206        exact_type_check!(typ, Date);
207        <CqlDate as SerializeValue>::serialize(&(*me).into(), typ, writer)?
208    });
209}
210#[cfg(feature = "time-03")]
211impl SerializeValue for time_03::OffsetDateTime {
212    impl_serialize_via_writer!(|me, typ, writer| {
213        exact_type_check!(typ, Timestamp);
214        <CqlTimestamp as SerializeValue>::serialize(&(*me).into(), typ, writer)?
215    });
216}
217#[cfg(feature = "time-03")]
218impl SerializeValue for time_03::Time {
219    impl_serialize_via_writer!(|me, typ, writer| {
220        exact_type_check!(typ, Time);
221        <CqlTime as SerializeValue>::serialize(&(*me).into(), typ, writer)?
222    });
223}
224#[cfg(feature = "secrecy-08")]
225impl<V: SerializeValue + secrecy_08::Zeroize> SerializeValue for secrecy_08::Secret<V> {
226    fn serialize<'b>(
227        &self,
228        typ: &ColumnType,
229        writer: CellWriter<'b>,
230    ) -> Result<WrittenCellProof<'b>, SerializationError> {
231        use secrecy_08::ExposeSecret;
232        V::serialize(self.expose_secret(), typ, writer).map_err(fix_rust_name_in_err::<Self>)
233    }
234}
235#[cfg(feature = "secrecy-10")]
236impl<V: SerializeValue + secrecy_10::zeroize::Zeroize + ?Sized> SerializeValue
237    for secrecy_10::SecretBox<V>
238{
239    fn serialize<'b>(
240        &self,
241        typ: &ColumnType,
242        writer: CellWriter<'b>,
243    ) -> Result<WrittenCellProof<'b>, SerializationError> {
244        use secrecy_10::ExposeSecret;
245        V::serialize(self.expose_secret(), typ, writer).map_err(fix_rust_name_in_err::<Self>)
246    }
247}
248impl SerializeValue for bool {
249    impl_serialize_via_writer!(|me, typ, writer| {
250        exact_type_check!(typ, Boolean);
251        writer.set_value(&[*me as u8]).unwrap()
252    });
253}
254impl SerializeValue for f32 {
255    impl_serialize_via_writer!(|me, typ, writer| {
256        exact_type_check!(typ, Float);
257        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
258    });
259}
260impl SerializeValue for f64 {
261    impl_serialize_via_writer!(|me, typ, writer| {
262        exact_type_check!(typ, Double);
263        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
264    });
265}
266impl SerializeValue for Uuid {
267    impl_serialize_via_writer!(|me, typ, writer| {
268        exact_type_check!(typ, Uuid);
269        writer.set_value(me.as_bytes().as_ref()).unwrap()
270    });
271}
272impl SerializeValue for CqlTimeuuid {
273    impl_serialize_via_writer!(|me, typ, writer| {
274        exact_type_check!(typ, Timeuuid);
275        writer.set_value(me.as_bytes().as_ref()).unwrap()
276    });
277}
278impl SerializeValue for CqlVarint {
279    impl_serialize_via_writer!(|me, typ, writer| {
280        exact_type_check!(typ, Varint);
281        writer
282            .set_value(me.as_signed_bytes_be_slice())
283            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
284    });
285}
286impl SerializeValue for CqlVarintBorrowed<'_> {
287    impl_serialize_via_writer!(|me, typ, writer| {
288        exact_type_check!(typ, Varint);
289        writer
290            .set_value(me.as_signed_bytes_be_slice())
291            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
292    });
293}
294#[cfg(feature = "num-bigint-03")]
295impl SerializeValue for num_bigint_03::BigInt {
296    impl_serialize_via_writer!(|me, typ, writer| {
297        exact_type_check!(typ, Varint);
298        // TODO: The allocation here can be avoided and we can reimplement
299        // `to_signed_bytes_be` by using `to_u64_digits` and a bit of custom
300        // logic. Need better tests in order to do this.
301        writer
302            .set_value(me.to_signed_bytes_be().as_slice())
303            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
304    });
305}
306#[cfg(feature = "num-bigint-04")]
307impl SerializeValue for num_bigint_04::BigInt {
308    impl_serialize_via_writer!(|me, typ, writer| {
309        exact_type_check!(typ, Varint);
310        // TODO: See above comment for num-bigint-03.
311        writer
312            .set_value(me.to_signed_bytes_be().as_slice())
313            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
314    });
315}
316impl SerializeValue for str {
317    impl_serialize_via_writer!(|me, typ, writer| {
318        exact_type_check!(typ, Ascii, Text);
319        writer
320            .set_value(me.as_bytes())
321            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
322    });
323}
324impl SerializeValue for Vec<u8> {
325    impl_serialize_via_writer!(|me, typ, writer| {
326        exact_type_check!(typ, Blob);
327        writer
328            .set_value(me.as_ref())
329            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
330    });
331}
332impl SerializeValue for &[u8] {
333    impl_serialize_via_writer!(|me, typ, writer| {
334        exact_type_check!(typ, Blob);
335        writer
336            .set_value(me)
337            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
338    });
339}
340impl<const N: usize> SerializeValue for [u8; N] {
341    impl_serialize_via_writer!(|me, typ, writer| {
342        exact_type_check!(typ, Blob);
343        writer
344            .set_value(me.as_ref())
345            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
346    });
347}
348impl SerializeValue for Bytes {
349    impl_serialize_via_writer!(|me, typ, writer| {
350        exact_type_check!(typ, Blob);
351        writer
352            .set_value(me)
353            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
354    });
355}
356impl SerializeValue for IpAddr {
357    impl_serialize_via_writer!(|me, typ, writer| {
358        exact_type_check!(typ, Inet);
359        match me {
360            IpAddr::V4(ip) => writer.set_value(&ip.octets()).unwrap(),
361            IpAddr::V6(ip) => writer.set_value(&ip.octets()).unwrap(),
362        }
363    });
364}
365impl SerializeValue for String {
366    impl_serialize_via_writer!(|me, typ, writer| {
367        exact_type_check!(typ, Ascii, Text);
368        writer
369            .set_value(me.as_bytes())
370            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
371    });
372}
373impl<T: SerializeValue> SerializeValue for Option<T> {
374    fn serialize<'b>(
375        &self,
376        typ: &ColumnType,
377        writer: CellWriter<'b>,
378    ) -> Result<WrittenCellProof<'b>, SerializationError> {
379        match self {
380            Some(v) => v
381                .serialize(typ, writer)
382                .map_err(fix_rust_name_in_err::<Self>),
383            None => Ok(writer.set_null()),
384        }
385    }
386}
387impl SerializeValue for Unset {
388    impl_serialize_via_writer!(|_me, writer| writer.set_unset());
389}
390impl SerializeValue for Counter {
391    impl_serialize_via_writer!(|me, typ, writer| {
392        exact_type_check!(typ, Counter);
393        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
394    });
395}
396impl SerializeValue for CqlDuration {
397    impl_serialize_via_writer!(|me, typ, writer| {
398        exact_type_check!(typ, Duration);
399        // A vint takes at most 9 bytes. Months and days are i32s, which take
400        // at most 5, so 19 bytes would be enough, but 3 * 9 is easier to check.
401        let mut buf = [0; 27];
402        let mut unused = &mut buf[..];
403        vint_encode(me.months as i64, &mut unused);
404        vint_encode(me.days as i64, &mut unused);
405        vint_encode(me.nanoseconds, &mut unused);
406        let unused_len = unused.len();
407        writer.set_value(&buf[..buf.len() - unused_len]).unwrap()
408    });
409}
410impl<V: SerializeValue> SerializeValue for MaybeUnset<V> {
411    fn serialize<'b>(
412        &self,
413        typ: &ColumnType,
414        writer: CellWriter<'b>,
415    ) -> Result<WrittenCellProof<'b>, SerializationError> {
416        match self {
417            MaybeUnset::Set(v) => v
418                .serialize(typ, writer)
419                .map_err(fix_rust_name_in_err::<Self>),
420            MaybeUnset::Unset => Ok(writer.set_unset()),
421        }
422    }
423}
424impl<T: SerializeValue + Emptiable> SerializeValue for MaybeEmpty<T> {
425    fn serialize<'b>(
426        &self,
427        typ: &ColumnType,
428        writer: CellWriter<'b>,
429    ) -> Result<WrittenCellProof<'b>, SerializationError> {
430        // Check that the type supports empty values
431        if !typ.supports_special_empty_value() {
432            return Err(mk_typck_err::<Self>(
433                typ,
434                BuiltinTypeCheckErrorKind::NotEmptyable,
435            ));
436        }
437
438        match self {
439            MaybeEmpty::Empty => Ok(writer.set_value(&[]).unwrap()),
440            MaybeEmpty::Value(v) => v
441                .serialize(typ, writer)
442                .map_err(fix_rust_name_in_err::<Self>),
443        }
444    }
445}
446impl<T: SerializeValue + ?Sized> SerializeValue for &T {
447    fn serialize<'b>(
448        &self,
449        typ: &ColumnType,
450        writer: CellWriter<'b>,
451    ) -> Result<WrittenCellProof<'b>, SerializationError> {
452        T::serialize(*self, typ, writer).map_err(fix_rust_name_in_err::<Self>)
453    }
454}
455impl<T: SerializeValue + ?Sized> SerializeValue for Box<T> {
456    fn serialize<'b>(
457        &self,
458        typ: &ColumnType,
459        writer: CellWriter<'b>,
460    ) -> Result<WrittenCellProof<'b>, SerializationError> {
461        T::serialize(&**self, typ, writer).map_err(fix_rust_name_in_err::<Self>)
462    }
463}
464impl<T: SerializeValue + ?Sized> SerializeValue for Arc<T> {
465    fn serialize<'b>(
466        &self,
467        typ: &ColumnType,
468        writer: CellWriter<'b>,
469    ) -> Result<WrittenCellProof<'b>, SerializationError> {
470        T::serialize(&**self, typ, writer).map_err(fix_rust_name_in_err::<Self>)
471    }
472}
473impl<T: SerializeValue + ?Sized + ToOwned> SerializeValue for Cow<'_, T> {
474    fn serialize<'b>(
475        &self,
476        typ: &ColumnType,
477        writer: CellWriter<'b>,
478    ) -> Result<WrittenCellProof<'b>, SerializationError> {
479        T::serialize(self.as_ref(), typ, writer).map_err(fix_rust_name_in_err::<Self>)
480    }
481}
482impl<V: SerializeValue, S: BuildHasher + Default> SerializeValue for HashSet<V, S> {
483    fn serialize<'b>(
484        &self,
485        typ: &ColumnType,
486        writer: CellWriter<'b>,
487    ) -> Result<WrittenCellProof<'b>, SerializationError> {
488        serialize_sequence(
489            std::any::type_name::<Self>(),
490            self.len(),
491            self.iter(),
492            typ,
493            writer,
494        )
495    }
496}
497impl<K: SerializeValue, V: SerializeValue, S: BuildHasher> SerializeValue for HashMap<K, V, S> {
498    fn serialize<'b>(
499        &self,
500        typ: &ColumnType,
501        writer: CellWriter<'b>,
502    ) -> Result<WrittenCellProof<'b>, SerializationError> {
503        serialize_mapping(
504            std::any::type_name::<Self>(),
505            self.len(),
506            self.iter(),
507            typ,
508            writer,
509        )
510    }
511}
512impl<V: SerializeValue> SerializeValue for BTreeSet<V> {
513    fn serialize<'b>(
514        &self,
515        typ: &ColumnType,
516        writer: CellWriter<'b>,
517    ) -> Result<WrittenCellProof<'b>, SerializationError> {
518        serialize_sequence(
519            std::any::type_name::<Self>(),
520            self.len(),
521            self.iter(),
522            typ,
523            writer,
524        )
525    }
526}
527impl<K: SerializeValue, V: SerializeValue> SerializeValue for BTreeMap<K, V> {
528    fn serialize<'b>(
529        &self,
530        typ: &ColumnType,
531        writer: CellWriter<'b>,
532    ) -> Result<WrittenCellProof<'b>, SerializationError> {
533        serialize_mapping(
534            std::any::type_name::<Self>(),
535            self.len(),
536            self.iter(),
537            typ,
538            writer,
539        )
540    }
541}
542impl<T: SerializeValue> SerializeValue for Vec<T> {
543    fn serialize<'b>(
544        &self,
545        typ: &ColumnType,
546        writer: CellWriter<'b>,
547    ) -> Result<WrittenCellProof<'b>, SerializationError> {
548        match typ {
549            ColumnType::Collection {
550                typ: CollectionType::List(_) | CollectionType::Set(_),
551                ..
552            } => serialize_sequence(
553                std::any::type_name::<Self>(),
554                self.len(),
555                self.iter(),
556                typ,
557                writer,
558            ),
559
560            ColumnType::Vector {
561                typ: element_type,
562                dimensions,
563            } => serialize_vector(
564                std::any::type_name::<Self>(),
565                self.len(),
566                self.iter(),
567                element_type,
568                *dimensions,
569                typ,
570                writer,
571            ),
572
573            _ => Err(mk_typck_err_named(
574                std::any::type_name::<Self>(),
575                typ,
576                SetOrListTypeCheckErrorKind::NotSetOrList,
577            )),
578        }
579    }
580}
581impl<T: SerializeValue> SerializeValue for [T] {
582    fn serialize<'b>(
583        &self,
584        typ: &ColumnType,
585        writer: CellWriter<'b>,
586    ) -> Result<WrittenCellProof<'b>, SerializationError> {
587        match typ {
588            ColumnType::Collection {
589                typ: CollectionType::List(_) | CollectionType::Set(_),
590                ..
591            } => serialize_sequence(
592                std::any::type_name::<Self>(),
593                self.len(),
594                self.iter(),
595                typ,
596                writer,
597            ),
598
599            ColumnType::Vector {
600                typ: element_type,
601                dimensions,
602            } => serialize_vector(
603                std::any::type_name::<Self>(),
604                self.len(),
605                self.iter(),
606                element_type,
607                *dimensions,
608                typ,
609                writer,
610            ),
611
612            _ => Err(mk_typck_err_named(
613                std::any::type_name::<Self>(),
614                typ,
615                SetOrListTypeCheckErrorKind::NotSetOrList,
616            )),
617        }
618    }
619}
620impl SerializeValue for CqlValue {
621    fn serialize<'b>(
622        &self,
623        typ: &ColumnType,
624        writer: CellWriter<'b>,
625    ) -> Result<WrittenCellProof<'b>, SerializationError> {
626        serialize_cql_value(self, typ, writer).map_err(fix_rust_name_in_err::<Self>)
627    }
628}
629
630fn serialize_cql_value<'b>(
631    value: &CqlValue,
632    typ: &ColumnType,
633    writer: CellWriter<'b>,
634) -> Result<WrittenCellProof<'b>, SerializationError> {
635    #[deny(clippy::wildcard_enum_match_arm)]
636    match value {
637        CqlValue::Ascii(a) => <_ as SerializeValue>::serialize(&a, typ, writer),
638        CqlValue::Boolean(b) => <_ as SerializeValue>::serialize(&b, typ, writer),
639        CqlValue::Blob(b) => <_ as SerializeValue>::serialize(&b, typ, writer),
640        CqlValue::Counter(c) => <_ as SerializeValue>::serialize(&c, typ, writer),
641        CqlValue::Decimal(d) => <_ as SerializeValue>::serialize(&d, typ, writer),
642        CqlValue::Date(d) => <_ as SerializeValue>::serialize(&d, typ, writer),
643        CqlValue::Double(d) => <_ as SerializeValue>::serialize(&d, typ, writer),
644        CqlValue::Duration(d) => <_ as SerializeValue>::serialize(&d, typ, writer),
645        CqlValue::Empty => {
646            if !typ.supports_special_empty_value() {
647                return Err(mk_typck_err::<CqlValue>(
648                    typ,
649                    BuiltinTypeCheckErrorKind::NotEmptyable,
650                ));
651            }
652            Ok(writer.set_value(&[]).unwrap())
653        }
654        CqlValue::Float(f) => <_ as SerializeValue>::serialize(&f, typ, writer),
655        CqlValue::Int(i) => <_ as SerializeValue>::serialize(&i, typ, writer),
656        CqlValue::BigInt(b) => <_ as SerializeValue>::serialize(&b, typ, writer),
657        CqlValue::Text(t) => <_ as SerializeValue>::serialize(&t, typ, writer),
658        CqlValue::Timestamp(t) => <_ as SerializeValue>::serialize(&t, typ, writer),
659        CqlValue::Inet(i) => <_ as SerializeValue>::serialize(&i, typ, writer),
660        CqlValue::List(l) => <_ as SerializeValue>::serialize(&l, typ, writer),
661        CqlValue::Map(m) => serialize_mapping(
662            std::any::type_name::<CqlValue>(),
663            m.len(),
664            m.iter().map(|p| (&p.0, &p.1)),
665            typ,
666            writer,
667        ),
668        CqlValue::Set(s) => <_ as SerializeValue>::serialize(&s, typ, writer),
669        CqlValue::UserDefinedType {
670            keyspace,
671            name: type_name,
672            fields,
673        } => serialize_udt(typ, keyspace, type_name, fields, writer),
674        CqlValue::SmallInt(s) => <_ as SerializeValue>::serialize(&s, typ, writer),
675        CqlValue::TinyInt(t) => <_ as SerializeValue>::serialize(&t, typ, writer),
676        CqlValue::Time(t) => <_ as SerializeValue>::serialize(&t, typ, writer),
677        CqlValue::Timeuuid(t) => <_ as SerializeValue>::serialize(&t, typ, writer),
678        CqlValue::Tuple(t) => {
679            // We allow serializing tuples that have less fields
680            // than the database tuple, but not the other way around.
681            let fields = {
682                #[deny(clippy::wildcard_enum_match_arm)]
683                match typ {
684                    ColumnType::Tuple(fields) => {
685                        if fields.len() < t.len() {
686                            return Err(mk_typck_err::<CqlValue>(
687                                typ,
688                                TupleTypeCheckErrorKind::WrongElementCount {
689                                    rust_type_el_count: t.len(),
690                                    cql_type_el_count: fields.len(),
691                                },
692                            ));
693                        }
694                        fields
695                    }
696                    ColumnType::Native(_)
697                    | ColumnType::Collection { .. }
698                    | ColumnType::Vector { .. }
699                    | ColumnType::UserDefinedType { .. } => {
700                        return Err(mk_typck_err::<CqlValue>(
701                            typ,
702                            TupleTypeCheckErrorKind::NotTuple,
703                        ));
704                    }
705                }
706            };
707            serialize_tuple_like(typ, fields.iter(), t.iter(), writer)
708        }
709        CqlValue::Uuid(u) => <_ as SerializeValue>::serialize(&u, typ, writer),
710        CqlValue::Varint(v) => <_ as SerializeValue>::serialize(&v, typ, writer),
711        CqlValue::Vector(v) => <_ as SerializeValue>::serialize(&v, typ, writer),
712    }
713}
714
715fn fix_rust_name_in_err<RustT>(mut err: SerializationError) -> SerializationError {
716    // The purpose of this function is to change the `rust_name` field
717    // in the error to the given one. Most of the time, the `err` given to the
718    // function here will be the sole owner of the data, so theoretically
719    // we could fix this in place.
720
721    let rust_name = std::any::type_name::<RustT>();
722
723    match Arc::get_mut(&mut err.0) {
724        Some(err_mut) => {
725            if let Some(err) = err_mut.downcast_mut::<BuiltinTypeCheckError>() {
726                err.rust_name = rust_name;
727            } else if let Some(err) = err_mut.downcast_mut::<BuiltinSerializationError>() {
728                err.rust_name = rust_name;
729            }
730        }
731        None => {
732            // The `None` case shouldn't happen considering how we are using
733            // the function in the code now, but let's provide it here anyway
734            // for correctness.
735            if let Some(err) = err.0.downcast_ref::<BuiltinTypeCheckError>()
736                && err.rust_name != rust_name
737            {
738                return SerializationError::new(BuiltinTypeCheckError {
739                    rust_name,
740                    ..err.clone()
741                });
742            }
743            if let Some(err) = err.0.downcast_ref::<BuiltinSerializationError>()
744                && err.rust_name != rust_name
745            {
746                return SerializationError::new(BuiltinSerializationError {
747                    rust_name,
748                    ..err.clone()
749                });
750            }
751        }
752    };
753
754    err
755}
756
757fn serialize_udt<'b>(
758    typ: &ColumnType,
759    keyspace: &str,
760    type_name: &str,
761    values: &[(String, Option<CqlValue>)],
762    writer: CellWriter<'b>,
763) -> Result<WrittenCellProof<'b>, SerializationError> {
764    let (dst_type_name, dst_keyspace, field_types) = match typ {
765        ColumnType::UserDefinedType {
766            definition: udt, ..
767        } => (&udt.name, &udt.keyspace, &udt.field_types),
768        _ => return Err(mk_typck_err::<CqlValue>(typ, UdtTypeCheckErrorKind::NotUdt)),
769    };
770
771    if keyspace != dst_keyspace || type_name != dst_type_name {
772        return Err(mk_typck_err::<CqlValue>(
773            typ,
774            UdtTypeCheckErrorKind::NameMismatch {
775                keyspace: dst_keyspace.clone().into_owned(),
776                type_name: dst_type_name.clone().into_owned(),
777            },
778        ));
779    }
780
781    // Allow columns present in the CQL type which are not present in CqlValue,
782    // but not the other way around
783    let mut field_values = UdtFieldValues::new(field_types, values);
784
785    let mut builder = writer.into_value_builder();
786    for (fname, ftyp) in field_types {
787        // Take a value from the original list.
788        // If a field is missing, write null instead.
789        let fvalue = field_values.take(fname).and_then(|x| x.as_ref());
790
791        let writer = builder.make_sub_writer();
792        match fvalue {
793            None => writer.set_null(),
794            Some(v) => serialize_cql_value(v, ftyp, writer).map_err(|err| {
795                let err = fix_rust_name_in_err::<CqlValue>(err);
796                mk_ser_err::<CqlValue>(
797                    typ,
798                    UdtSerializationErrorKind::FieldSerializationFailed {
799                        field_name: fname.clone().into_owned(),
800                        err,
801                    },
802                )
803            })?,
804        };
805    }
806
807    // If there are some leftover fields, it's an error.
808    if let Some(fname) = field_values.smallest_leftover() {
809        return Err(mk_typck_err::<CqlValue>(
810            typ,
811            UdtTypeCheckErrorKind::NoSuchFieldInUdt {
812                field_name: fname.to_string(),
813            },
814        ));
815    }
816
817    builder
818        .finish()
819        .map_err(|_| mk_ser_err::<CqlValue>(typ, BuiltinSerializationErrorKind::SizeOverflow))
820}
821
822/// The values of a `CqlValue::UserDefinedType`'s fields, looked up by the
823/// fields' names.
824enum UdtFieldValues<'a> {
825    /// The values follow the order of the UDT's fields, possibly with some
826    /// fields missing. This is almost always the case, and then the values
827    /// can be matched up as the fields are walked, without an index.
828    InOrder(Peekable<std::slice::Iter<'a, (String, Option<CqlValue>)>>),
829    Indexed(HashMap<&'a str, &'a Option<CqlValue>>),
830}
831
832impl<'a> UdtFieldValues<'a> {
833    fn new(
834        field_types: &[(Cow<'_, str>, ColumnType<'_>)],
835        values: &'a [(String, Option<CqlValue>)],
836    ) -> Self {
837        let mut in_order = values.iter().peekable();
838        for (fname, _) in field_types {
839            in_order.next_if(|(name, _)| name == fname);
840        }
841        if in_order.peek().is_none() {
842            Self::InOrder(values.iter().peekable())
843        } else {
844            Self::Indexed(values.iter().map(|(k, v)| (k.as_str(), v)).collect())
845        }
846    }
847
848    /// Takes the value of the field `name`. Must be called for the UDT's
849    /// fields in order.
850    fn take(&mut self, name: &str) -> Option<&'a Option<CqlValue>> {
851        match self {
852            Self::InOrder(values) => values.next_if(|(n, _)| n == name).map(|(_, v)| v),
853            Self::Indexed(values) => values.remove(name),
854        }
855    }
856
857    /// Returns the lexicographically smallest of the fields not taken, so
858    /// that the error about them is deterministic.
859    fn smallest_leftover(&self) -> Option<&'a str> {
860        match self {
861            // All the values matched one of the fields, or this would be
862            // `Indexed`.
863            Self::InOrder(_) => None,
864            Self::Indexed(values) => values.keys().min().copied(),
865        }
866    }
867}
868
869fn serialize_tuple_like<'t, 'b>(
870    typ: &ColumnType,
871    field_types: impl Iterator<Item = &'t ColumnType<'t>>,
872    field_values: impl Iterator<Item = &'t Option<CqlValue>>,
873    writer: CellWriter<'b>,
874) -> Result<WrittenCellProof<'b>, SerializationError> {
875    let mut builder = writer.into_value_builder();
876
877    for (index, (el, el_typ)) in field_values.zip(field_types).enumerate() {
878        let sub = builder.make_sub_writer();
879        match el {
880            None => sub.set_null(),
881            Some(el) => serialize_cql_value(el, el_typ, sub).map_err(|err| {
882                let err = fix_rust_name_in_err::<CqlValue>(err);
883                mk_ser_err::<CqlValue>(
884                    typ,
885                    TupleSerializationErrorKind::ElementSerializationFailed { index, err },
886                )
887            })?,
888        };
889    }
890
891    builder
892        .finish()
893        .map_err(|_| mk_ser_err::<CqlValue>(typ, BuiltinSerializationErrorKind::SizeOverflow))
894}
895
896macro_rules! impl_tuple {
897    (
898        $($typs:ident),*;
899        $($fidents:ident),*;
900        $($tidents:ident),*;
901        $length:expr
902    ) => {
903        impl<$($typs: SerializeValue),*> SerializeValue for ($($typs,)*) {
904            fn serialize<'b>(
905                &self,
906                typ: &ColumnType,
907                writer: CellWriter<'b>,
908            ) -> Result<WrittenCellProof<'b>, SerializationError> {
909                let ($($tidents,)*) = match typ {
910                    ColumnType::Tuple(typs) => match typs.as_slice() {
911                        // Allow CQL tuples with more fields than the Rust tuple.
912                        // The extra fields will simply not be serialized (treated as null by the server).
913                        // This mirrors how CqlValue::Tuple serialization works.
914                        [$($tidents),*, ..] => ($($tidents,)*),
915                        _ => return Err(mk_typck_err::<Self>(
916                            typ,
917                            TupleTypeCheckErrorKind::WrongElementCount {
918                                rust_type_el_count: $length,
919                                cql_type_el_count: typs.len(),
920                            }
921                        ))
922                    }
923                    _ => return Err(mk_typck_err::<Self>(
924                        typ,
925                        TupleTypeCheckErrorKind::NotTuple,
926                    ))
927                };
928                let ($($fidents,)*) = self;
929                let mut builder = writer.into_value_builder();
930                let index = 0;
931                $(
932                    <$typs as SerializeValue>::serialize($fidents, $tidents, builder.make_sub_writer())
933                        .map_err(|err| mk_ser_err::<Self>(
934                            typ,
935                            TupleSerializationErrorKind::ElementSerializationFailed {
936                                index,
937                                err,
938                            }
939                        ))?;
940                    let index = index + 1;
941                )*
942                let _ = index;
943                builder
944                    .finish()
945                    .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))
946            }
947        }
948    };
949}
950
951macro_rules! impl_tuples {
952    (;;;$length:expr) => {};
953    (
954        $typ:ident$(, $($typs:ident),*)?;
955        $fident:ident$(, $($fidents:ident),*)?;
956        $tident:ident$(, $($tidents:ident),*)?;
957        $length:expr
958    ) => {
959        impl_tuples!(
960            $($($typs),*)?;
961            $($($fidents),*)?;
962            $($($tidents),*)?;
963            $length - 1
964        );
965        impl_tuple!(
966            $typ$(, $($typs),*)?;
967            $fident$(, $($fidents),*)?;
968            $tident$(, $($tidents),*)?;
969            $length
970        );
971    };
972}
973
974impl_tuples!(
975    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15;
976    f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15;
977    t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15;
978    16
979);
980
981fn serialize_sequence<'t, 'b, T: SerializeValue + 't>(
982    rust_name: &'static str,
983    len: usize,
984    iter: impl Iterator<Item = &'t T>,
985    typ: &ColumnType,
986    writer: CellWriter<'b>,
987) -> Result<WrittenCellProof<'b>, SerializationError> {
988    let elt = match typ {
989        ColumnType::Collection {
990            frozen: _,
991            typ: CollectionType::List(elt),
992        }
993        | ColumnType::Collection {
994            frozen: _,
995            typ: CollectionType::Set(elt),
996        } => elt,
997        _ => {
998            return Err(mk_typck_err_named(
999                rust_name,
1000                typ,
1001                SetOrListTypeCheckErrorKind::NotSetOrList,
1002            ));
1003        }
1004    };
1005
1006    let mut builder = writer.into_value_builder();
1007
1008    let element_count: i32 = len.try_into().map_err(|_| {
1009        mk_ser_err_named(
1010            rust_name,
1011            typ,
1012            SetOrListSerializationErrorKind::TooManyElements,
1013        )
1014    })?;
1015    builder.append_bytes(&element_count.to_be_bytes());
1016
1017    for el in iter {
1018        T::serialize(el, elt, builder.make_sub_writer()).map_err(|err| {
1019            mk_ser_err_named(
1020                rust_name,
1021                typ,
1022                SetOrListSerializationErrorKind::ElementSerializationFailed(err),
1023            )
1024        })?;
1025    }
1026
1027    builder
1028        .finish()
1029        .map_err(|_| mk_ser_err_named(rust_name, typ, BuiltinSerializationErrorKind::SizeOverflow))
1030}
1031
1032/// Serializes an element with constant-length encoding
1033#[cfg(all(scylla_unstable, feature = "unstable-python-rs"))]
1034pub fn serialize_next_constant_length_elem_unstable<'t, T: SerializeValue + 't>(
1035    rust_name: &'static str,
1036    element_type: &ColumnType,
1037    typ: &ColumnType,
1038    builder: &mut CellValueBuilder,
1039    element: &'t T,
1040) -> Result<(), SerializationError> {
1041    serialize_next_constant_length_elem(rust_name, element_type, typ, builder, element)
1042}
1043
1044pub(crate) fn serialize_next_constant_length_elem<'t, T: SerializeValue + 't>(
1045    rust_name: &'static str,
1046    element_type: &ColumnType,
1047    typ: &ColumnType,
1048    builder: &mut CellValueBuilder,
1049    element: &'t T,
1050) -> Result<(), SerializationError> {
1051    T::serialize(
1052        element,
1053        element_type,
1054        builder.make_sub_writer_without_size(),
1055    )
1056    .map_err(|err| {
1057        mk_ser_err_named(
1058            rust_name,
1059            typ,
1060            VectorSerializationErrorKind::ElementSerializationFailed(err),
1061        )
1062    })?;
1063    Ok(())
1064}
1065
1066/// Serializes an element with variable-length encoding (vint length prefix + data).
1067#[cfg(all(scylla_unstable, feature = "unstable-python-rs"))]
1068pub fn serialize_next_variable_length_elem_unstable<'t, T: SerializeValue + 't>(
1069    rust_name: &'static str,
1070    element_type: &ColumnType,
1071    typ: &ColumnType,
1072    builder: &mut CellValueBuilder,
1073    element: &'t T,
1074) -> Result<(), SerializationError> {
1075    serialize_next_variable_length_elem(rust_name, element_type, typ, builder, element)
1076}
1077
1078pub(crate) fn serialize_next_variable_length_elem<'t, T: SerializeValue + 't>(
1079    rust_name: &'static str,
1080    element_type: &ColumnType,
1081    typ: &ColumnType,
1082    builder: &mut CellValueBuilder,
1083    element: &'t T,
1084) -> Result<(), SerializationError> {
1085    T::serialize(
1086        element,
1087        element_type,
1088        builder.make_sub_writer_with_vint_size(),
1089    )
1090    .map_err(|err| {
1091        mk_ser_err_named(
1092            rust_name,
1093            typ,
1094            VectorSerializationErrorKind::ElementSerializationFailed(err),
1095        )
1096    })?;
1097    Ok(())
1098}
1099
1100fn serialize_vector<'t, 'b, T: SerializeValue + 't>(
1101    rust_name: &'static str,
1102    len: usize,
1103    iter: impl Iterator<Item = &'t T>,
1104    element_type: &ColumnType,
1105    dimensions: u16,
1106    typ: &ColumnType,
1107    writer: CellWriter<'b>,
1108) -> Result<WrittenCellProof<'b>, SerializationError> {
1109    if len != dimensions as usize {
1110        return Err(mk_ser_err_named(
1111            rust_name,
1112            typ,
1113            VectorSerializationErrorKind::InvalidNumberOfElements(len, dimensions),
1114        ));
1115    }
1116    let mut builder = writer.into_value_builder();
1117    match element_type.type_size_for_vector() {
1118        Some(_) => {
1119            for element in iter {
1120                serialize_next_constant_length_elem(
1121                    rust_name,
1122                    element_type,
1123                    typ,
1124                    &mut builder,
1125                    element,
1126                )?;
1127            }
1128        }
1129        None => {
1130            for element in iter {
1131                serialize_next_variable_length_elem(
1132                    rust_name,
1133                    element_type,
1134                    typ,
1135                    &mut builder,
1136                    element,
1137                )?;
1138            }
1139        }
1140    }
1141
1142    builder
1143        .finish()
1144        .map_err(|_| mk_ser_err_named(rust_name, typ, BuiltinSerializationErrorKind::SizeOverflow))
1145}
1146
1147fn serialize_mapping<'t, 'b, K: SerializeValue + 't, V: SerializeValue + 't>(
1148    rust_name: &'static str,
1149    len: usize,
1150    iter: impl Iterator<Item = (&'t K, &'t V)>,
1151    typ: &ColumnType,
1152    writer: CellWriter<'b>,
1153) -> Result<WrittenCellProof<'b>, SerializationError> {
1154    let (ktyp, vtyp) = match typ {
1155        ColumnType::Collection {
1156            frozen: _,
1157            typ: CollectionType::Map(k, v),
1158        } => (k, v),
1159        _ => {
1160            return Err(mk_typck_err_named(
1161                rust_name,
1162                typ,
1163                MapTypeCheckErrorKind::NotMap,
1164            ));
1165        }
1166    };
1167
1168    let mut builder = writer.into_value_builder();
1169
1170    let element_count: i32 = len.try_into().map_err(|_| {
1171        mk_ser_err_named(rust_name, typ, MapSerializationErrorKind::TooManyElements)
1172    })?;
1173    builder.append_bytes(&element_count.to_be_bytes());
1174
1175    for (k, v) in iter {
1176        K::serialize(k, ktyp, builder.make_sub_writer()).map_err(|err| {
1177            mk_ser_err_named(
1178                rust_name,
1179                typ,
1180                MapSerializationErrorKind::KeySerializationFailed(err),
1181            )
1182        })?;
1183        V::serialize(v, vtyp, builder.make_sub_writer()).map_err(|err| {
1184            mk_ser_err_named(
1185                rust_name,
1186                typ,
1187                MapSerializationErrorKind::ValueSerializationFailed(err),
1188            )
1189        })?;
1190    }
1191
1192    builder
1193        .finish()
1194        .map_err(|_| mk_ser_err_named(rust_name, typ, BuiltinSerializationErrorKind::SizeOverflow))
1195}
1196
1197/// Type checking of one of the built-in types failed.
1198#[derive(Debug, Error, Clone)]
1199#[error("Failed to type check Rust type {rust_name} against CQL type {got:?}: {kind}")]
1200pub struct BuiltinTypeCheckError {
1201    /// Name of the Rust type being serialized.
1202    pub rust_name: &'static str,
1203
1204    /// The CQL type that the Rust type was being serialized to.
1205    pub got: ColumnType<'static>,
1206
1207    /// Detailed information about the failure.
1208    pub kind: BuiltinTypeCheckErrorKind,
1209}
1210
1211/// Creates a [`BuiltinTypeCheckError`] with the given kind.
1212pub fn mk_typck_err<T: ?Sized>(
1213    got: &ColumnType,
1214    kind: impl Into<BuiltinTypeCheckErrorKind>,
1215) -> SerializationError {
1216    mk_typck_err_named(std::any::type_name::<T>(), got, kind)
1217}
1218
1219// Outlined and cold: building the error deep-clones the `ColumnType` and
1220// allocates, which would otherwise bloat every `serialize` body enough to
1221// stop it being inlined into a collection's element loop.
1222#[cold]
1223#[inline(never)]
1224fn mk_typck_err_named(
1225    name: &'static str,
1226    got: &ColumnType,
1227    kind: impl Into<BuiltinTypeCheckErrorKind>,
1228) -> SerializationError {
1229    SerializationError::new(BuiltinTypeCheckError {
1230        rust_name: name,
1231        got: got.clone().into_owned(),
1232        kind: kind.into(),
1233    })
1234}
1235
1236/// Serialization of one of the built-in types failed.
1237#[derive(Debug, Error, Clone)]
1238#[error("Failed to serialize Rust type {rust_name} into CQL type {got:?}: {kind}")]
1239pub struct BuiltinSerializationError {
1240    /// Name of the Rust type being serialized.
1241    pub rust_name: &'static str,
1242
1243    /// The CQL type that the Rust type was being serialized to.
1244    pub got: ColumnType<'static>,
1245
1246    /// Detailed information about the failure.
1247    pub kind: BuiltinSerializationErrorKind,
1248}
1249
1250/// Creates a [`BuiltinSerializationError`] with the given kind.
1251pub fn mk_ser_err<T: ?Sized>(
1252    got: &ColumnType,
1253    kind: impl Into<BuiltinSerializationErrorKind>,
1254) -> SerializationError {
1255    mk_ser_err_named(std::any::type_name::<T>(), got, kind)
1256}
1257
1258// Outlined and cold: building the error deep-clones the `ColumnType` and
1259// allocates, which would otherwise bloat every `serialize` body enough to
1260// stop it being inlined into a collection's element loop.
1261#[cold]
1262#[inline(never)]
1263fn mk_ser_err_named(
1264    name: &'static str,
1265    got: &ColumnType,
1266    kind: impl Into<BuiltinSerializationErrorKind>,
1267) -> SerializationError {
1268    SerializationError::new(BuiltinSerializationError {
1269        rust_name: name,
1270        got: got.clone().into_owned(),
1271        kind: kind.into(),
1272    })
1273}
1274
1275/// Describes why type checking some of the built-in types has failed.
1276#[derive(Debug, Clone)]
1277#[non_exhaustive]
1278pub enum BuiltinTypeCheckErrorKind {
1279    /// Expected one from a list of particular types.
1280    MismatchedType {
1281        /// The list of types that the Rust type can serialize as.
1282        expected: &'static [ColumnType<'static>],
1283    },
1284
1285    /// Expected a type that can be empty.
1286    NotEmptyable,
1287
1288    /// A type check failure specific to a CQL set or list.
1289    SetOrListError(SetOrListTypeCheckErrorKind),
1290
1291    /// A type check failure specific to a CQL map.
1292    MapError(MapTypeCheckErrorKind),
1293
1294    /// A type check failure specific to a CQL tuple.
1295    TupleError(TupleTypeCheckErrorKind),
1296
1297    /// A type check failure specific to a CQL UDT.
1298    UdtError(UdtTypeCheckErrorKind),
1299}
1300
1301impl From<SetOrListTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
1302    fn from(value: SetOrListTypeCheckErrorKind) -> Self {
1303        BuiltinTypeCheckErrorKind::SetOrListError(value)
1304    }
1305}
1306
1307impl From<MapTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
1308    fn from(value: MapTypeCheckErrorKind) -> Self {
1309        BuiltinTypeCheckErrorKind::MapError(value)
1310    }
1311}
1312
1313impl From<TupleTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
1314    fn from(value: TupleTypeCheckErrorKind) -> Self {
1315        BuiltinTypeCheckErrorKind::TupleError(value)
1316    }
1317}
1318
1319impl From<UdtTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
1320    fn from(value: UdtTypeCheckErrorKind) -> Self {
1321        BuiltinTypeCheckErrorKind::UdtError(value)
1322    }
1323}
1324
1325impl Display for BuiltinTypeCheckErrorKind {
1326    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1327        match self {
1328            BuiltinTypeCheckErrorKind::MismatchedType { expected } => {
1329                write!(f, "expected one of the CQL types: {expected:?}")
1330            }
1331            BuiltinTypeCheckErrorKind::NotEmptyable => {
1332                f.write_str("the separate empty representation is not valid for this type")
1333            }
1334            BuiltinTypeCheckErrorKind::SetOrListError(err) => err.fmt(f),
1335            BuiltinTypeCheckErrorKind::MapError(err) => err.fmt(f),
1336            BuiltinTypeCheckErrorKind::TupleError(err) => err.fmt(f),
1337            BuiltinTypeCheckErrorKind::UdtError(err) => err.fmt(f),
1338        }
1339    }
1340}
1341
1342/// Describes why serialization of some of the built-in types has failed.
1343#[derive(Debug, Clone)]
1344#[non_exhaustive]
1345pub enum BuiltinSerializationErrorKind {
1346    /// The size of the Rust value is too large to fit in the CQL serialization
1347    /// format (over i32::MAX bytes).
1348    SizeOverflow,
1349
1350    /// The Rust value is out of range supported by the CQL type.
1351    ValueOverflow,
1352
1353    /// A serialization failure specific to a CQL set or list.
1354    SetOrListError(SetOrListSerializationErrorKind),
1355
1356    /// A serialization failure specific to a CQL set or list.
1357    VectorError(VectorSerializationErrorKind),
1358
1359    /// A serialization failure specific to a CQL map.
1360    MapError(MapSerializationErrorKind),
1361
1362    /// A serialization failure specific to a CQL tuple.
1363    TupleError(TupleSerializationErrorKind),
1364
1365    /// A serialization failure specific to a CQL UDT.
1366    UdtError(UdtSerializationErrorKind),
1367}
1368
1369impl From<SetOrListSerializationErrorKind> for BuiltinSerializationErrorKind {
1370    fn from(value: SetOrListSerializationErrorKind) -> Self {
1371        BuiltinSerializationErrorKind::SetOrListError(value)
1372    }
1373}
1374
1375impl From<VectorSerializationErrorKind> for BuiltinSerializationErrorKind {
1376    fn from(value: VectorSerializationErrorKind) -> Self {
1377        BuiltinSerializationErrorKind::VectorError(value)
1378    }
1379}
1380
1381impl From<MapSerializationErrorKind> for BuiltinSerializationErrorKind {
1382    fn from(value: MapSerializationErrorKind) -> Self {
1383        BuiltinSerializationErrorKind::MapError(value)
1384    }
1385}
1386
1387impl From<TupleSerializationErrorKind> for BuiltinSerializationErrorKind {
1388    fn from(value: TupleSerializationErrorKind) -> Self {
1389        BuiltinSerializationErrorKind::TupleError(value)
1390    }
1391}
1392
1393impl From<UdtSerializationErrorKind> for BuiltinSerializationErrorKind {
1394    fn from(value: UdtSerializationErrorKind) -> Self {
1395        BuiltinSerializationErrorKind::UdtError(value)
1396    }
1397}
1398
1399impl Display for BuiltinSerializationErrorKind {
1400    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1401        match self {
1402            BuiltinSerializationErrorKind::SizeOverflow => {
1403                f.write_str("the Rust value is too big to be serialized in the CQL protocol format")
1404            }
1405            BuiltinSerializationErrorKind::ValueOverflow => {
1406                f.write_str("the Rust value is out of range supported by the CQL type")
1407            }
1408            BuiltinSerializationErrorKind::SetOrListError(err) => err.fmt(f),
1409            BuiltinSerializationErrorKind::VectorError(err) => err.fmt(f),
1410            BuiltinSerializationErrorKind::MapError(err) => err.fmt(f),
1411            BuiltinSerializationErrorKind::TupleError(err) => err.fmt(f),
1412            BuiltinSerializationErrorKind::UdtError(err) => err.fmt(f),
1413        }
1414    }
1415}
1416
1417/// Describes why type checking of a map type failed.
1418#[derive(Debug, Clone)]
1419#[non_exhaustive]
1420pub enum MapTypeCheckErrorKind {
1421    /// The CQL type is not a map.
1422    NotMap,
1423}
1424
1425impl Display for MapTypeCheckErrorKind {
1426    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1427        match self {
1428            MapTypeCheckErrorKind::NotMap => f.write_str(
1429                "the CQL type the Rust type was attempted to be type checked against was not a map",
1430            ),
1431        }
1432    }
1433}
1434
1435/// Describes why serialization of a map type failed.
1436#[derive(Debug, Clone)]
1437#[non_exhaustive]
1438pub enum MapSerializationErrorKind {
1439    /// The many contains too many items, exceeding the protocol limit (i32::MAX).
1440    TooManyElements,
1441
1442    /// One of the keys in the map failed to serialize.
1443    KeySerializationFailed(SerializationError),
1444
1445    /// One of the values in the map failed to serialize.
1446    ValueSerializationFailed(SerializationError),
1447}
1448
1449impl Display for MapSerializationErrorKind {
1450    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1451        match self {
1452            MapSerializationErrorKind::TooManyElements => {
1453                f.write_str("the map contains too many elements to fit in CQL representation")
1454            }
1455            MapSerializationErrorKind::KeySerializationFailed(err) => {
1456                write!(f, "failed to serialize one of the keys: {err}")
1457            }
1458            MapSerializationErrorKind::ValueSerializationFailed(err) => {
1459                write!(f, "failed to serialize one of the values: {err}")
1460            }
1461        }
1462    }
1463}
1464
1465/// Describes why type checking of a set or list type failed.
1466#[derive(Debug, Clone)]
1467#[non_exhaustive]
1468pub enum SetOrListTypeCheckErrorKind {
1469    /// The CQL type is neither a set, nor a list, nor a vector.
1470    NotSetOrList,
1471}
1472
1473impl Display for SetOrListTypeCheckErrorKind {
1474    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1475        match self {
1476            SetOrListTypeCheckErrorKind::NotSetOrList => {
1477                f.write_str("the CQL type the Rust type was attempted to be type checked against was neither a set, nor a list, nor a vector")
1478            }
1479        }
1480    }
1481}
1482
1483/// Describes why serialization of a set or list type failed.
1484#[derive(Debug, Clone)]
1485#[non_exhaustive]
1486pub enum SetOrListSerializationErrorKind {
1487    /// The set/list contains too many items, exceeding the protocol limit (i32::MAX).
1488    TooManyElements,
1489
1490    /// One of the elements of the set/list failed to serialize.
1491    ElementSerializationFailed(SerializationError),
1492}
1493
1494impl Display for SetOrListSerializationErrorKind {
1495    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1496        match self {
1497            SetOrListSerializationErrorKind::TooManyElements => f.write_str(
1498                "the collection contains too many elements to fit in CQL representation",
1499            ),
1500            SetOrListSerializationErrorKind::ElementSerializationFailed(err) => {
1501                write!(f, "failed to serialize one of the elements: {err}")
1502            }
1503        }
1504    }
1505}
1506
1507/// Describes why serialization of a vector type failed.
1508#[derive(Error, Debug, Clone)]
1509#[non_exhaustive]
1510pub enum VectorSerializationErrorKind {
1511    /// The number of elements in the serialized collection does not match
1512    /// the number of vector dimensions
1513    #[error(
1514        "number of vector elements ({0}) does not match the number of declared dimensions ({1})"
1515    )]
1516    InvalidNumberOfElements(usize, u16),
1517
1518    /// One of the elements of the vector failed to serialize.
1519    #[error("failed to serialize one of the elements: {0}")]
1520    ElementSerializationFailed(SerializationError),
1521}
1522
1523/// Describes why type checking of a tuple failed.
1524#[derive(Debug, Clone)]
1525#[non_exhaustive]
1526pub enum TupleTypeCheckErrorKind {
1527    /// The CQL type is not a tuple.
1528    NotTuple,
1529
1530    /// The tuple has the wrong element count.
1531    ///
1532    /// Note that it is allowed to write a Rust tuple with less elements
1533    /// than the corresponding CQL type, but not more. The additional, unknown
1534    /// elements will be set to null.
1535    WrongElementCount {
1536        /// The number of elements that the Rust tuple has.
1537        rust_type_el_count: usize,
1538
1539        /// The number of elements that the CQL tuple type has.
1540        cql_type_el_count: usize,
1541    },
1542}
1543
1544impl Display for TupleTypeCheckErrorKind {
1545    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1546        match self {
1547            TupleTypeCheckErrorKind::NotTuple => f.write_str(
1548                "the CQL type the Rust type was attempted to be type checked against is not a tuple"
1549            ),
1550            TupleTypeCheckErrorKind::WrongElementCount { rust_type_el_count, cql_type_el_count } => write!(
1551                f,
1552                "wrong tuple element count: CQL type has {cql_type_el_count}, the Rust tuple has {rust_type_el_count}"
1553            ),
1554        }
1555    }
1556}
1557
1558/// Describes why serialize of a tuple failed.
1559#[derive(Debug, Clone)]
1560#[non_exhaustive]
1561pub enum TupleSerializationErrorKind {
1562    /// One of the tuple elements failed to serialize.
1563    ElementSerializationFailed {
1564        /// Index of the tuple element that failed to serialize.
1565        index: usize,
1566
1567        /// The error that caused the tuple field serialization to fail.
1568        err: SerializationError,
1569    },
1570}
1571
1572impl Display for TupleSerializationErrorKind {
1573    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1574        match self {
1575            TupleSerializationErrorKind::ElementSerializationFailed { index, err } => {
1576                write!(f, "element no. {index} failed to serialize: {err}")
1577            }
1578        }
1579    }
1580}
1581
1582/// Describes why type checking of a user defined type failed.
1583#[derive(Debug, Clone)]
1584#[non_exhaustive]
1585pub enum UdtTypeCheckErrorKind {
1586    /// The CQL type is not a user defined type.
1587    NotUdt,
1588
1589    /// The name of the UDT being serialized to does not match.
1590    NameMismatch {
1591        /// Keyspace in which the UDT was defined.
1592        keyspace: String,
1593
1594        /// Name of the UDT.
1595        type_name: String,
1596    },
1597
1598    /// The Rust data does not have a field that is required in the CQL UDT type.
1599    ValueMissingForUdtField {
1600        /// Name of field that the CQL UDT requires but is missing in the Rust struct.
1601        field_name: String,
1602    },
1603
1604    /// The Rust data contains a field that is not present in the UDT.
1605    NoSuchFieldInUdt {
1606        /// Name of the Rust struct field that is missing in the UDT.
1607        field_name: String,
1608    },
1609
1610    /// A different field name was expected at given position.
1611    FieldNameMismatch {
1612        /// The name of the Rust field.
1613        rust_field_name: String,
1614
1615        /// The name of the CQL UDT field.
1616        db_field_name: String,
1617    },
1618}
1619
1620impl Display for UdtTypeCheckErrorKind {
1621    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1622        match self {
1623            UdtTypeCheckErrorKind::NotUdt => f.write_str(
1624                "the CQL type the Rust type was attempted to be type checked against is not a UDT",
1625            ),
1626            UdtTypeCheckErrorKind::NameMismatch {
1627                keyspace,
1628                type_name,
1629            } => write!(
1630                f,
1631                "the Rust UDT name does not match the actual CQL UDT name ({keyspace}.{type_name})"
1632            ),
1633            UdtTypeCheckErrorKind::ValueMissingForUdtField { field_name } => {
1634                write!(
1635                    f,
1636                    "the field {field_name} is missing in the Rust data but is required by the CQL UDT type"
1637                )
1638            }
1639            UdtTypeCheckErrorKind::NoSuchFieldInUdt { field_name } => write!(
1640                f,
1641                "the field {field_name} that is present in the Rust data is not present in the CQL type"
1642            ),
1643            UdtTypeCheckErrorKind::FieldNameMismatch {
1644                rust_field_name,
1645                db_field_name,
1646            } => write!(
1647                f,
1648                "expected field with name {db_field_name} at given position, but the Rust field name is {rust_field_name}"
1649            ),
1650        }
1651    }
1652}
1653
1654/// Describes why serialization of a user defined type failed.
1655#[derive(Debug, Clone)]
1656#[non_exhaustive]
1657pub enum UdtSerializationErrorKind {
1658    /// One of the fields failed to serialize.
1659    FieldSerializationFailed {
1660        /// Name of the field which failed to serialize.
1661        field_name: String,
1662
1663        /// The error that caused the UDT field serialization to fail.
1664        err: SerializationError,
1665    },
1666}
1667
1668impl Display for UdtSerializationErrorKind {
1669    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1670        match self {
1671            UdtSerializationErrorKind::FieldSerializationFailed { field_name, err } => {
1672                write!(f, "field {field_name} failed to serialize: {err}")
1673            }
1674        }
1675    }
1676}
1677
1678#[cfg(test)]
1679#[path = "value_tests.rs"]
1680pub(crate) mod tests;