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
use std::prelude::v1::*;
#[cfg(test)]
macro_rules! assert_size_of {
($size_of:expr, $ident:ident) => (assert_eq!($size_of, std::mem::size_of::<$ident>(),
concat!("Unexpected sizeof(", stringify!($ident), ")")));
}
#[test]
#[should_panic]
fn assert_size_of() {
struct Foo(i32);
assert_size_of!(8, Foo);
}
macro_rules! offset_of {
($ty:ty, $($field_bits:tt)*) => {
unsafe { &(*(0 as *const $ty)).$($field_bits)* as *const _ as usize }
}
}
mod c_str;
#[allow(dead_code)]
mod wide_str;
mod guid;
mod align;
#[cfg(feature = "serde")]
pub(crate) mod serde_helper;
pub use self::c_str::CStr;
pub(crate) use self::wide_str::FmtUtf16;
pub use self::align::*;
pub trait FromBytes {
const MIN_SIZE_OF: usize;
const ALIGN_OF: usize;
unsafe fn from_bytes(bytes: &[u8]) -> Option<&Self>;
}
#[inline]
pub(crate) fn split_f<T, F: FnMut(&T) -> bool>(slice: &[T], f: F) -> (&[T], &[T]) {
let i = slice.iter().position(f).unwrap_or(slice.len());
(&slice[..i], &slice[i..])
}
#[inline]
pub fn strn(buf: &[u8]) -> &[u8] {
split_f(buf, |&byte| byte == 0).0
}
pub(crate) fn trimn(buf: &[u8]) -> &[u8] {
let mut len = buf.len();
while len > 0 {
if buf[len - 1] != 0 {
break;
}
len -= 1;
}
&buf[..len]
}
pub(crate) fn parsen(buf: &[u8]) -> Result<&str, &[u8]> {
std::str::from_utf8(trimn(buf)).map_err(|_| buf)
}
#[inline]
pub fn wstrn(buf: &[u16]) -> &[u16] {
split_f(buf, |&word| word == 0).0
}
#[cfg(feature = "std")]
pub fn shannon_entropy(data: &[u8]) -> f64 {
let mut map = [0usize; 256];
for &byte in data {
map[byte as usize] += 1;
}
let mut result = 0.0;
let len = data.len() as f64;
for &item in &map[..] {
if item != 0 {
let freq = item as f64 / len;
result -= freq * freq.log2();
}
}
result
}
pub(crate) unsafe fn extend_in_place<'a, T, F: FnMut(&'a mut [T])>(vec: &'a mut Vec<T>, additional: usize, mut f: F) {
let vec_len = vec.len();
if vec_len + additional > vec.capacity() {
vec.reserve(additional);
}
f(std::slice::from_raw_parts_mut(vec.as_mut_ptr().offset(vec_len as isize), additional));
vec.set_len(vec_len + additional);
}