nandi/rustnimpublic Fork 0
ae9f986fc43d0fc9ab029946e2c7a25cdc72b4ed
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 · on ae9f986fc43d0fc9ab029946e2c7a25cdc72b4ed · nandithebull · 22h ago
main.rs · 83 lines · 2.4 KBRust Blame HistoryRaw
 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
//@ args: run
// base16ct 1.0.0, transpiled as a multi-file crate.
//
// `error.rs` and `mixed.rs` are the crate's own files, byte-for-byte.
// This file carries `lib.rs`'s core -- `decoded_len`, `encoded_len` and
// `decode_inner` verbatim -- plus a driver, because the runner needs a `main`.
// The `alloc`-gated items are off, as they are by default in the crate.

mod error;
mod mixed;

pub use crate::error::{Error, Result};

/// Compute decoded length of the given hex-encoded input.
#[inline(always)]
pub fn decoded_len(bytes: &[u8]) -> Result<usize> {
    if bytes.len() & 1 == 0 {
        Ok(bytes.len() / 2)
    } else {
        Err(Error::InvalidLength)
    }
}

/// Get the length of Base16 (hex) produced by encoding the given bytes.
#[inline(always)]
pub fn encoded_len(bytes: &[u8]) -> usize {
    bytes.len() * 2
}

fn decode_inner<'a>(
    src: &[u8],
    dst: &'a mut [u8],
    decode_nibble: impl Fn(u8) -> u16,
) -> Result<&'a [u8]> {
    let dst = dst
        .get_mut(..decoded_len(src)?)
        .ok_or(Error::InvalidLength)?;

    let mut err: u16 = 0;
    for (src, dst) in src.chunks_exact(2).zip(dst.iter_mut()) {
        let byte = (decode_nibble(src[0]) << 4) | decode_nibble(src[1]);
        err |= byte >> 8;
        *dst = byte as u8;
    }

    match err {
        0 => Ok(dst),
        _ => Err(Error::InvalidEncoding),
    }
}

fn show(tag: &str, r: Result<&[u8]>) {
    match r {
        Ok(v) => {
            print!("{} ok ", tag);
            for b in v.iter() {
                print!("{:02x}", b);
            }
            println!(" len={}", v.len());
        }
        Err(e) => println!("{} err {:?} / {}", tag, e, e),
    }
}

fn main() {
    let mut buf = [0u8; 16];

    show("mixed-l", mixed::decode(b"abcd1234", &mut buf));
    show("mixed-u", mixed::decode(b"ABCD1234", &mut buf));
    show("mixed-m", mixed::decode(b"abCD1234", &mut buf));
    show("edge", mixed::decode(b"00ff7f80", &mut buf));
    show("oddlen", mixed::decode(b"abc", &mut buf));
    show("bad", mixed::decode(b"zzzz", &mut buf));
    show("empty", mixed::decode(b"", &mut buf));

    let mut small = [0u8; 2];
    show("short-dst", mixed::decode(b"abcd1234", &mut small));

    // `lower::encode` is not here: `lower.rs` also defines `encode_str`, whose
    // body is a closure over an `unsafe` block, and neither is implemented.

    println!("{} {}", decoded_len(b"abcd").unwrap(), encoded_len(b"\xab\xcd"));
}