datex-core 0.0.13

The DATEX Core Rust implementation
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use crate::{core_compiler::core_compilation_context::ByteCursor, prelude::*};
use binrw::io::Write;
use core::{convert::TryInto, fmt::Write as FmtWrite, iter::FromIterator};
use itertools::Itertools;
/*
read functions for primitive data types on a U8 array, also increments the index
 */

pub fn read_u8(buffer: &[u8], index: &mut usize) -> u8 {
    let val = buffer[*index];
    *index += 1;
    val
}

pub fn read_i8(buffer: &[u8], index: &mut usize) -> i8 {
    let slice = &buffer[*index..*index + 1];
    *index += 1;
    i8::from_le_bytes(slice.try_into().unwrap())
}

pub fn read_u16(buffer: &[u8], index: &mut usize) -> u16 {
    let slice = &buffer[*index..*index + 2];
    *index += 2;
    u16::from_be_bytes(slice.try_into().unwrap())
}
pub fn read_i16(buffer: &[u8], index: &mut usize) -> i16 {
    let slice = &buffer[*index..*index + 2];
    *index += 2;
    i16::from_be_bytes(slice.try_into().unwrap())
}

pub fn read_i32(buffer: &[u8], index: &mut usize) -> i32 {
    let slice = &buffer[*index..*index + 4];
    *index += 4;
    i32::from_be_bytes(slice.try_into().unwrap())
}
pub fn read_u32(buffer: &[u8], index: &mut usize) -> u32 {
    let slice = &buffer[*index..*index + 4];
    *index += 4;
    u32::from_be_bytes(slice.try_into().unwrap())
}

pub fn read_u64(buffer: &[u8], index: &mut usize) -> u64 {
    let slice = &buffer[*index..*index + 8];
    *index += 8;
    u64::from_be_bytes(slice.try_into().unwrap())
}
pub fn read_i64(buffer: &[u8], index: &mut usize) -> i64 {
    let slice = &buffer[*index..*index + 8];
    *index += 8;
    i64::from_be_bytes(slice.try_into().unwrap())
}

pub fn read_f64(buffer: &[u8], index: &mut usize) -> f64 {
    let slice = &buffer[*index..*index + 8];
    *index += 8;
    f64::from_be_bytes(slice.try_into().unwrap())
}

pub fn read_string_utf8(
    buffer: &[u8],
    index: &mut usize,
    size: usize,
) -> String {
    // end is min(index+size, buffer len)
    let end = if *index + size > buffer.len() {
        buffer.len()
    } else {
        *index + size
    };
    let slice = &buffer[*index..end];
    *index = end;
    String::from_utf8(slice.to_vec())
        .unwrap_or("⎣INVALID UTF8 STRING⎤".to_string())
}

pub fn read_vec_slice(
    buffer: &[u8],
    index: &mut usize,
    size: usize,
) -> Vec<u8> {
    let slice = &buffer[*index..*index + size];
    *index += size;
    slice.to_vec()
}

pub fn read_slice<'a, const SIZE: usize>(
    buffer: &'a [u8],
    index: &mut usize,
) -> &'a [u8; SIZE] {
    let slice = &buffer[*index..*index + SIZE];
    *index += SIZE;
    slice.try_into().unwrap()
}

/*
write functions: set value at specific index in byte vector, vector length must be big enough
append functions: appends the value at the end of the byte vector, automatically increases size
 */

pub fn write_u8(buffer: &mut [u8], index: &mut usize, val: u8) {
    buffer[*index] = val;
    *index += 1;
}
pub fn append_u8(cursor: &mut ByteCursor, val: u8) {
    cursor
        .write_all(&[val])
        .expect("could not write u8 to buffer");
}
pub fn write_i8(buffer: &mut [u8], index: &mut usize, val: i8) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn append_i8(buffer: &mut Vec<u8>, val: i8) {
    buffer.extend_from_slice(&val.to_le_bytes());
}

pub fn write_u16(buffer: &mut [u8], index: &mut usize, val: u16) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn write_u32(buffer: &mut [u8], index: &mut usize, val: u32) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}

pub fn set_bit(buffer: &mut [u8], byte_index: usize, bit_position: u8) {
    buffer[byte_index] |= 1 << bit_position;
}

pub fn clear_bit(buffer: &mut [u8], byte_index: usize, bit_position: u8) {
    if byte_index < buffer.len() && bit_position < 8 {
        buffer[byte_index] &= !(1 << bit_position);
    }
}

pub fn toggle_bit(buffer: &mut [u8], byte_index: usize, bit_position: u8) {
    if byte_index < buffer.len() && bit_position < 8 {
        buffer[byte_index] ^= 1 << bit_position;
    }
}

// TODO #161
// pub fn write_int<T: PrimInt>(buffer: &mut Vec<u8>, mut index: usize, val: T) {
//     let bytes = val.to_u128().unwrap().to_le_bytes();
//     for b in bytes {
//         buffer[index] = b;
//         index += 1;
//     }
// }

pub fn append_u16(buffer: &mut ByteCursor, val: u16) {
    buffer
        .write_all(&val.to_le_bytes())
        .expect("could not write u16 to buffer");
}
pub fn write_i16(buffer: &mut [u8], index: &mut usize, val: i16) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn append_i16(cursor: &mut ByteCursor, val: i16) {
    cursor
        .write_all(&val.to_le_bytes())
        .expect("could not write i16 to buffer");
}

pub fn append_u32(cursor: &mut ByteCursor, val: u32) {
    cursor
        .write_all(&val.to_le_bytes())
        .expect("could not write u32 to buffer");
}
pub fn write_i32(buffer: &mut [u8], index: &mut usize, val: i32) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn append_i32(cursor: &mut ByteCursor, val: i32) {
    cursor
        .write_all(&val.to_le_bytes())
        .expect("could not write i32 to buffer");
}

pub fn write_u64(buffer: &mut [u8], index: &mut usize, val: u64) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn append_u64(buffer: &mut Vec<u8>, val: u64) {
    buffer.extend_from_slice(&val.to_le_bytes());
}
pub fn write_i64(buffer: &mut [u8], index: &mut usize, val: i64) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn append_i64(buffer: &mut Vec<u8>, val: i64) {
    buffer.extend_from_slice(&val.to_le_bytes());
}
pub fn append_i128(buffer: &mut Vec<u8>, val: i128) {
    buffer.extend_from_slice(&val.to_le_bytes());
}
pub fn append_u128(buffer: &mut Vec<u8>, val: u128) {
    buffer.extend_from_slice(&val.to_le_bytes());
}

pub fn write_f64(buffer: &mut [u8], index: &mut usize, val: f64) {
    let bytes = val.to_le_bytes();
    for b in bytes {
        buffer[*index] = b;
        *index += 1;
    }
}
pub fn append_f64(buffer: &mut Vec<u8>, val: f64) {
    buffer.extend_from_slice(&val.to_le_bytes());
}

pub fn append_f32(buffer: &mut Vec<u8>, val: f32) {
    buffer.extend_from_slice(&val.to_le_bytes());
}

pub fn append_string_utf8(buffer: &mut Vec<u8>, val: &str) {
    buffer.extend_from_slice(val.as_bytes());
}

// hex - buffer conversions

pub fn buffer_to_hex(buffer: Vec<u8>) -> String {
    let n = buffer.len();

    let mut s = String::with_capacity(2 * n);
    for byte in buffer {
        core::write!(s, "{byte:02X}").expect("could not parse buffer")
    }
    s
}

/**
 * seperator: char sequence inserted between each byte
 * pad_size_bytes: if 0, it is ignored
 * x_shorthand: collapse multiple 0 bytes to "xC", with C being the number of zero bytes
 */
pub fn buffer_to_hex_advanced(
    buffer: Vec<u8>,
    seperator: &str,
    pad_size_bytes: usize,
    x_shorthand: bool,
) -> String {
    let n = if pad_size_bytes == 0 {
        buffer.len()
    } else {
        pad_size_bytes
    };

    let buf_len = buffer.len();

    let mut s = String::with_capacity(2 * n);
    let mut i = 0;
    while i < n {
        // next byte
        let byte = if i < buf_len { buffer[i] } else { 0 };
        i += 1;
        // multiple (>=2) zero bytes - x shorthand
        if x_shorthand
            && byte == 0
            && i < n
            && if i < buf_len { buffer[i] } else { 0 } == 0
        {
            let mut zero_count: u8 = 2;
            let initial_i = i;
            while i + 1 < n && buffer[i + 1] == 0 {
                i += 1;
                zero_count += 1;
            }
            // 0 count, max 15
            if zero_count <= 0xf {
                i += 1;
                core::write!(s, "x{zero_count:01X}")
                    .expect("could not parse buffer");
            } else {
                i = initial_i;
                core::write!(s, "{byte:02X}").expect("could not parse buffer");
            }
        }
        // normal
        else {
            core::write!(s, "{byte:02X}").expect("could not parse buffer");
        }

        // seperator?
        if !seperator.is_empty() && i < n {
            s += seperator;
        }
    }

    s
}

pub fn hex_to_buffer(hex: String) -> Vec<u8> {
    let mut buffer = Vec::<u8>::new();

    for chunk in &hex.chars().chunks(2) {
        buffer.push(
            u8::from_str_radix(&String::from_iter(chunk), 16)
                .expect("invalid hex buffer"),
        );
    }

    buffer
}

pub fn hex_to_buffer_advanced(hex: String, seperator: &str) -> Vec<u8> {
    let mut buffer = Vec::<u8>::new();

    let raw_hex = hex.replace(seperator, "");

    for chunk in &raw_hex.chars().chunks(2) {
        let part = &String::from_iter(chunk);
        if part.starts_with("x") {
            let count = u8::from_str_radix(part.split_at(1).1, 16)
                .expect("invalid x shortcut");
            for _i in 0..count {
                buffer.push(0);
            }
        } else {
            buffer.push(
                u8::from_str_radix(part, 16).expect("invalid hex buffer"),
            );
        }
    }

    buffer
}

#[cfg(test)]
mod tests {
    use super::{
        buffer_to_hex, buffer_to_hex_advanced, hex_to_buffer,
        hex_to_buffer_advanced,
    };
    use crate::prelude::*;

    /**
     * test byte array to hex string conversion, including seperator characters and fixed length padding
     */
    #[test]
    pub fn buffer_to_hex_tests() {
        assert_eq!(buffer_to_hex_advanced(vec![], "_", 0, true), "");
        assert_eq!(
            buffer_to_hex_advanced(vec![0x00, 0x00, 0x00], "", 0, true),
            "x3"
        );
        assert_eq!(
            buffer_to_hex_advanced(
                vec![
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00
                ],
                "",
                0,
                true
            ),
            "xF"
        );
        assert_eq!(
            buffer_to_hex_advanced(
                vec![
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa
                ],
                "",
                0,
                true
            ),
            "00xFAA"
        );
        assert_eq!(buffer_to_hex(vec![0xaa, 0xbb, 0xcc, 0x00]), "AABBCC00");
        assert_eq!(
            buffer_to_hex_advanced(vec![0xaa, 0xbb, 0xcc, 0x00], "-", 0, false),
            "AA-BB-CC-00"
        );
        assert_eq!(
            buffer_to_hex_advanced(
                vec![0xaa, 0xbb, 0xcc, 0x00, 0x00, 0x00, 0x00, 0x01],
                "_",
                0,
                false
            ),
            "AA_BB_CC_00_00_00_00_01"
        );
        assert_eq!(
            buffer_to_hex_advanced(
                vec![0xaa, 0xbb, 0xcc, 0x00, 0x00, 0x00, 0x00, 0x01],
                "_",
                0,
                true
            ),
            "AA_BB_CC_x4_01"
        );

        assert_eq!(
            buffer_to_hex_advanced(vec![0xaa, 0xbb], "-", 4, true),
            "AA-BB-x2"
        );
        assert_eq!(
            buffer_to_hex_advanced(vec![0xaa, 0xbb, 0xcc], "-", 6, false),
            "AA-BB-CC-00-00-00"
        );
        assert_eq!(
            buffer_to_hex_advanced(vec![0xaa, 0xbb, 0xcc, 0xdd], "-", 2, false),
            "AA-BB"
        );
    }

    /**
     * test hex string to byte array conversion, and conversion back to hex string
     */
    #[test]
    pub fn hex_to_buffer_tests() {
        assert_eq!(hex_to_buffer(buffer_to_hex(vec![0x1])), vec![0x1]);
        assert_eq!(
            hex_to_buffer(buffer_to_hex(vec![0xaa, 0xbb, 0xcc, 0x00])),
            vec![0xaa, 0xbb, 0xcc, 0x00]
        );

        assert_eq!(buffer_to_hex(hex_to_buffer("".to_string())), "");
        assert_eq!(
            buffer_to_hex(hex_to_buffer("AABB1122".to_string())),
            "AABB1122"
        );
        assert_eq!(
            buffer_to_hex(hex_to_buffer_advanced(
                "AA-BB-11-22".to_string(),
                "-"
            )),
            "AABB1122"
        );
        assert_eq!(
            buffer_to_hex_advanced(
                hex_to_buffer_advanced("AA-BB-11-22".to_string(), "-"),
                "-",
                0,
                false
            ),
            "AA-BB-11-22"
        );

        assert_eq!(
            hex_to_buffer_advanced("AA-BB-11-22".to_string(), "-"),
            vec![0xAA, 0xBB, 0x11, 0x22]
        );
        assert_eq!(
            hex_to_buffer_advanced("AABB1122".to_string(), ""),
            vec![0xAA, 0xBB, 0x11, 0x22]
        );
    }
}