asn1rs 0.1.14

ASN.1 to Rust, Protobuf and SQL compiler/code generator. Supports ASN.1 UPER
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use backtrace::Backtrace;
use byteorder::LittleEndian as E;
use byteorder::ReadBytesExt;
use byteorder::WriteBytesExt;
use std::io::Error as IoError;
use std::io::Read;
use std::io::Write;

#[derive(Debug)]
pub enum Error {
    Io(Backtrace, IoError),
    #[allow(unused)]
    InvalidUtf8Received,
    #[allow(unused)]
    MissingRequiredField(&'static str),
    InvalidTagReceived(Backtrace, u32),
    InvalidFormat(Backtrace, u32),
    UnexpectedFormat(Backtrace, Format),
    UnexpectedTag(Backtrace, (u32, Format)),
}

impl Error {
    #[allow(unused)]
    pub fn invalid_format(format: u32) -> Self {
        Error::InvalidFormat(Backtrace::new(), format)
    }

    #[allow(unused)]
    pub fn invalid_variant(format: u32) -> Self {
        Error::InvalidFormat(Backtrace::new(), format)
    }

    #[allow(unused)]
    pub fn invalid_tag_received(tag: u32) -> Self {
        Error::InvalidTagReceived(Backtrace::new(), tag)
    }

    #[allow(unused)]
    pub fn unexpected_format(format: Format) -> Self {
        Error::UnexpectedFormat(Backtrace::new(), format)
    }

    #[allow(unused)]
    pub fn unexpected_tag(tag: (u32, Format)) -> Self {
        Error::UnexpectedTag(Backtrace::new(), tag)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::Io(b, ioe) => write!(f, "Internal IO Error: {}\n{:?}", ioe, b),
            Error::InvalidUtf8Received => write!(f, "Received String is not valid UTF8"),
            Error::MissingRequiredField(name) => {
                write!(f, "The required field '{}' is missing", name)
            }
            Error::InvalidTagReceived(b, tag) => write!(f, "Tag({}) is unknown\n{:?}", tag, b),
            Error::InvalidFormat(b, tag) => write!(f, "Format({}) is invalid\n{:?}", tag, b),
            Error::UnexpectedFormat(b, format) => {
                write!(f, "Format({:?}) is unexpected\n{:?}", format, b)
            }
            Error::UnexpectedTag(b, (tag, format)) => {
                write!(f, "Tag({}/{:?}) is unexpected\n{:?}", tag, format, b)
            }
        }
    }
}

impl std::error::Error for Error {}

#[derive(Debug, PartialOrd, PartialEq)]
#[repr(u32)]
pub enum Format {
    #[allow(unused)]
    VarInt = 0,
    #[allow(unused)]
    Fixed64 = 1,
    #[allow(unused)]
    LengthDelimited = 2,
    #[allow(unused)]
    Fixed32 = 5,
}

impl ToString for Format {
    fn to_string(&self) -> String {
        match self {
            Format::VarInt => "VarInt",
            Format::Fixed64 => "Fixed64",
            Format::LengthDelimited => "LengthDelimited",
            Format::Fixed32 => "Fixed32",
        }
        .into()
    }
}

impl Format {
    #[allow(unused)]
    pub fn from(id: u32) -> Result<Format, Error> {
        match id {
            0 => Ok(Format::VarInt),
            1 => Ok(Format::Fixed64),
            2 => Ok(Format::LengthDelimited),
            5 => Ok(Format::Fixed32),
            f => Err(Error::InvalidFormat(Backtrace::new(), f)),
        }
    }
}

impl From<IoError> for Error {
    fn from(e: IoError) -> Self {
        Error::Io(Backtrace::new(), e)
    }
}

pub trait Protobuf: ProtobufEq {
    fn protobuf_format(&self) -> Format;

    fn read_protobuf(reader: &mut dyn Reader) -> Result<Self, Error>
    where
        Self: Sized;

    fn write_protobuf(&self, writer: &mut dyn Writer) -> Result<(), Error>;
}

pub trait Writer {
    fn write_varint(&mut self, value: u64) -> Result<(), Error>;

    fn write_bool(&mut self, value: bool) -> Result<(), Error> {
        self.write_varint(if value { 1 } else { 0 })
    }

    fn write_bytes(&mut self, value: &[u8]) -> Result<(), Error>;

    fn write_tag(&mut self, field: u32, format: Format) -> Result<(), Error> {
        self.write_varint(u64::from(field << 3 | (format as u32)))
    }

    fn write_enum_variant(&mut self, variant: u32) -> Result<(), Error> {
        self.write_varint(u64::from(variant))
    }

    fn write_sfixed32(&mut self, value: i32) -> Result<(), Error>;

    fn write_uint32(&mut self, value: u32) -> Result<(), Error> {
        self.write_varint(u64::from(value))
    }

    fn write_uint64(&mut self, value: u64) -> Result<(), Error> {
        self.write_varint(value)
    }

    fn write_sint32(&mut self, value: i32) -> Result<(), Error> {
        // remove leading negative sign to allow further size reduction
        // protobuf magic, probably something like value - I32_MIN
        self.write_varint(((value << 1) ^ (value >> 31)) as u64)
    }

    fn write_sint64(&mut self, value: i64) -> Result<(), Error> {
        // remove leading negative sign to allow further size reduction
        // protobuf magic, probably something like value - I64_MIN
        self.write_varint(((value << 1) ^ (value >> 63)) as u64)
    }

    fn write_string(&mut self, value: &str) -> Result<(), Error>;

    fn write_tagged_bool(&mut self, field: u32, value: bool) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_bool(value)
    }

    fn write_tagged_bytes(&mut self, field: u32, value: &[u8]) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_bytes(value)
    }

    fn write_tagged_sfixed32(&mut self, field: u32, value: i32) -> Result<(), Error> {
        self.write_tag(field, Format::Fixed32)?;
        self.write_sfixed32(value)
    }

    fn write_tagged_uint32(&mut self, field: u32, value: u32) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_uint32(value)
    }

    fn write_tagged_uint64(&mut self, field: u32, value: u64) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_uint64(value)
    }

    fn write_tagged_sint32(&mut self, field: u32, value: i32) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_sint32(value)
    }

    fn write_tagged_sint64(&mut self, field: u32, value: i64) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_sint64(value)
    }

    fn write_tagged_string(&mut self, field: u32, value: &str) -> Result<(), Error> {
        self.write_tag(field, Format::LengthDelimited)?;
        self.write_string(value)
    }

    fn write_tagged_varint(&mut self, field: u32, value: u64) -> Result<(), Error> {
        self.write_tag(field, Format::VarInt)?;
        self.write_varint(value)
    }

    fn write_tagged_enum_variant(&mut self, field: u32, value: u32) -> Result<(), Error> {
        self.write_tagged_varint(field, u64::from(value))
    }
}

impl<W: Write> Writer for W {
    fn write_varint(&mut self, mut value: u64) -> Result<(), Error> {
        while value > 0x7F {
            self.write_u8(((value as u8) & 0x7F) | 0x80)?;
            value >>= 7;
        }
        self.write_u8(value as u8)?;
        Ok(())
    }

    fn write_bytes(&mut self, value: &[u8]) -> Result<(), Error> {
        self.write_varint(value.len() as u64)?;
        self.write_all(value)?;
        Ok(())
    }

    fn write_sfixed32(&mut self, value: i32) -> Result<(), Error> {
        self.write_i32::<E>(value)?;
        Ok(())
    }

    fn write_string(&mut self, value: &str) -> Result<(), Error> {
        self.write_bytes(value.as_bytes())?;
        Ok(())
    }
}

pub trait Reader {
    fn read_varint(&mut self) -> Result<u64, Error>;

    fn read_bool(&mut self) -> Result<bool, Error> {
        Ok(self.read_varint()? != 0)
    }

    fn read_bytes(&mut self) -> Result<Vec<u8>, Error>;

    fn read_tag(&mut self) -> Result<(u32, Format), Error> {
        let mask = 0b0000_0111;
        let tag = self.read_varint()? as u32;
        let format = Format::from(tag & mask)?;
        let field = tag >> 3;
        Ok((field, format))
    }

    fn read_enum_variant(&mut self) -> Result<u32, Error> {
        Ok(self.read_varint()? as u32)
    }

    fn read_sfixed32(&mut self) -> Result<i32, Error>;

    fn read_uint32(&mut self) -> Result<u32, Error> {
        Ok(self.read_varint()? as u32)
    }

    fn read_uint64(&mut self) -> Result<u64, Error> {
        self.read_varint()
    }

    fn read_sint32(&mut self) -> Result<i32, Error> {
        // remove leading negative sign to allow further size reduction
        // protobuf magic, probably something like value - I32_MIN
        let value = self.read_varint()? as u32;
        Ok(((value >> 1) as i32) ^ (-((value & 0x01) as i32)))
    }

    fn read_sint64(&mut self) -> Result<i64, Error> {
        // remove leading negative sign to allow further size reduction
        // protobuf magic, probably something like value - I64_MIN
        let value = self.read_varint()?;
        Ok(((value >> 1) as i64) ^ (-((value & 0x01) as i64)))
    }

    fn read_string(&mut self) -> Result<String, Error>;
}

impl<R: Read> Reader for R {
    fn read_varint(&mut self) -> Result<u64, Error> {
        let mut value = 0;
        let mut shift = 0_usize;
        while shift < 64 {
            let read = self.read_u8()?;
            value |= u64::from(read & 0x7F) << shift;
            shift += 7;
            if read & 0x80 == 0 {
                break;
            }
        }
        Ok(value)
    }

    fn read_bytes(&mut self) -> Result<Vec<u8>, Error> {
        let len = self.read_varint()? as usize;
        let mut vec = vec![0_u8; len];
        self.read_exact(&mut vec[..])?;
        Ok(vec)
    }

    fn read_sfixed32(&mut self) -> Result<i32, Error> {
        Ok(self.read_i32::<E>()?)
    }

    fn read_string(&mut self) -> Result<String, Error> {
        let bytes = self.read_bytes()?;
        if let Ok(string) = String::from_utf8(bytes) {
            Ok(string)
        } else {
            Err(Error::InvalidUtf8Received)
        }
    }
}

#[allow(clippy::module_name_repetitions)]
pub trait ProtobufEq<Rhs: ?Sized = Self> {
    fn protobuf_eq(&self, other: &Rhs) -> bool;
}

impl<T: ProtobufEq + Default + PartialEq> ProtobufEq<Option<T>> for Option<T> {
    fn protobuf_eq(&self, other: &Option<T>) -> bool {
        match self {
            Some(ref v) => match other {
                Some(ref v_other) => v.protobuf_eq(v_other),
                None => v == &T::default(),
            },
            None => match other {
                Some(ref v_other) => &T::default() == v_other,
                None => true,
            },
        }
    }
}

impl<T: ProtobufEq> ProtobufEq<Vec<T>> for Vec<T> {
    fn protobuf_eq(&self, other: &Vec<T>) -> bool {
        if self.len() == other.len() {
            for (i, v) in self.iter().enumerate() {
                if !other[i].protobuf_eq(v) {
                    return false;
                }
            }
            true
        } else {
            false
        }
    }
}

impl ProtobufEq<bool> for bool {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<u8> for u8 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<u16> for u16 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<u32> for u32 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<u64> for u64 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<i8> for i8 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<i16> for i16 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<i32> for i32 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<i64> for i64 {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}

impl ProtobufEq<String> for String {
    fn protobuf_eq(&self, other: &Self) -> bool {
        self == other
    }
}