cassandra_protocol/frame/
traits.rs

1use crate::error;
2use crate::frame::Version;
3use crate::query;
4use num_bigint::BigInt;
5use std::io::{Cursor, Write};
6
7/// Trait that should be implemented by all types that wish to be serialized to a buffer.
8pub trait Serialize {
9    /// Serializes given value using the cursor.
10    fn serialize(&self, cursor: &mut Cursor<&mut Vec<u8>>, version: Version);
11
12    /// Wrapper for easily starting hierarchical serialization.
13    fn serialize_to_vec(&self, version: Version) -> Vec<u8> {
14        let mut buf = vec![];
15
16        self.serialize(&mut Cursor::new(&mut buf), version);
17        buf
18    }
19}
20
21/// `FromBytes` should be used to parse an array of bytes into a structure.
22pub trait FromBytes {
23    /// It gets and array of bytes and should return an implementor struct.
24    fn from_bytes(bytes: &[u8]) -> error::Result<Self>
25    where
26        Self: Sized;
27}
28
29/// `FromCursor` should be used to get parsed structure from an `io:Cursor`
30/// which bound to an array of bytes.
31pub trait FromCursor {
32    /// Tries to parse Self from a cursor of bytes.
33    fn from_cursor(cursor: &mut Cursor<&[u8]>, version: Version) -> error::Result<Self>
34    where
35        Self: Sized;
36}
37
38/// The trait that allows transformation of `Self` to CDRS query values.
39pub trait IntoQueryValues {
40    fn into_query_values(self) -> query::QueryValues;
41}
42
43pub trait TryFromRow: Sized {
44    fn try_from_row(row: crate::types::rows::Row) -> error::Result<Self>;
45}
46
47pub trait TryFromUdt: Sized {
48    fn try_from_udt(udt: crate::types::udt::Udt) -> error::Result<Self>;
49}
50
51impl<const S: usize> Serialize for [u8; S] {
52    fn serialize(&self, cursor: &mut Cursor<&mut Vec<u8>>, _version: Version) {
53        let _ = cursor.write(self);
54    }
55}
56
57impl Serialize for &[u8] {
58    #[inline]
59    fn serialize(&self, cursor: &mut Cursor<&mut Vec<u8>>, _version: Version) {
60        let _ = cursor.write(self);
61    }
62}
63
64impl Serialize for Vec<u8> {
65    #[inline]
66    fn serialize(&self, cursor: &mut Cursor<&mut Vec<u8>>, _version: Version) {
67        let _ = cursor.write(self);
68    }
69}
70
71impl Serialize for BigInt {
72    #[inline]
73    fn serialize(&self, cursor: &mut Cursor<&mut Vec<u8>>, _version: Version) {
74        let _ = cursor.write(&self.to_signed_bytes_be());
75    }
76}
77
78macro_rules! impl_serialized {
79    ($t:ty) => {
80        impl Serialize for $t {
81            #[inline]
82            fn serialize(&self, cursor: &mut Cursor<&mut Vec<u8>>, _version: Version) {
83                let _ = cursor.write(&self.to_be_bytes());
84            }
85        }
86    };
87}
88
89impl_serialized!(i8);
90impl_serialized!(i16);
91impl_serialized!(i32);
92impl_serialized!(i64);
93impl_serialized!(u8);
94impl_serialized!(u16);
95impl_serialized!(u32);
96impl_serialized!(u64);