Repository: launchbadge/sqlx
File: sqlx-postgres/src/types/cube.rs (Rust)

Code before:

    fn deserialize_string(input: &str) -> Result<PgCube, Error> {
        let content = &input[1..input.len() - 1];

        if !content.contains('(') && !content.contains(',') {
            return Self::parse_point(content);
        }

        if !content.contains("),(") {
            return Self::parse_zero_volume(content);
        }

        let point_vecs = content.split("),(").collect::<Vec<&str>>();
        if point_vecs.len() == 2 && !point_vecs.iter().any(|pv| pv.contains(',')) {
            return Self::parse_one_dimensional_interval(point_vecs);
        }

        Self::parse_multidimensional_interval(point_vecs)
    }

    fn remove_parentheses(s: &str) -> String {
        s.trim_matches(|c| c == '(' || c == ')').to_string()
    }

    fn deserialize_bytes(bytes: &[u8]) -> Result<Self, Error> {
        let cube_type = bytes[0] as usize;
        let dimensionality = bytes[3] as usize;
        let start_index = 4;

        match (cube_type, dimensionality) {
            (128, 1) => {
                let point = Self::get_f64_from_bytes(&bytes, 4)?;
                Ok(PgCube::Point(point))
            }
            (128, _) => Ok(PgCube::ZeroVolume(Self::deserialize_vector(
                &bytes,
                start_index,
            )?)),
            (0, 1) => {
                let x_start = 4; // 16 bytes per dimension (2 coordinates)
                let y_start = x_start + BYTE_WIDTH; // Upper right follows lower left
                let x = Self::get_f64_from_bytes(&bytes, x_start)?;
                let y = Self::get_f64_from_bytes(&bytes, y_start)?;
                Ok(PgCube::OneDimensionInterval(x, y))
            }
            (0, dim) => Ok(PgCube::MultiDimension(Self::deserialize_matrix(
                &bytes,
                start_index,
                dim,
            )?)),
            (flag, dimension) => Err(Error::Decode(

Review comment (suggestion):
Again, anything using the `[]` operator will panic if the index is out of bounds. This needs to be carefully checked to avoid surprising panics (e.g. https://github.com/launchbadge/sqlx/issues/2691).

Code after:
}

fn get_f64_from_bytes(bytes: &[u8], start: usize) -> Result<f64, Error> {
    bytes
        .get(start..start + BYTE_WIDTH)
        .ok_or(Error::Decode(
            format!("Could not decode cube bytes: {:?}", bytes).into(),
        ))?
        .try_into()
        .map(f64::from_be_bytes)
        .map_err(|err| Error::Decode(format!("Invalid bytes slice: {:?}", err).into()))
}

fn deserialize_vector(bytes: &[u8], start_index: usize) -> Result<Vec<f64>, Error> {
    let steps = (bytes.len() - start_index) / BYTE_WIDTH;
    (0..steps)
        .map(|i| get_f64_from_bytes(bytes, start_index + i * BYTE_WIDTH))
        .collect()
}

fn deserialize_matrix(
    bytes: &[u8],
    start_index: usize,
    dim: usize,
) -> Result<Vec<Vec<f64>>, Error> {
    let step = BYTE_WIDTH * dim;
    let steps = (bytes.len() - start_index) / step;

    (0..steps)
        .map(|step_idx| {
            (0..dim)
                .map(|dim_idx| {
                    get_f64_from_bytes(bytes, start_index + step_idx * step + dim_idx * BYTE_WIDTH)
                })
                .collect()
        })
        .collect()
}

fn parse_float_from_str(s: &str, error_msg: &str) -> Result<f64, Error> {
    s.parse().map_err(|_| Error::Decode(error_msg.into()))
}

fn parse_point(str: &str) -> Result<PgCube, Error> {
    Ok(PgCube::Point(parse_float_from_str(
        str,
        "Failed to parse point",
    )?))
}

fn parse_zero_volume(content: &str) -> Result<PgCube, Error> {