Skip to content

Commit

Permalink
jsonb: Introduce JsonDom type and parsing/conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
blackbeam committed Oct 3, 2024
1 parent 3d6bd8e commit f6dd979
Show file tree
Hide file tree
Showing 6 changed files with 594 additions and 7 deletions.
33 changes: 32 additions & 1 deletion src/binlog/decimal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub const POWERS_10: [i32; DIG_PER_DEC + 1] = [
/// i.e. both `rhs` and `lhs` will be serialized into temporary buffers;
/// * even though MySql's `string2decimal` function allows scientific notation,
/// this implementation denies it.
#[derive(Default, Debug, Eq)]
#[derive(Default, Debug, Eq, Clone)]
pub struct Decimal {
/// The number of *decimal* digits (NOT number of `Digit`s!) before the point.
intg: usize,
Expand All @@ -75,13 +75,23 @@ impl Decimal {
decimal_bin_size(self.intg + self.frac, self.frac)
}

/// See [`Decimal::parse_str_bytes`].
#[deprecated = "use parse_str_bytes"]
pub fn parse_bytes(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
match std::str::from_utf8(bytes) {
Ok(string) => Decimal::from_str(string),
Err(_) => Err(ParseDecimalError),
}
}

/// Runs `Decimal::from_str` on the given bytes. Errors if not UTF-8 or not a decimal string.
pub fn parse_str_bytes(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
match std::str::from_utf8(bytes) {
Ok(string) => Decimal::from_str(string),
Err(_) => Err(ParseDecimalError),
}
}

pub fn write_bin<T: Write>(&self, mut output: T) -> io::Result<()> {
// result bits must be inverted if the sign is negative,
// we'll XOR it with `mask` to achieve this.
Expand Down Expand Up @@ -139,6 +149,27 @@ impl Decimal {
output.write_all(&out_buf)
}

/// Reads packed representation of a [`Decimal`].
///
/// Packed representation is:
///
/// 1. precision (u8)
/// 2. scale (u8)
/// 3. serialized decimal value (see [`Decimal::read_bin`])
pub fn read_packed<T: Read>(mut input: T, keep_precision: bool) -> io::Result<Self> {
let mut precision_and_scale = [0_u8, 0_u8];
input.read_exact(&mut precision_and_scale)?;
Self::read_bin(
input,
precision_and_scale[0] as usize,
precision_and_scale[1] as usize,
keep_precision,
)
}

/// Reads serialized representation of a decimal value.
///
/// The value is usually written in the packed form (see [`Decimal::read_packed`]).
pub fn read_bin<T: Read>(
mut input: T,
precision: usize,
Expand Down
Loading

0 comments on commit f6dd979

Please sign in to comment.