aboutsummaryrefslogtreecommitdiff
path: root/rust/src/lib.rs
blob: 88b999decd6557f96118882a0a15cd7f5b989e9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use std::collections::HashMap;
use std::vec::Vec;
use std::io::{Write,Read};
use std::num::FpCategory;
use std::sync::LazyLock;

pub enum Value {
    Integer(i64),
    ByteString(Vec<u8>),
    Boolean(bool),
    List(Vec<Value>),
    Dictionary(HashMap<String, Value>),
    Float(f64),
    Nothing,
}

static FLOAT_DIVISOR: LazyLock<f64> = LazyLock::new(|| (256_f64).ln());

fn write_packed_int( x: i64 ) -> Vec<u8>
{
    let mut w = Vec::<u8>::with_capacity(10);
    let mut v = x;
    let mut bb = if x < 0 {
        v = -v;
        0x40_u8
    } else {
        0x00_u8 
    } | (v&0x3F) as u8 | if v > (v & 0x3F) { 0x80_u8 } else { 0x00_u8 };
    w.push(bb);
    v = v >> 6;
    while v > 0 {
        bb = (v & 0x7F) as u8 | if v > (v & 0x7F) { 0x80_u8 } else { 0x00_u8 };
        w.push(bb);
        v = v >> 7;
    }

    w
}

fn read_packed_int<R: Read>( r: &mut R ) -> Result<i64, std::io::Error> {
    let mut out : i64;
    let mut bb = [0u8];
    r.read( &mut bb )?;
    let negative = (bb[0]&0x40_u8) == 0x40_u8;
    out = (bb[0]&0x3F_u8) as i64;
    let mut c = 0;
    while (bb[0]&0x80_u8) != 0 {
        r.read( &mut bb )?;
        out |= ((bb[0]&0x7F_u8) as i64) << (6+7*c);
        c += 1;
    }

    if negative {
        Ok(-out)
    } else {
        Ok(out)
    }
}

impl Value {
    pub fn write<W: Write>(&self, w: &mut W) -> Result<(), std::io::Error> {
        match self {
            Self::Integer(x) => {
                let bb = ['i' as u8];
                w.write_all(&bb)?;
                w.write_all(&write_packed_int( *x ))?;
            },
            Self::ByteString(s) => {
                let bb = ['s' as u8];
                w.write_all(&bb)?;
                w.write_all(&write_packed_int( s.len() as i64 ))?;
                w.write_all( &s )?;
            },
            Self::Boolean(b) => {
                let mut bb = [0u8];
                bb[0] = if *b { '1' } else { '0' } as u8;
                w.write_all( &bb )?;
            },
            Self::List(l) => {
                let mut bb = ['l' as u8];
                w.write_all(&bb)?;
                for v in l {
                    v.write( w )?;
                }
                bb[0] = 'e' as u8;
                w.write_all(&bb)?;
            },
            Self::Dictionary(d) => {
                let mut bb = ['d' as u8];
                w.write_all(&bb)?;
                for (k, v) in d {
                    (Value::ByteString( k.clone().into_bytes() )).write( w )?;
                    v.write( w )?;
                }
                bb[0] = 'e' as u8;
                w.write_all(&bb)?;
            },
            Self::Float(f) => {
                match f.classify() {
                    FpCategory::Nan => {
                        let mut bb = ['F' as u8, 0u8];
                        bb[1] = if f.is_sign_negative() { 'N' } else { 'n' } as u8;
                        w.write_all( &bb )?;
                    },
                    FpCategory::Infinite => {
                        let mut bb = ['F' as u8, 0u8];
                        bb[1] = if f.is_sign_negative() { 'I' } else { 'i' } as u8;
                        w.write_all( &bb )?;
                    },
                    FpCategory::Zero => {
                        let mut bb = ['F' as u8, 0u8];
                        bb[1] = if f.is_sign_negative() { 'Z' } else { 'z' } as u8;
                        w.write_all( &bb )?;
                    },
                    FpCategory::Subnormal => {
                        let mut bb = ['F' as u8, 0u8];
                        // The format doesn't account for these...uh...make them zero?
                        bb[1] = if f.is_sign_negative() { 'Z' } else { 'z' } as u8;
                        w.write_all( &bb )?;
                    },
                    FpCategory::Normal => {
                        let bb = ['f' as u8];
                        w.write_all( &bb )?;
                        let mut bin = Vec::<u8>::with_capacity(10);
                        let (negative, d) = if f.is_sign_negative() { (true, -*f) } else { (false, *f) };
                        let scale : i64 = (d.ln() / *FLOAT_DIVISOR) as i64;
                        let scale = if scale < 0 { -1 } else { scale };
                        let mut d = d / 256.0_f64.powf( scale as f64 );
                        bin.push( d as u8 );
                        d = d.fract();
                        for _ in 0..15 {
                            d = d*256.0;
                            bin.push( d as u8 );
                            d = d.fract();
                            if d == 0.0 {
                                break;
                            }
                        }
                        if negative {
                            w.write_all( &write_packed_int( -(bin.len() as i64) ) )?;
                        } else {
                            w.write_all( &write_packed_int( bin.len() as i64 ) )?;
                        }
                        w.write_all( &bin )?;
                        w.write_all( &write_packed_int( scale ) )?;
                    },
                }
            },
            Self::Nothing => {
                let bb = ['n' as u8];
                w.write_all( &bb )?;
            },
        }
        Ok(())
    }

    pub fn write_packet<W: Write>( &self, w: &mut W ) -> Result<(), std::io::Error> {
        let mut body : Vec<u8> = vec![1u8,0u8,0u8,0u8,0u8];
        self.write( &mut body )?;
        let len = body.len() as u32;
        body[1..5].copy_from_slice( &len.to_be_bytes() );
        w.write_all( &body )
    }


}

#[cfg(test)]
mod tests {
    use super::*;
    use core::error::Error;
    use std::fs::File;
    use std::io::prelude::*;

    #[test]
    fn write_file1() -> Result<(),Box<dyn Error>> {
        let mut f = File::create("test.gats")?;
        let v = Value::Dictionary(HashMap::from([
            ("biggerint".to_string(), Value::Integer(98765)),
            ("negint".to_string(), Value::Integer(-98765)),
            ("integer".to_string(), Value::Integer(44)),
            ("boolean".to_string(), Value::Boolean(true)),
            ("list".to_string(), Value::List(vec![
                Value::Integer(1), Value::Integer(1), Value::Integer(2),
                Value::Integer(3), Value::Integer(5), Value::Integer(8),
            ])),
            ("null".to_string(), Value::Nothing),
            ("float".to_string(), Value::Float(123.456)),
        ]));
        v.write_packet( &mut f );
        Ok(())
    }
}