Skip to main content

rs_ints2tinydict/
lib.rs

1use std::collections::BTreeMap;
2use std::io;
3
4use io::Write;
5
6pub fn new_item_found(
7    item: i32,
8    dict: &mut BTreeMap<u8, i32>,
9    buf: &mut BTreeMap<i32, u8>,
10) -> Result<u8, io::Error> {
11    let sz: usize = dict.len();
12
13    let szu8: u8 = sz as u8;
14    let onext_id: Option<_> = szu8.checked_add(1);
15
16    let Some(next_id) = onext_id else {
17        return Err(io::Error::other("too many unique ints"));
18    };
19
20    dict.insert(next_id, item);
21    buf.insert(item, next_id);
22
23    Ok(next_id)
24}
25
26pub fn ints2dict2writer<I, W>(
27    ints: I,
28    mut wtr: W,
29    buf: &mut BTreeMap<i32, u8>,
30) -> Result<BTreeMap<u8, i32>, io::Error>
31where
32    I: Iterator<Item = Result<i32, io::Error>>,
33    W: FnMut(u8) -> Result<(), io::Error>,
34{
35    buf.clear();
36
37    let mut ret: BTreeMap<u8, i32> = BTreeMap::default();
38
39    for rint in ints {
40        let ival: i32 = rint?;
41        let omapd_id: Option<&u8> = buf.get(&ival);
42
43        let Some(mapd_id) = omapd_id else {
44            let mapd_id: u8 = new_item_found(ival, &mut ret, buf)?;
45            wtr(mapd_id)?;
46            continue;
47        };
48
49        // the item is already registered
50        wtr(*mapd_id)?;
51    }
52
53    Ok(ret)
54}
55
56pub trait DictWriter {
57    fn write(&mut self, dict: &BTreeMap<u8, i32>) -> Result<(), io::Error>;
58}
59
60impl<F> DictWriter for F
61where
62    F: FnMut(&BTreeMap<u8, i32>) -> Result<(), io::Error>,
63{
64    fn write(&mut self, dict: &BTreeMap<u8, i32>) -> Result<(), io::Error> {
65        self(dict)
66    }
67}
68
69#[derive(Debug, Clone, Copy)]
70pub enum Endian {
71    Lit,
72    Big,
73}
74
75impl std::str::FromStr for Endian {
76    type Err = io::Error;
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        match s {
79            "little" => Ok(Self::Lit),
80            "lit" => Ok(Self::Lit),
81            "Lit" => Ok(Self::Lit),
82            "Little" => Ok(Self::Lit),
83            "l" => Ok(Self::Lit),
84            "big" => Ok(Self::Big),
85            "Big" => Ok(Self::Big),
86            "b" => Ok(Self::Big),
87            _ => Err(io::Error::other("invalid endian string")),
88        }
89    }
90}
91
92impl Endian {
93    pub fn to_int2bytes(&self) -> impl Fn(i32) -> [u8; 4] {
94        match self {
95            Self::Lit => |i: i32| i.to_le_bytes(),
96            Self::Big => |i: i32| i.to_be_bytes(),
97        }
98    }
99}
100
101impl Endian {
102    pub fn wtr2dict_wtr<W>(&self, mut wtr: W) -> impl DictWriter
103    where
104        W: Write,
105    {
106        let i2b = self.to_int2bytes();
107        move |dict: &BTreeMap<u8, i32>| {
108            for (key, val) in dict.iter() {
109                let bkey: u8 = *key;
110                let bval: [u8; 4] = i2b(*val);
111                wtr.write_all(&[bkey])?;
112                wtr.write_all(&bval)?;
113            }
114            wtr.flush()
115        }
116    }
117}
118
119pub trait StrToInt {
120    fn parse(&self, s: &str) -> Result<i32, io::Error>;
121
122    fn lines2ints<I>(&self, lines: I) -> impl Iterator<Item = Result<i32, io::Error>>
123    where
124        I: Iterator<Item = Result<String, io::Error>>,
125    {
126        lines.map(|rline| rline.and_then(|line| self.parse(&line)))
127    }
128}
129
130impl<F> StrToInt for F
131where
132    F: Fn(&str) -> Result<i32, io::Error>,
133{
134    fn parse(&self, s: &str) -> Result<i32, io::Error> {
135        self(s)
136    }
137}
138
139pub fn str2int_std(s: &str) -> Result<i32, io::Error> {
140    str::parse(s).map_err(io::Error::other)
141}
142
143pub fn str2int_default() -> impl StrToInt {
144    str2int_std
145}
146
147pub trait MapdIntWriter {
148    fn write(&mut self, mapd: u8) -> Result<(), io::Error>;
149}
150
151impl<F> MapdIntWriter for F
152where
153    F: FnMut(u8) -> Result<(), io::Error>,
154{
155    fn write(&mut self, mapd: u8) -> Result<(), io::Error> {
156        self(mapd)
157    }
158}
159
160pub fn wtr2fn<W>(mut wtr: W) -> impl FnMut(u8) -> Result<(), io::Error>
161where
162    W: MapdIntWriter,
163{
164    move |u: u8| wtr.write(u)
165}
166
167pub fn iowtr2wtr<W>(mut wtr: W) -> impl MapdIntWriter
168where
169    W: Write,
170{
171    move |mapd: u8| wtr.write_all(&[mapd])
172}