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
extern crate byteorder;
use byteorder::{BigEndian, LittleEndian, ReadBytesExt};

#[derive(Debug, Clone, PartialEq, Eq)]
/// `DecodedData` enum is used to wrap the decoded content into one of the supported data-type.
/// Example: `DecodedData::Str("hello")`, contains the string `hello` decoded back from the encoded bytes.
pub enum DecodedData {
    /// Int8 data representation
    Int8(i8),
    /// Int16 data representation
    Int16(i16),
    /// Int32 data representation
    Int32(i32),
    /// Int64 data representation
    Int64(i64),
    /// Int128 data representation
    Int128(i128),

    /// Uint8 data representation
    Uint8(u8),
    /// Uint16 data representation
    Uint16(u16),
    /// Uint32 data representation
    Uint32(u32),
    /// Uint64 data representation
    Uint64(u64),
    /// Uint128 data representation
    Uint128(u128),

    /// Str data representation
    Str(String),

    /// Bytes data representation
    Bytes(Vec<u8>),
}

#[derive(Debug, Clone)]
/// `DecodeType` enum can be used to tell the decoder who a sequence of bytes at a given offset must be decoded back.
/// Example: `DecodeType::Uint16` can be used to tell the decoder to interpret the next two bytes as `uint16`.
pub enum DecodeType {
    /// Int8 tells the decoder to decode next 1 byte as signed 8-bit integer
    Int8,
    /// Int16 tells the decoder to decode next 2 bytes as signed 16-bit integer
    Int16,
    /// Int32 tells the decoder to decode next 4 bytes as signed 32-bit integer
    Int32,
    /// Int64 tells the decoder to decode next 8 bytes as signed 64-bit integer
    Int64,
    /// Int128 tells the decoder to decode next 16 bytes as signed 128-bit integer
    Int128,

    /// Uint8 tells the decoder to decode next 1 byte as unsigned 8-bit integer
    Uint8,
    /// Uint16 tells the decoder to decode next 2 bytes as unsigned 16-bit integer
    Uint16,
    /// Uint32 tells the decoder to decode next 4 bytes as unsigned 32-bit integer
    Uint32,
    /// Uint64 tells the decoder to decode next 8 bytes as unsigned 64-bit integer
    Uint64,
    /// Uint128 tells the decoder to decode next 16 bytes as unsigned 128-bit integer
    Uint128,

    /// Str(usize) tells the decoded to decode next `x` bytes as a string
    Str(usize),

    /// Str(usize) tells the decoded to decode next `x` bytes as a byte-array
    Bytes(usize),
}

#[derive(Debug, Clone)]
/// `DecodeOrder` is used to specify how signed and unsigned integers encoded as bytes must be assumed w.r.t byte-order for decoding.
/// Example `DecodeOrder::Little` assumes all the bytes to be decoded are in little endian byte order.
pub enum DecodeOrder {
    /// Big endian byte ordering
    Big,
    /// Little endian byte ordering
    Little,
}

#[derive(Debug, Clone)]
/// `DecodeError` wraps the error that occurred during during
pub enum DecodeError {
    /// InvalidData represents an error that happens when given sequency of bytes at given offset cannot be decoded into the required data-type.
    /// Example `Err(DecodeErr::InvalidData(1))` says that the given bytes cannot be converted into the data-type specified at index 1.
    InvalidData(usize),
    /// IndexOutOfBounds occurs when offset > size of the byte array.
    IndexOutOfBounds,
}

#[inline]
fn decode_i16(mut array: &[u8], decode_order: DecodeOrder) -> Option<i16> {
    match decode_order {
        DecodeOrder::Big => array.read_i16::<BigEndian>(),
        DecodeOrder::Little => array.read_i16::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_i32(mut array: &[u8], decode_order: DecodeOrder) -> Option<i32> {
    match decode_order {
        DecodeOrder::Big => array.read_i32::<BigEndian>(),
        DecodeOrder::Little => array.read_i32::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_i64(mut array: &[u8], decode_order: DecodeOrder) -> Option<i64> {
    match decode_order {
        DecodeOrder::Big => array.read_i64::<BigEndian>(),
        DecodeOrder::Little => array.read_i64::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_i128(mut array: &[u8], decode_order: DecodeOrder) -> Option<i128> {
    match decode_order {
        DecodeOrder::Big => array.read_i128::<BigEndian>(),
        DecodeOrder::Little => array.read_i128::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_u16(mut array: &[u8], decode_order: DecodeOrder) -> Option<u16> {
    match decode_order {
        DecodeOrder::Big => array.read_u16::<BigEndian>(),
        DecodeOrder::Little => array.read_u16::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_u32(mut array: &[u8], decode_order: DecodeOrder) -> Option<u32> {
    match decode_order {
        DecodeOrder::Big => array.read_u32::<BigEndian>(),
        DecodeOrder::Little => array.read_u32::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_u64(mut array: &[u8], decode_order: DecodeOrder) -> Option<u64> {
    match decode_order {
        DecodeOrder::Big => array.read_u64::<BigEndian>(),
        DecodeOrder::Little => array.read_u64::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_u128(mut array: &[u8], decode_order: DecodeOrder) -> Option<u128> {
    match decode_order {
        DecodeOrder::Big => array.read_u128::<BigEndian>(),
        DecodeOrder::Little => array.read_u128::<LittleEndian>(),
    }
    .ok()
}

#[inline]
fn decode_string(array: &[u8]) -> Option<String> {
    String::from_utf8(array.to_vec()).ok()
}

#[allow(clippy::question_mark)]
/// `decode_packed` function decoded a given byte-array into list of required values specified in `types` parameter.
/// Returns the list of decoded values `Vec<DecodedData>` or `DecodeError`.
///
/// # Arguments
///
/// * `types`: List of required types to decode, example: `&[DecodeType::Int8, DecodeType::Str(10)]`
/// * `buffer`: Immutable reference to the slice that contains bytes to be decoded
/// * `decode_order`: the byte ordering to consider while decoding
///
/// # Examples
/// ```rust
/// extern crate packed_encoder;
/// use packed_encoder::decoder;
///
/// fn main() {
///
///     // byte data to decode
///     let bytes = vec![192, 24, 212, 73, 201, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 116, 104, 105, 115, 45, 105, 115, 45, 103, 111, 111, 100, 11, 230, 234, 49, 0, 0, 0, 0, 10, 255, 171, 18, 51];
///     // required types to decode from the given byte array
///     let required_types = &[
///            decoder::DecodeType::Int128,
///            decoder::DecodeType::Str(12),
///            decoder::DecodeType::Uint64,
///            decoder::DecodeType::Int8,
///            decoder::DecodeType::Bytes(4),
///        ];
///     
///     // decode
///     let result = decoder::decode_packed(required_types, &bytes, decoder::DecodeOrder::Little);
///     assert_eq!(result.is_ok(), true);
///
///     // check values
///     let decoded_data = result.unwrap();
///     match &decoded_data[1] {
///         decoder::DecodedData::Str(content) => {println!("decoded string at position 1: {}", content)},
///         _ => {}
///     }
///
/// }
/// ```
pub fn decode_packed(
    types: &[DecodeType],
    buffer: &[u8],
    decode_order: DecodeOrder,
) -> Result<Vec<DecodedData>, DecodeError> {
    let mut decoded_data = vec![];
    let mut last_read = 0;

    for (idx, entry) in types.iter().enumerate() {
        let (result, size_offset) = match entry {
            DecodeType::Int8 => {
                if buffer.len() < last_read + 1 {
                    (Err(DecodeError::IndexOutOfBounds), 1)
                } else {
                    (Ok(DecodedData::Int8(buffer[last_read] as i8)), 1)
                }
            }

            DecodeType::Int16 => {
                if buffer.len() < last_read + 2 {
                    (Err(DecodeError::IndexOutOfBounds), 2)
                } else {
                    let decoded_result =
                        decode_i16(&buffer[last_read..last_read + 2], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Int16(decoded)),
                        ),
                        2,
                    )
                }
            }

            DecodeType::Int32 => {
                if buffer.len() < last_read + 4 {
                    (Err(DecodeError::IndexOutOfBounds), 4)
                } else {
                    let decoded_result =
                        decode_i32(&buffer[last_read..last_read + 4], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Int32(decoded)),
                        ),
                        4,
                    )
                }
            }

            DecodeType::Int64 => {
                if buffer.len() < last_read + 8 {
                    (Err(DecodeError::IndexOutOfBounds), 8)
                } else {
                    let decoded_result =
                        decode_i64(&buffer[last_read..last_read + 8], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Int64(decoded)),
                        ),
                        8,
                    )
                }
            }

            DecodeType::Int128 => {
                if buffer.len() < last_read + 16 {
                    (Err(DecodeError::IndexOutOfBounds), 16)
                } else {
                    let decoded_result =
                        decode_i128(&buffer[last_read..last_read + 16], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Int128(decoded)),
                        ),
                        16,
                    )
                }
            }

            DecodeType::Uint8 => {
                if buffer.len() < last_read + 1 {
                    (Err(DecodeError::IndexOutOfBounds), 1)
                } else {
                    (Ok(DecodedData::Uint8(buffer[last_read])), 1)
                }
            }

            DecodeType::Uint16 => {
                if buffer.len() < last_read + 2 {
                    (Err(DecodeError::IndexOutOfBounds), 2)
                } else {
                    let decoded_result =
                        decode_u16(&buffer[last_read..last_read + 2], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Uint16(decoded)),
                        ),
                        2,
                    )
                }
            }

            DecodeType::Uint32 => {
                if buffer.len() < last_read + 4 {
                    (Err(DecodeError::IndexOutOfBounds), 4)
                } else {
                    let decoded_result =
                        decode_u32(&buffer[last_read..last_read + 4], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Uint32(decoded)),
                        ),
                        4,
                    )
                }
            }

            DecodeType::Uint64 => {
                if buffer.len() < last_read + 8 {
                    (Err(DecodeError::IndexOutOfBounds), 8)
                } else {
                    let decoded_result =
                        decode_u64(&buffer[last_read..last_read + 8], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Uint64(decoded)),
                        ),
                        8,
                    )
                }
            }

            DecodeType::Uint128 => {
                if buffer.len() < last_read + 16 {
                    (Err(DecodeError::IndexOutOfBounds), 16)
                } else {
                    let decoded_result =
                        decode_u128(&buffer[last_read..last_read + 16], decode_order.clone());
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Uint128(decoded)),
                        ),
                        16,
                    )
                }
            }

            DecodeType::Str(size) => {
                if buffer.len() < last_read + *size {
                    (Err(DecodeError::IndexOutOfBounds), *size)
                } else {
                    let decoded_result = decode_string(&buffer[last_read..last_read + *size]);
                    (
                        decoded_result.map_or_else(
                            || Err(DecodeError::InvalidData(idx)),
                            |decoded| Ok(DecodedData::Str(decoded)),
                        ),
                        *size,
                    )
                }
            }

            DecodeType::Bytes(size) => {
                if buffer.len() < last_read + *size {
                    (Err(DecodeError::IndexOutOfBounds), *size)
                } else {
                    let vec_repr = buffer[last_read..last_read + *size].to_vec();
                    (Ok(DecodedData::Bytes(vec_repr)), *size)
                }
            }
        };

        if let Err(err) = result {
            return Err(err);
        }

        last_read += size_offset;
        decoded_data.push(result.unwrap());
    }

    Ok(decoded_data)
}