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
#![feature(llvm_asm)]
#![no_std]
#![warn(unused)]
#![warn(missing_debug_implementations)]
#![allow(unused_unsafe)]
#![allow(unreachable_code)]
#![allow(dead_code)]
#![cfg_attr(test, allow(unused_imports))]
#![warn(missing_docs)]
#![deny(intra_doc_link_resolution_failure)]
use num_traits::Num;
use core::ops::{Not, BitAnd};
use core::fmt::Write;
pub mod io;
mod cursor;
pub use crate::cursor::*;
pub mod loop_future;
pub fn align_up<T: Num + Not<Output = T> + BitAnd<Output = T> + Copy>(addr: T, align: T) -> T
{
align_down(addr + (align - T::one()), align)
}
pub fn align_down<T: Num + Not<Output = T> + BitAnd<Output = T> + Copy>(addr: T, align: T) -> T
{
addr & !(align - T::one())
}
pub fn align_up_checked(addr: usize, align: usize) -> Option<usize> {
match addr & (align - 1) {
0 => Some(addr),
_ => addr.checked_add(align - (addr % align))
}
}
pub fn div_ceil<T: Num + Copy>(a: T, b: T) -> T {
if a % b != T::zero() {
a / b + T::one()
} else {
a / b
}
}
#[macro_export]
macro_rules! enum_with_val {
($(#[$meta:meta])* $vis:vis struct $ident:ident($innervis:vis $ty:ty) {
$($(#[$varmeta:meta])* $variant:ident = $num:expr),* $(,)*
}) => {
$(#[$meta])*
#[repr(transparent)]
$vis struct $ident($innervis $ty);
impl $ident {
$($(#[$varmeta])* $vis const $variant: $ident = $ident($num);)*
}
impl ::core::fmt::Debug for $ident {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
$(&$ident::$variant => write!(f, "{}::{}", stringify!($ident), stringify!($variant)),)*
&$ident(v) => write!(f, "UNKNOWN({})", v),
}
}
}
}
}
pub fn print_hexdump<T: Write>(f: &mut T, mem: &[u8]) {
print_hexdump_as_if_at_addr(f, mem, mem.as_ptr() as usize)
}
pub fn print_hexdump_as_if_at_addr<T: Write>(f: &mut T, mem: &[u8], display_addr: usize) {
for chunk in mem.chunks(16) {
let mut arr = [None; 16];
for (i, elem) in chunk.iter().enumerate() {
arr[i] = Some(*elem);
}
let offset_in_mem = chunk.as_ptr() as usize - mem.as_ptr() as usize;
let _ = write!(f, "{:08x}:", display_addr + offset_in_mem);
for pair in arr.chunks(2) {
let _ = write!(f, " ");
for elem in pair {
if let Some(i) = *elem {
let _ = write!(f, "{:02x}", i);
} else {
let _ = write!(f, " ");
}
}
}
let _ = write!(f, " ");
for i in chunk {
if i.is_ascii_graphic() || *i == 0x20 {
let _ = write!(f, "{}", *i as char);
} else {
let _ = write!(f, ".");
}
}
let _ = writeln!(f);
}
}
pub trait BitArrayExt<U: ::bit_field::BitField>: ::bit_field::BitArray<U> {
fn set_bits_area(&mut self, range: ::core::ops::Range<usize>, value: bool) {
for i in range {
self.set_bit(i, value);
}
}
}
impl<T: ?Sized, U: ::bit_field::BitField> BitArrayExt<U> for T where T: ::bit_field::BitArray<U> {}
pub fn bit_array_first_zero(bitarray: &[u8]) -> Option<usize> {
for (index, &byte) in bitarray.iter().enumerate() {
if byte == 0xFF {
continue;
}
for offset in 0..8 {
if (byte & (1 << offset)) == 0 {
return Some(index * 8 + offset);
}
}
}
None
}
pub fn bit_array_first_one(bitarray: &[u8]) -> Option<usize> {
for (index, &byte) in bitarray.iter().enumerate() {
if byte == 0x00 {
continue;
}
for offset in 0..8 {
if (byte & (1 << offset)) != 0 {
return Some(index * 8 + offset);
}
}
}
None
}
pub fn bit_array_first_count_one(bitarray: &[u8], count: usize) -> Option<usize> {
let mut curcount = 0;
for (index, &byte) in bitarray.iter().enumerate() {
if byte == 0x00 {
curcount = 0;
continue;
}
for offset in 0..8 {
if (byte & (1 << offset)) != 0 {
curcount += 1;
if curcount == count {
return Some((index * 8 + offset) - (count - 1));
}
} else {
curcount = 0;
}
}
}
None
}
pub const fn log2_floor(val: usize) -> usize {
core::mem::size_of::<usize>() * 8 - val.leading_zeros() as usize - 1
}
pub const fn log2_ceil(val: usize) -> usize {
core::mem::size_of::<usize>() * 8 - val.leading_zeros() as usize - (val & (val - 1) == 0) as usize
}
#[allow(clippy::cast_ptr_alignment)]
pub unsafe fn cast_mut<T, R>(data: &mut [T]) -> &mut [R] {
let elem_of_r = core::mem::size_of::<T>() * data.len() / core::mem::size_of::<R>();
core::slice::from_raw_parts_mut(data.as_mut_ptr() as *mut R, elem_of_r)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_log2_floor() {
for i in 1..512 {
assert_eq!((i as f32).log2().floor() as usize, log2_floor(i));
}
}
#[test]
fn test_log2_ceil() {
for i in 1..512 {
assert_eq!((i as f32).log2().ceil() as usize, log2_ceil(i));
}
}
#[test]
#[should_panic]
fn test_log2_floor_panic() {
log2_floor(0);
}
#[test]
#[should_panic]
fn test_log2_ceil_panic() {
log2_ceil(0);
}
}
#[macro_export]
macro_rules! initialize_to_zero {
($ty:ty) => {{
#[doc(hidden)]
union ZeroedTypeUnion {
data: $ty,
arr: [u8; core::mem::size_of::<$ty>()]
}
ZeroedTypeUnion { arr: [0; core::mem::size_of::<$ty>()] }.data
}}
}