Skip to main content

mysql_common/misc/
mod.rs

1// Copyright (c) 2017 Anatoly Ikorsky
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use std::io::{self};
10
11use crate::io::ParseBuf;
12
13pub mod raw;
14
15/// Returns length of length-encoded-integer representation of `x`.
16pub fn lenenc_int_len(x: u64) -> u64 {
17    if x < 251 {
18        1
19    } else if x < 65_536 {
20        3
21    } else if x < 16_777_216 {
22        4
23    } else {
24        9
25    }
26}
27
28/// Returns length of lenght-encoded-string representation of `s`.
29pub fn lenenc_str_len(s: &[u8]) -> u64 {
30    let len = s.len() as u64;
31    lenenc_int_len(len) + len
32}
33
34// ---------------------------------------------------------------------------
35// Variable-length integer encoding (MySQL serialization library format)
36// ---------------------------------------------------------------------------
37
38/// Reads a variable-length unsigned integer from the MySQL serialization format.
39///
40/// # Encoding
41///
42/// Bytes are stored in little-endian order. The least-significant byte's
43/// trailing 1-bits encode the total byte count: `count = trailing_ones + 1`.
44///
45/// For 1–8 bytes, the encoded value is: `le_uint >> (trailing_ones + 1)`.
46/// For 9 bytes (first byte = `0xFF`), the remaining 8 bytes are the raw value.
47///
48/// # Reference
49///
50/// <https://dev.mysql.com/doc/dev/mysql-server/latest/PageLibsMysqlSerialization.html>
51pub fn read_varlen_uint(buf: &mut ParseBuf<'_>) -> io::Result<u64> {
52    if buf.is_empty() {
53        return Err(io::Error::new(
54            io::ErrorKind::UnexpectedEof,
55            "unexpected end of buffer reading varlen uint",
56        ));
57    }
58
59    let first_byte = buf.0[0];
60    let trailing_ones = first_byte.trailing_ones() as usize;
61
62    if trailing_ones == 8 {
63        // Special case: 0xFF → 9 bytes total, remaining 8 bytes are the raw u64
64        if buf.len() < 9 {
65            return Err(io::Error::new(
66                io::ErrorKind::UnexpectedEof,
67                "unexpected end of buffer reading 9-byte varlen uint",
68            ));
69        }
70        buf.0 = &buf.0[1..]; // skip 0xFF marker
71        let mut bytes = [0u8; 8];
72        bytes.copy_from_slice(&buf.0[..8]);
73        buf.0 = &buf.0[8..];
74        return Ok(u64::from_le_bytes(bytes));
75    }
76
77    let num_bytes = trailing_ones + 1;
78    if buf.len() < num_bytes {
79        return Err(io::Error::new(
80            io::ErrorKind::UnexpectedEof,
81            "unexpected end of buffer reading varlen uint",
82        ));
83    }
84
85    let mut raw = [0u8; 8];
86    raw[..num_bytes].copy_from_slice(&buf.0[..num_bytes]);
87    buf.0 = &buf.0[num_bytes..];
88
89    let le_val = u64::from_le_bytes(raw);
90    Ok(le_val >> num_bytes)
91}
92
93/// Writes a variable-length unsigned integer in the MySQL serialization format.
94///
95/// # Reference
96///
97/// <https://dev.mysql.com/doc/dev/mysql-server/latest/PageLibsMysqlSerialization.html>
98pub fn write_varlen_uint(buf: &mut Vec<u8>, value: u64) {
99    let num_bytes = varlen_uint_size(value);
100
101    if num_bytes == 9 {
102        // Special case: 0xFF marker followed by raw 8-byte LE value
103        buf.push(0xFF);
104        buf.extend_from_slice(&value.to_le_bytes());
105        return;
106    }
107
108    // Shift value left by num_bytes to make room for trailing ones + terminator
109    let shifted = value << num_bytes;
110
111    // Set trailing ones: the lowest (num_bytes - 1) bits are 1, bit (num_bytes - 1) is 0
112    let trailer = (1u64 << (num_bytes - 1)) - 1;
113    let encoded = shifted | trailer;
114
115    buf.extend_from_slice(&encoded.to_le_bytes()[..num_bytes]);
116}
117
118/// Returns the number of bytes needed to varlen-encode the given unsigned value.
119///
120/// Mirrors `get_size_integer_varlen_unsigned()` from MySQL:
121/// <https://github.com/mysql/mysql-server/blob/trunk/libs/mysql/serialization/variable_length_integers.h>
122pub fn varlen_uint_size(value: u64) -> usize {
123    let data_bits = if value == 0 {
124        0
125    } else {
126        64 - value.leading_zeros() as usize
127    };
128    match data_bits {
129        0..=7 => 1,
130        8..=14 => 2,
131        15..=21 => 3,
132        22..=28 => 4,
133        29..=35 => 5,
134        36..=42 => 6,
135        43..=49 => 7,
136        50..=56 => 8,
137        _ => 9,
138    }
139}
140
141pub(crate) fn unexpected_buf_eof() -> io::Error {
142    io::Error::new(
143        io::ErrorKind::UnexpectedEof,
144        "can't parse: buf doesn't have enough data",
145    )
146}
147
148/// Splits server 'version' string into three numeric pieces.
149///
150/// It'll return `(0, 0, 0)` in case of error.
151pub fn split_version<T: AsRef<[u8]>>(version_str: T) -> (u8, u8, u8) {
152    let bytes = version_str.as_ref();
153    split_version_inner(bytes).unwrap_or((0, 0, 0))
154}
155
156// Split into its own function for two reasons:
157// 1. Generic function will be instantiated for every type, increasing code size
158// 2. It allows using Option and ? operator without breaking public API
159fn split_version_inner(input: &[u8]) -> Option<(u8, u8, u8)> {
160    let mut nums = [0_u8; 3];
161    let mut iter = input.split(|c| *c == b'.');
162    for (i, chunk) in (&mut iter).take(2).enumerate() {
163        nums[i] = btoi::btoi(chunk).ok()?;
164    }
165    // allow junk at the end of the final part of the version
166    let chunk_with_junk = iter.next()?;
167    let end_of_digits = chunk_with_junk.iter().position(|c| *c < b'0' || *c > b'9');
168    let chunk = match end_of_digits {
169        Some(pos) => &chunk_with_junk[..pos],
170        None => chunk_with_junk,
171    };
172    nums[2] = btoi::btoi(chunk).ok()?;
173
174    Some((nums[0], nums[1], nums[2]))
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn should_split_version() {
183        assert_eq!((1, 2, 3), split_version("1.2.3"));
184        assert_eq!((10, 20, 30), split_version("10.20.30foo"));
185        assert_eq!((0, 0, 0), split_version("100.200.300foo"));
186        assert_eq!((0, 0, 0), split_version("100.200foo"));
187        assert_eq!((0, 0, 0), split_version("1,2.3"));
188        assert_eq!((0, 0, 0), split_version("1"));
189        assert_eq!((0, 0, 0), split_version("1.2"));
190    }
191}