rs-ints2tinydict 0.1.0

Map i32 sequences to unique u8 identifiers
Documentation
use std::collections::BTreeMap;
use std::io;

use io::Write;

pub fn new_item_found(
    item: i32,
    dict: &mut BTreeMap<u8, i32>,
    buf: &mut BTreeMap<i32, u8>,
) -> Result<u8, io::Error> {
    let sz: usize = dict.len();

    let szu8: u8 = sz as u8;
    let onext_id: Option<_> = szu8.checked_add(1);

    let Some(next_id) = onext_id else {
        return Err(io::Error::other("too many unique ints"));
    };

    dict.insert(next_id, item);
    buf.insert(item, next_id);

    Ok(next_id)
}

pub fn ints2dict2writer<I, W>(
    ints: I,
    mut wtr: W,
    buf: &mut BTreeMap<i32, u8>,
) -> Result<BTreeMap<u8, i32>, io::Error>
where
    I: Iterator<Item = Result<i32, io::Error>>,
    W: FnMut(u8) -> Result<(), io::Error>,
{
    buf.clear();

    let mut ret: BTreeMap<u8, i32> = BTreeMap::default();

    for rint in ints {
        let ival: i32 = rint?;
        let omapd_id: Option<&u8> = buf.get(&ival);

        let Some(mapd_id) = omapd_id else {
            let mapd_id: u8 = new_item_found(ival, &mut ret, buf)?;
            wtr(mapd_id)?;
            continue;
        };

        // the item is already registered
        wtr(*mapd_id)?;
    }

    Ok(ret)
}

pub trait DictWriter {
    fn write(&mut self, dict: &BTreeMap<u8, i32>) -> Result<(), io::Error>;
}

impl<F> DictWriter for F
where
    F: FnMut(&BTreeMap<u8, i32>) -> Result<(), io::Error>,
{
    fn write(&mut self, dict: &BTreeMap<u8, i32>) -> Result<(), io::Error> {
        self(dict)
    }
}

#[derive(Debug, Clone, Copy)]
pub enum Endian {
    Lit,
    Big,
}

impl std::str::FromStr for Endian {
    type Err = io::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "little" => Ok(Self::Lit),
            "lit" => Ok(Self::Lit),
            "Lit" => Ok(Self::Lit),
            "Little" => Ok(Self::Lit),
            "l" => Ok(Self::Lit),
            "big" => Ok(Self::Big),
            "Big" => Ok(Self::Big),
            "b" => Ok(Self::Big),
            _ => Err(io::Error::other("invalid endian string")),
        }
    }
}

impl Endian {
    pub fn to_int2bytes(&self) -> impl Fn(i32) -> [u8; 4] {
        match self {
            Self::Lit => |i: i32| i.to_le_bytes(),
            Self::Big => |i: i32| i.to_be_bytes(),
        }
    }
}

impl Endian {
    pub fn wtr2dict_wtr<W>(&self, mut wtr: W) -> impl DictWriter
    where
        W: Write,
    {
        let i2b = self.to_int2bytes();
        move |dict: &BTreeMap<u8, i32>| {
            for (key, val) in dict.iter() {
                let bkey: u8 = *key;
                let bval: [u8; 4] = i2b(*val);
                wtr.write_all(&[bkey])?;
                wtr.write_all(&bval)?;
            }
            wtr.flush()
        }
    }
}

pub trait StrToInt {
    fn parse(&self, s: &str) -> Result<i32, io::Error>;

    fn lines2ints<I>(&self, lines: I) -> impl Iterator<Item = Result<i32, io::Error>>
    where
        I: Iterator<Item = Result<String, io::Error>>,
    {
        lines.map(|rline| rline.and_then(|line| self.parse(&line)))
    }
}

impl<F> StrToInt for F
where
    F: Fn(&str) -> Result<i32, io::Error>,
{
    fn parse(&self, s: &str) -> Result<i32, io::Error> {
        self(s)
    }
}

pub fn str2int_std(s: &str) -> Result<i32, io::Error> {
    str::parse(s).map_err(io::Error::other)
}

pub fn str2int_default() -> impl StrToInt {
    str2int_std
}

pub trait MapdIntWriter {
    fn write(&mut self, mapd: u8) -> Result<(), io::Error>;
}

impl<F> MapdIntWriter for F
where
    F: FnMut(u8) -> Result<(), io::Error>,
{
    fn write(&mut self, mapd: u8) -> Result<(), io::Error> {
        self(mapd)
    }
}

pub fn wtr2fn<W>(mut wtr: W) -> impl FnMut(u8) -> Result<(), io::Error>
where
    W: MapdIntWriter,
{
    move |u: u8| wtr.write(u)
}

pub fn iowtr2wtr<W>(mut wtr: W) -> impl MapdIntWriter
where
    W: Write,
{
    move |mapd: u8| wtr.write_all(&[mapd])
}