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

Code before:
            }
            PgCube::OneDimensionInterval(x, y) => {
                buff.extend_from_slice(&[0, 0, 0, 1]);
                buff.extend_from_slice(&x.to_be_bytes());
                buff.extend_from_slice(&y.to_be_bytes());
            }
            PgCube::MultiDimension(multi_values) => {
                let dimension = multi_values
                    .first()
                    .map(|arr| arr.len() as u8)
                    .unwrap_or(1 as u8);
                buff.extend_from_slice(&[0, 0, 0]);
                buff.extend_from_slice(&dimension.to_be_bytes());
                let bytes = multi_values
                    .into_iter()
                    .flat_map(|inner| inner)
                    .flat_map(|v| v.to_be_bytes())
                    .collect::<Vec<u8>>();
                buff.extend_from_slice(&bytes);
            }
        };
        buff
    }

    fn get_f64_from_bytes(bytes: &[u8], start: usize) -> Result<f64, Error> {
        bytes[start..start + BYTE_WIDTH]
            .try_into()
            .map(f64::from_be_bytes)
            .map_err(|err| Error::Decode(format!("Invalid bytes slice: {:?}", err).into()))
    }
    // Helper to deserialize a vector of f64 values
    fn deserialize_vector(bytes: &[u8], start_index: usize) -> Result<Vec<f64>, Error> {
        let steps = (bytes.len() - start_index) / BYTE_WIDTH;
        (0..steps)
            .map(|i| Self::get_f64_from_bytes(&bytes, start_index + i * BYTE_WIDTH))
            .collect()
    }

    // Helper to deserialize a matrix of f64 values
    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| {

Review comment (bug):
This will panic if `bytes` is shorter than `start + BYTE_WIDTH` which could be the case if someone decoded the wrong type by mistake.

Everything that does slicing or assumes a certain slice length needs to check this first.

Code after:
            .trim_end_matches(']')
            .replace(' ', "");

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

        if !content.contains("),(") {
            return 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 parse_one_dimensional_interval(point_vecs);
        }

        parse_multidimensional_interval(point_vecs)
    }
}

fn pg_cube_from_bytes(bytes: &[u8]) -> Result<PgCube, Error> {
    let cube_type = bytes
        .first()
        .map(|&byte| byte as usize)
        .ok_or(Error::Decode(
            format!("Could not decode cube bytes: {:?}", bytes).into(),
        ))?;

    let dimensionality = bytes
        .get(DIMENSIONALITY_POSITION)
        .map(|&byte| byte as usize)
        .ok_or(Error::Decode(
            format!("Could not decode cube bytes: {:?}", bytes).into(),
        ))?;

    match (cube_type, dimensionality) {
        (CUBE_TYPE_ZERO_VOLUME, CUBE_DIMENSION_ONE) => {
            let point = get_f64_from_bytes(bytes, 4)?;
            Ok(PgCube::Point(point))
        }
        (CUBE_TYPE_ZERO_VOLUME, _) => {
            Ok(PgCube::ZeroVolume(deserialize_vector(bytes, START_INDEX)?))
        }
        (CUBE_TYPE_DEFAULT, CUBE_DIMENSION_ONE) => {
            let x_start = 4;
            let y_start = x_start + BYTE_WIDTH;
            let x = get_f64_from_bytes(bytes, x_start)?;
            let y = get_f64_from_bytes(bytes, y_start)?;
            Ok(PgCube::OneDimensionInterval(x, y))
        }
        (CUBE_TYPE_DEFAULT, dim) => Ok(PgCube::MultiDimension(deserialize_matrix(