summaryrefslogtreecommitdiff
path: root/crates/windlass/src/encoding.rs
blob: 0950956aac84b4bd4a834feb87eebff3d8d55b6a (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::fmt::Display;

use crate::messages::MessageSkipperError;

/// Message decoding error
#[derive(thiserror::Error, Debug, Clone)]
pub enum MessageDecodeError {
    /// More data was expected but none is available
    #[error("eof unexpected")]
    UnexpectedEof,
    /// A received string could not be decoded as UTF8
    #[error("invalid utf8 string")]
    Utf8Error(#[from] std::str::Utf8Error),
}

pub(crate) fn encode_vlq_int(output: &mut Vec<u8>, v: u32) {
    let sv = v as i32;
    if !(-(1 << 26)..(3 << 26)).contains(&sv) {
        output.push(((sv >> 28) & 0x7F) as u8 | 0x80);
    }
    if !(-(1 << 19)..(3 << 19)).contains(&sv) {
        output.push(((sv >> 21) & 0x7F) as u8 | 0x80);
    }
    if !(-(1 << 12)..(3 << 12)).contains(&sv) {
        output.push(((sv >> 14) & 0x7F) as u8 | 0x80);
    }
    if !(-(1 << 5)..(3 << 5)).contains(&sv) {
        output.push(((sv >> 7) & 0x7F) as u8 | 0x80);
    }
    output.push((sv & 0x7F) as u8);
}

pub(crate) fn next_byte(data: &mut &[u8]) -> Result<u8, MessageDecodeError> {
    if data.is_empty() {
        Err(MessageDecodeError::UnexpectedEof)
    } else {
        let v = data[0];
        *data = &data[1..];
        Ok(v)
    }
}

pub(crate) fn parse_vlq_int(data: &mut &[u8]) -> Result<u32, MessageDecodeError> {
    let mut c = next_byte(data)? as u32;
    let mut v = c & 0x7F;
    if (c & 0x60) == 0x60 {
        v |= (-0x20i32) as u32;
    }
    while c & 0x80 != 0 {
        c = next_byte(data)? as u32;
        v = (v << 7) | (c & 0x7F);
    }

    Ok(v)
}

pub trait Readable<'de>: Sized {
    fn read(data: &mut &'de [u8]) -> Result<Self, MessageDecodeError>;

    fn skip(data: &mut &[u8]) -> Result<(), MessageDecodeError>;
}

pub trait Writable: Sized {
    fn write(&self, output: &mut Vec<u8>);
}

pub trait Borrowable: Sized {
    type Borrowed<'a>
    where
        Self: 'a;
    fn from_borrowed(src: Self::Borrowed<'_>) -> Self;
}

pub trait ToFieldType: Sized {
    fn as_field_type() -> FieldType;
}

macro_rules! int_readwrite {
    ( $type:tt, $field_type:expr ) => {
        impl Readable<'_> for $type {
            fn read(data: &mut &[u8]) -> Result<Self, MessageDecodeError> {
                parse_vlq_int(data).map(|v| v as $type)
            }

            fn skip(data: &mut &[u8]) -> Result<(), MessageDecodeError> {
                parse_vlq_int(data).map(|_| ())
            }
        }

        impl Writable for $type {
            fn write(&self, output: &mut Vec<u8>) {
                encode_vlq_int(output, *self as u32)
            }
        }

        impl Borrowable for $type {
            type Borrowed<'a> = Self;
            fn from_borrowed(src: Self::Borrowed<'_>) -> Self {
                src
            }
        }

        impl ToFieldType for $type {
            fn as_field_type() -> FieldType {
                $field_type
            }
        }
    };
}

int_readwrite!(u32, FieldType::U32);
int_readwrite!(i32, FieldType::I32);
int_readwrite!(u16, FieldType::U16);
int_readwrite!(i16, FieldType::I16);
int_readwrite!(u8, FieldType::U8);

impl Readable<'_> for bool {
    fn read(data: &mut &[u8]) -> Result<Self, MessageDecodeError> {
        parse_vlq_int(data).map(|v| v != 0)
    }

    fn skip(data: &mut &[u8]) -> Result<(), MessageDecodeError> {
        parse_vlq_int(data).map(|_| ())
    }
}

impl Writable for bool {
    fn write(&self, output: &mut Vec<u8>) {
        encode_vlq_int(output, u32::from(*self))
    }
}

impl Borrowable for bool {
    type Borrowed<'a> = Self;
    fn from_borrowed(src: Self::Borrowed<'_>) -> Self {
        src
    }
}

impl ToFieldType for bool {
    fn as_field_type() -> FieldType {
        FieldType::U8
    }
}

impl<'de> Readable<'de> for &'de [u8] {
    fn read(data: &mut &'de [u8]) -> Result<&'de [u8], MessageDecodeError> {
        let len = parse_vlq_int(data)? as usize;
        if data.len() < len {
            Err(MessageDecodeError::UnexpectedEof)
        } else {
            let ret = &data[..len];
            *data = &data[len..];
            Ok(ret)
        }
    }

    fn skip(data: &mut &[u8]) -> Result<(), MessageDecodeError> {
        let len = parse_vlq_int(data)? as usize;
        if data.len() < len {
            Err(MessageDecodeError::UnexpectedEof)
        } else {
            *data = &data[len..];
            Ok(())
        }
    }
}

impl Writable for &[u8] {
    fn write(&self, output: &mut Vec<u8>) {
        encode_vlq_int(output, self.len() as u32);
        output.extend_from_slice(self);
    }
}

impl Borrowable for Vec<u8> {
    type Borrowed<'a> = &'a [u8];
    fn from_borrowed(src: Self::Borrowed<'_>) -> Self {
        src.into()
    }
}

impl ToFieldType for Vec<u8> {
    fn as_field_type() -> FieldType {
        FieldType::ByteArray
    }
}

impl<'de> Readable<'de> for &'de str {
    fn read(data: &mut &'de [u8]) -> Result<&'de str, MessageDecodeError> {
        let len = parse_vlq_int(data)? as usize;
        if data.len() < len {
            Err(MessageDecodeError::UnexpectedEof)
        } else {
            let ret = &data[..len];
            *data = &data[len..];
            Ok(std::str::from_utf8(ret)?)
        }
    }

    fn skip(data: &mut &[u8]) -> Result<(), MessageDecodeError> {
        let len = parse_vlq_int(data)? as usize;
        if data.len() < len {
            Err(MessageDecodeError::UnexpectedEof)
        } else {
            *data = &data[len..];
            Ok(())
        }
    }
}

impl Writable for &str {
    fn write(&self, output: &mut Vec<u8>) {
        let bytes = self.as_bytes();
        encode_vlq_int(output, bytes.len() as u32);
        output.extend_from_slice(bytes);
    }
}

impl Borrowable for String {
    type Borrowed<'a> = &'a str;
    fn from_borrowed(src: Self::Borrowed<'_>) -> Self {
        src.to_string()
    }
}

impl ToFieldType for String {
    fn as_field_type() -> FieldType {
        FieldType::String
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum FieldType {
    U32,
    I32,
    U16,
    I16,
    U8,
    String,
    ByteArray,
}

impl FieldType {
    pub(crate) fn skip(&self, input: &mut &[u8]) -> Result<(), MessageDecodeError> {
        match self {
            Self::U32 => <u32 as Readable>::skip(input),
            Self::I32 => <i32 as Readable>::skip(input),
            Self::U16 => <u16 as Readable>::skip(input),
            Self::I16 => <i16 as Readable>::skip(input),
            Self::U8 => <u8 as Readable>::skip(input),
            Self::String => <&str as Readable>::skip(input),
            Self::ByteArray => <&[u8] as Readable>::skip(input),
        }
    }

    pub(crate) fn read(&self, input: &mut &[u8]) -> Result<FieldValue, MessageDecodeError> {
        Ok(match self {
            Self::U32 => FieldValue::U32(<u32 as Readable>::read(input)?),
            Self::I32 => FieldValue::I32(<i32 as Readable>::read(input)?),
            Self::U16 => FieldValue::U16(<u16 as Readable>::read(input)?),
            Self::I16 => FieldValue::I16(<i16 as Readable>::read(input)?),
            Self::U8 => FieldValue::U8(<u8 as Readable>::read(input)?),
            Self::String => FieldValue::String(<&str as Readable>::read(input)?.into()),
            Self::ByteArray => FieldValue::ByteArray(<&[u8] as Readable>::read(input)?.into()),
        })
    }

    pub(crate) fn from_msg(s: &str) -> Result<Self, MessageSkipperError> {
        match s {
            "%u" => Ok(Self::U32),
            "%i" => Ok(Self::I32),
            "%hu" => Ok(Self::U16),
            "%hi" => Ok(Self::I16),
            "%c" => Ok(Self::U8),
            "%s" => Ok(Self::String),
            "%*s" => Ok(Self::ByteArray),
            "%.*s" => Ok(Self::ByteArray),
            s => Err(MessageSkipperError::InvalidFormatFieldType(s.to_string())),
        }
    }

    pub(crate) fn from_format(s: &str) -> Result<(Self, &str), MessageSkipperError> {
        if let Some(rest) = s.strip_prefix("%u") {
            Ok((Self::U32, rest))
        } else if let Some(rest) = s.strip_prefix("%i") {
            Ok((Self::I32, rest))
        } else if let Some(rest) = s.strip_prefix("%hu") {
            Ok((Self::U16, rest))
        } else if let Some(rest) = s.strip_prefix("%hi") {
            Ok((Self::I16, rest))
        } else if let Some(rest) = s.strip_prefix("%c") {
            Ok((Self::U8, rest))
        } else if let Some(rest) = s.strip_prefix("%.*s") {
            Ok((Self::ByteArray, rest))
        } else if let Some(rest) = s.strip_prefix("%*s") {
            Ok((Self::String, rest))
        } else {
            Err(MessageSkipperError::InvalidFormatFieldType(s.to_string()))
        }
    }
}

#[derive(Debug)]
pub enum FieldValue {
    U32(u32),
    I32(i32),
    U16(u16),
    I16(i16),
    U8(u8),
    String(String),
    ByteArray(Vec<u8>),
}

impl Display for FieldValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::U32(v) => write!(f, "{}", v),
            Self::I32(v) => write!(f, "{}", v),
            Self::U16(v) => write!(f, "{}", v),
            Self::I16(v) => write!(f, "{}", v),
            Self::U8(v) => write!(f, "{}", v),
            Self::String(v) => write!(f, "{}", v),
            Self::ByteArray(v) => write!(f, "{:?}", v),
        }
    }
}