firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
//! Bytes as a hex dump, the text the value popup shows them in and the external editor edits them
//! in: lines of bytes in hexadecimal, each after the offset of its first byte.

use crate::errors::{HexDumpProblem, InvalidHexDump};
use std::str::FromStr;

/// The columns of the offset that starts each line.
pub const HEX_OFFSET_WIDTH: usize = 8;

/// What the dump writes between the offset of a line and its bytes. Only the dump writes it there,
/// so it tells an offset from eight digits of bytes when the dump is read back.
const HEX_OFFSET_SEPARATOR: &str = "  ";

/// The most bytes a line holds, when there is room for them.
pub const HEX_BYTES_PER_LINE: usize = 16;

/// `bytes` in hexadecimal, `per_line` to a line, each line after the offset of its first byte.
pub fn hex_lines(bytes: &[u8], per_line: usize) -> Vec<String> {
    bytes
        .chunks(per_line)
        .enumerate()
        .map(|(line, chunk)| {
            let hex: Vec<String> = chunk.iter().map(|byte| format!("{byte:02x}")).collect();
            format!(
                "{:0width$x}{HEX_OFFSET_SEPARATOR}{}",
                line * per_line,
                hex.join(" "),
                width = HEX_OFFSET_WIDTH
            )
        })
        .collect()
}

/// The bytes of a hex dump, read back: a line may start with its offset, which is left out, and so
/// is whitespace, so that bytes can be added, removed and moved between lines. What remains of a
/// line is two hexadecimal digits a byte.
pub struct HexDump(Vec<u8>);

impl HexDump {
    pub fn into_value(self) -> Vec<u8> {
        self.0
    }
}

impl FromStr for HexDump {
    type Err = InvalidHexDump;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let mut bytes = Vec::new();
        for (index, line) in text.lines().enumerate() {
            let mut digits = Vec::new();
            for character in without_offset(line).chars() {
                if character.is_whitespace() {
                    continue;
                }
                let Some(digit) = character.to_digit(16) else {
                    return Err(InvalidHexDump {
                        line: index + 1,
                        problem: HexDumpProblem::NotHexDigit(character),
                    });
                };
                digits.push(u8::try_from(digit).expect("a hexadecimal digit is below 16"));
            }
            if digits.len() % 2 != 0 {
                return Err(InvalidHexDump {
                    line: index + 1,
                    problem: HexDumpProblem::OddDigits,
                });
            }
            bytes.extend(digits.chunks(2).map(|pair| pair[0] << 4 | pair[1]));
        }
        Ok(Self(bytes))
    }
}

fn without_offset(line: &str) -> &str {
    let line = line.trim_start();
    match line.split_at_checked(HEX_OFFSET_WIDTH) {
        Some((offset, bytes))
            if offset.chars().all(|digit| digit.is_ascii_hexdigit())
                && bytes.starts_with(HEX_OFFSET_SEPARATOR) =>
        {
            bytes
        }
        _ => line,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_hex_dump_reads_back_without_its_offsets_and_whitespace_and_an_error_names_its_line() {
        let edited = "00000000  01 02 03\n0405 06\n\n00000010  ff\n";

        let read = edited.parse::<HexDump>().map(HexDump::into_value);
        let odd = "00000000  01 02\n00000002  0\n".parse::<HexDump>();
        let not_hex = "01 0x".parse::<HexDump>();

        assert_eq!(read.ok(), Some(vec![1, 2, 3, 4, 5, 6, 255]));
        assert!(matches!(
            odd,
            Err(InvalidHexDump {
                line: 2,
                problem: HexDumpProblem::OddDigits
            })
        ));
        assert!(matches!(
            not_hex,
            Err(InvalidHexDump {
                line: 1,
                problem: HexDumpProblem::NotHexDigit('x')
            })
        ));
    }

    #[test]
    fn eight_digits_not_followed_by_the_two_spaces_of_an_offset_are_bytes() {
        let packed = "deadbeef\n".parse::<HexDump>().map(HexDump::into_value);
        let grouped = "01020304 05\n".parse::<HexDump>().map(HexDump::into_value);

        assert_eq!(packed.ok(), Some(vec![0xde, 0xad, 0xbe, 0xef]));
        assert_eq!(grouped.ok(), Some(vec![1, 2, 3, 4, 5]));
    }
}