Skip to main content

mysql_replication/events/rows/
value.rs

1use crate::{Result, error::invalid};
2use std::fmt;
3
4/// A wire integer without an assumed SQL signedness.
5/// TABLE_MAP's required metadata does not identify signed/unsigned columns.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct IntegerValue<'a> {
8    pub(super) data: &'a [u8],
9}
10impl<'a> IntegerValue<'a> {
11    pub fn raw_bytes(self) -> &'a [u8] {
12        self.data
13    }
14    /// Interprets the actual wire width as an unsigned integer.
15    pub fn unsigned(self) -> u64 {
16        let mut bytes = [0; 8];
17        bytes[..self.data.len()].copy_from_slice(self.data);
18        u64::from_le_bytes(bytes)
19    }
20    /// Sign-extends the actual wire width, including three-byte MEDIUMINT.
21    pub fn signed(self) -> i64 {
22        let shift = (8 - self.data.len()) * 8;
23        ((self.unsigned() << shift) as i64) >> shift
24    }
25}
26
27/// Exact packed DECIMAL, borrowing the validated wire bytes.
28/// Formatting preserves scale and never passes through floating point.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct DecimalValue<'a> {
31    data: &'a [u8],
32    precision: u8,
33    scale: u8,
34}
35impl<'a> DecimalValue<'a> {
36    pub(super) fn new(data: &'a [u8], precision: u8, scale: u8) -> Result<Self> {
37        let value = Self {
38            data,
39            precision,
40            scale,
41        };
42        if value
43            .groups()
44            .any(|(digits, n)| n >= 10u32.pow(digits as u32))
45        {
46            return Err(invalid("invalid packed DECIMAL digit group"));
47        }
48        Ok(value)
49    }
50    pub fn raw_bytes(self) -> &'a [u8] {
51        self.data
52    }
53    pub fn precision(self) -> u8 {
54        self.precision
55    }
56    pub fn scale(self) -> u8 {
57        self.scale
58    }
59    fn negative(&self) -> bool {
60        self.data[0] & 0x80 == 0
61    }
62    fn groups(&self) -> impl Iterator<Item = (usize, u32)> + '_ {
63        let integral = usize::from(self.precision - self.scale);
64        let scale = usize::from(self.scale);
65        let mut offset = 0;
66        std::iter::once(integral % 9)
67            .filter(|&n| n != 0)
68            .chain(std::iter::repeat_n(9, integral / 9))
69            .chain(std::iter::repeat_n(9, scale / 9))
70            .chain(std::iter::once(scale % 9).filter(|&n| n != 0))
71            .map(move |digits| {
72                let width = decimal_group_size(digits);
73                let mut n = 0;
74                for &byte in &self.data[offset..offset + width] {
75                    let byte = if offset == 0 {
76                        // Only the first byte carries the sign bit.
77                        byte ^ 0x80
78                    } else {
79                        byte
80                    };
81                    let byte = if self.negative() { !byte } else { byte };
82                    n = (n << 8) | u32::from(byte);
83                    offset += 1;
84                }
85                (digits, n)
86            })
87    }
88}
89impl fmt::Display for DecimalValue<'_> {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        if self.negative() && self.groups().any(|(_, n)| n != 0) {
92            f.write_str("-")?;
93        }
94        let integral = usize::from(self.precision - self.scale).div_ceil(9);
95        let mut groups = self.groups();
96        let mut started = false;
97        for (_, n) in groups.by_ref().take(integral) {
98            if started {
99                write!(f, "{n:09}")?;
100            } else if n != 0 {
101                write!(f, "{n}")?;
102                started = true;
103            }
104        }
105        if !started {
106            f.write_str("0")?;
107        }
108        if self.scale != 0 {
109            f.write_str(".")?;
110            for (digits, n) in groups {
111                write!(f, "{n:0digits$}")?;
112            }
113        }
114        Ok(())
115    }
116}
117
118pub(super) fn decimal_group_size(digits: usize) -> usize {
119    const SIZES: [usize; 10] = [0, 1, 1, 2, 2, 3, 3, 4, 4, 4];
120    SIZES[digits]
121}
122
123/// Protocol values, independent from a table whitelist or CDC primary key.
124#[derive(Debug, Clone, Copy, PartialEq)]
125#[non_exhaustive]
126pub enum RowValue<'a> {
127    Null,
128    Integer(IntegerValue<'a>),
129    Float(f32),
130    Double(f64),
131    Decimal(DecimalValue<'a>),
132    /// CHAR/VARCHAR and BLOB bytes, without guessing a character set.
133    Bytes(&'a [u8]),
134    Bit(u64),
135    Enum(u16),
136    Set(u64),
137    Year(u16),
138    /// Temporal, JSON, geometry and vector bytes, without semantic conversion.
139    /// Consult the column definition for the type and encoding metadata.
140    Encoded(&'a [u8]),
141}