#byte #byte-slice #integer #read #bench #zeroed #u64

from_bytes_or_zeroed

Reads integers from an arbitrary slice of bytes

1 unstable release

0.1.0 May 14, 2023

#2145 in Algorithms

Download history 2181/week @ 2024-07-22 2284/week @ 2024-07-29 1781/week @ 2024-08-05 2954/week @ 2024-08-12 2461/week @ 2024-08-19 3738/week @ 2024-08-26 2802/week @ 2024-09-02 4241/week @ 2024-09-09 3689/week @ 2024-09-16 3952/week @ 2024-09-23 5993/week @ 2024-09-30 5993/week @ 2024-10-07 3515/week @ 2024-10-14 4201/week @ 2024-10-21 4337/week @ 2024-10-28 3885/week @ 2024-11-04

16,012 downloads per month
Used in 12 crates (via bitcode_lightyear_patch)

MIT/Apache

15KB
250 lines

from_bytes_or_zeroed

A crate that reads integers from an arbitrary slice of bytes


lib.rs:

from_bytes_or_zeroed is a crate for creating integers from a slice of bytes of any length.

Usage

use from_bytes_or_zeroed::FromBytesOrZeroed;

// If there are too few bytes the remaining bytes are zeroed.
let a = [1, 2];
let b = [1, 2, 0, 0, 0, 0, 0, 0];
assert_eq!(u64::from_le_bytes_or_zeroed(&a), u64::from_le_bytes(b));

// If there are too many bytes the extra bytes are ignored.
let a = [1, 2, 3, 4, 5, 6];
let b = [1, 2, 3, 4];
assert_eq!(u32::from_le_bytes_or_zeroed(&a), u32::from_le_bytes(b));

Motivation

This crate was created because implementing this operation for [prim@u64] in safe Rust was significantly slower than using unsafe.

test benches::bench_u64_safe    ... bench:       1,509 ns/iter (+/- 29)
test benches::bench_u64_unsafe  ... bench:         644 ns/iter (+/- 8)

No runtime deps