1use super::types::date_and_time::MysqlTime;
2use super::MysqlType;
34use crate::deserialize;
5use std::error::Error;
6use std::mem::MaybeUninit;
78/// Raw mysql value as received from the database
9#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for MysqlValue<'a> {
#[inline]
fn clone(&self) -> MysqlValue<'a> {
MysqlValue {
raw: ::core::clone::Clone::clone(&self.raw),
tpe: ::core::clone::Clone::clone(&self.tpe),
}
}
}Clone, #[automatically_derived]
impl<'a> ::core::fmt::Debug for MysqlValue<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "MysqlValue",
"raw", &self.raw, "tpe", &&self.tpe)
}
}Debug)]
10pub struct MysqlValue<'a> {
11 raw: &'a [u8],
12 tpe: MysqlType,
13}
1415impl<'a> MysqlValue<'a> {
16/// Create a new instance of [MysqlValue] based on a byte buffer
17 /// and information about the type of the value represented by the
18 /// given buffer
19#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
20pub fn new(raw: &'a [u8], tpe: MysqlType) -> Self {
21Self::new_internal(raw, tpe)
22 }
2324pub(in crate::mysql) fn new_internal(raw: &'a [u8], tpe: MysqlType) -> Self {
25Self { raw, tpe }
26 }
2728/// Get the underlying raw byte representation
29pub fn as_bytes(&self) -> &[u8] {
30self.raw
31 }
3233/// Get the mysql type of the current value
34pub fn value_type(&self) -> MysqlType {
35self.tpe
36 }
3738/// Checks that the type code is valid, and interprets the data as a
39 /// `MysqlTime` pointer
40// We use `ptr::copy` to read the actual data
41 // and copy it over to the returned `MysqlTime` instance
42#[allow(unsafe_code)] // MaybeUninit + ptr copy
43pub(crate) fn time_value(&self) -> deserialize::Result<MysqlTime> {
44match self.tpe {
45 MysqlType::Time | MysqlType::Date | MysqlType::DateTime | MysqlType::Timestamp => {
46// we check for the size of the `MYSQL_TIME` type from `mysqlclient_sys` here as
47 // certain older libmysqlclient and newer libmariadb versions do not have all the
48 // same fields (and size) as the `MysqlTime` type from diesel. The later one is modeled after
49 // the type from newer libmysqlclient
50self.too_short_buffer(
51#[cfg(feature = "mysql")]
52std::mem::size_of::<mysqlclient_sys::MYSQL_TIME>(),
53#[cfg(not(feature = "mysql"))]
54std::mem::size_of::<MysqlTime>(),
55"timestamp",
56 )?;
57// To ensure we copy the right number of bytes we need to make sure to copy not more bytes than needed
58 // for `MysqlTime` and not more bytes than inside of the buffer
59let len = std::cmp::min(std::mem::size_of::<MysqlTime>(), self.raw.len());
60// Zero is a valid pattern for this type so we are fine with initializing all fields to zero
61 // If the provided byte buffer is too short we just use 0 as default value
62let mut out = MaybeUninit::<MysqlTime>::zeroed();
63// Make sure to check that the boolean is an actual bool value, so 0 or 1
64 // as anything else is UB in rust
65let neg_offset = { builtin # offset_of(MysqlTime, neg) }std::mem::offset_of!(MysqlTime, neg);
66if neg_offset < self.raw.len()
67 && self.raw[neg_offset] != 0
68&& self.raw[neg_offset] != 1
69{
70return Err(
71"Received invalid value for `neg` in the `MysqlTime` datastructure".into(),
72 );
73 }
74let result = unsafe {
75// SAFETY: We copy over the bytes from our raw buffer to the `MysqlTime` instance
76 // This type is correctly aligned and we ensure that we do not copy more bytes than are there
77 // We are also sure that these ptr do not overlap as they are completely different
78 // instances
79std::ptr::copy_nonoverlapping(
80self.raw.as_ptr(),
81out.as_mut_ptr() as *mut u8,
82len,
83 );
84// SAFETY: all zero is a valid pattern for this type
85 // Otherwise any other bit pattern is also valid, beside
86 // neg being something other than 0 or 1
87 // We check for that above by looking at the byte before copying
88out.assume_init()
89 };
90if result.neg {
91Err("Negative dates/times are not yet supported".into())
92 } else {
93Ok(result)
94 }
95 }
96_ => Err(self.invalid_type_code("timestamp")),
97 }
98 }
99100/// Returns the numeric representation of this value, based on the type code.
101 /// Returns an error if the type code is not numeric.
102pub(crate) fn numeric_value(&self) -> deserialize::Result<NumericRepresentation<'_>> {
103Ok(match self.tpe {
104 MysqlType::UnsignedTiny | MysqlType::Tiny => {
105 NumericRepresentation::Tiny(self.raw[0].try_into()?)
106 }
107 MysqlType::UnsignedShort | MysqlType::Short => {
108self.too_short_buffer(2, "Short")?;
109 NumericRepresentation::Small(i16::from_ne_bytes((&self.raw[..2]).try_into()?))
110 }
111 MysqlType::UnsignedLong | MysqlType::Long => {
112self.too_short_buffer(4, "Long")?;
113 NumericRepresentation::Medium(i32::from_ne_bytes((&self.raw[..4]).try_into()?))
114 }
115 MysqlType::UnsignedLongLong | MysqlType::LongLong => {
116self.too_short_buffer(8, "LongLong")?;
117 NumericRepresentation::Big(i64::from_ne_bytes(self.raw.try_into()?))
118 }
119 MysqlType::Float => {
120self.too_short_buffer(4, "Float")?;
121 NumericRepresentation::Float(f32::from_ne_bytes(self.raw.try_into()?))
122 }
123 MysqlType::Double => {
124self.too_short_buffer(8, "Double")?;
125 NumericRepresentation::Double(f64::from_ne_bytes(self.raw.try_into()?))
126 }
127128 MysqlType::Numeric => NumericRepresentation::Decimal(self.raw),
129_ => return Err(self.invalid_type_code("number")),
130 })
131 }
132133fn invalid_type_code(&self, expected: &str) -> Box<dyn Error + Send + Sync> {
134::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Invalid representation received for {0}: {1:?}",
expected, self.tpe))
})format!(
135"Invalid representation received for {}: {:?}",
136 expected, self.tpe
137 )138 .into()
139 }
140141fn too_short_buffer(&self, expected: usize, tpe: &'static str) -> deserialize::Result<()> {
142if self.raw.len() < expected {
143Err(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Received a buffer with an invalid size while trying to read a {1} value: Expected at least {2} bytes but got {0}",
self.raw.len(), tpe, expected))
})format!(
144"Received a buffer with an invalid size while trying \
145 to read a {tpe} value: Expected at least {expected} bytes \
146 but got {}",
147self.raw.len()
148 )149 .into())
150 } else {
151Ok(())
152 }
153 }
154}
155156/// Represents all possible forms MySQL transmits integers
157#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for NumericRepresentation<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
NumericRepresentation::Tiny(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Tiny",
&__self_0),
NumericRepresentation::Small(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Small",
&__self_0),
NumericRepresentation::Medium(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Medium",
&__self_0),
NumericRepresentation::Big(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Big",
&__self_0),
NumericRepresentation::Float(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Float",
&__self_0),
NumericRepresentation::Double(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Double",
&__self_0),
NumericRepresentation::Decimal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Decimal", &__self_0),
}
}
}Debug, #[automatically_derived]
impl<'a> ::core::clone::Clone for NumericRepresentation<'a> {
#[inline]
fn clone(&self) -> NumericRepresentation<'a> {
let _: ::core::clone::AssertParamIsClone<i8>;
let _: ::core::clone::AssertParamIsClone<i16>;
let _: ::core::clone::AssertParamIsClone<i32>;
let _: ::core::clone::AssertParamIsClone<i64>;
let _: ::core::clone::AssertParamIsClone<f32>;
let _: ::core::clone::AssertParamIsClone<f64>;
let _: ::core::clone::AssertParamIsClone<&'a [u8]>;
*self
}
}Clone, #[automatically_derived]
impl<'a> ::core::marker::Copy for NumericRepresentation<'a> { }Copy)]
158#[non_exhaustive]
159pub enum NumericRepresentation<'a> {
160/// Corresponds to `MYSQL_TYPE_TINY`
161Tiny(i8),
162/// Corresponds to `MYSQL_TYPE_SHORT`
163Small(i16),
164/// Corresponds to `MYSQL_TYPE_INT24` and `MYSQL_TYPE_LONG`
165Medium(i32),
166/// Corresponds to `MYSQL_TYPE_LONGLONG`
167Big(i64),
168/// Corresponds to `MYSQL_TYPE_FLOAT`
169Float(f32),
170/// Corresponds to `MYSQL_TYPE_DOUBLE`
171Double(f64),
172/// Corresponds to `MYSQL_TYPE_DECIMAL` and `MYSQL_TYPE_NEWDECIMAL`
173Decimal(&'a [u8]),
174}
175176#[test]
177#[allow(unsafe_code, reason = "Test code")]
178fn invalid_reads() {
179use crate::data_types::MysqlTimestampType;
180181assert!(MysqlValue::new_internal(&[1], MysqlType::Timestamp)
182 .time_value()
183 .is_err());
184let v = MysqlTime {
185 year: 2025,
186 month: 9,
187 day: 15,
188 hour: 22,
189 minute: 3,
190 second: 10,
191 second_part: 0,
192 neg: false,
193 time_type: MysqlTimestampType::MYSQL_TIMESTAMP_DATETIME,
194 time_zone_displacement: 0,
195 };
196let mut bytes = [0; std::mem::size_of::<MysqlTime>()];
197unsafe {
198// SAFETY: Test code
199 // also the size matches and we want to get raw bytes
200std::ptr::copy(
201&v as *const MysqlTime as *const u8,
202 bytes.as_mut_ptr(),
203 bytes.len(),
204 );
205 }
206let offset = std::mem::offset_of!(MysqlTime, neg);
207 bytes[offset] = 42;
208assert!(MysqlValue::new_internal(&bytes, MysqlType::Timestamp)
209 .time_value()
210 .is_err());
211212assert!(MysqlValue::new_internal(&[1, 2], MysqlType::Long)
213 .numeric_value()
214 .is_err());
215216assert!(MysqlValue::new_internal(&[1, 2, 3, 4], MysqlType::LongLong)
217 .numeric_value()
218 .is_err());
219220assert!(MysqlValue::new_internal(&[1], MysqlType::Short)
221 .numeric_value()
222 .is_err());
223224assert!(MysqlValue::new_internal(&[1, 2, 3, 4], MysqlType::Double)
225 .numeric_value()
226 .is_err());
227228assert!(MysqlValue::new_internal(&[1, 2], MysqlType::Float)
229 .numeric_value()
230 .is_err());
231232assert!(MysqlValue::new_internal(&[1], MysqlType::Tiny)
233 .numeric_value()
234 .is_ok());
235}