-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathcommon.rs
More file actions
66 lines (57 loc) · 1.57 KB
/
common.rs
File metadata and controls
66 lines (57 loc) · 1.57 KB
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
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2019 Intel Corporation
#[macro_export]
macro_rules! container_of {
($ptr:ident, $container:ty, $field:ident) => {{
(($ptr as usize) - core::mem::offset_of!($container, $field)) as *const $container
}};
}
#[macro_export]
macro_rules! container_of_mut {
($ptr:ident, $container:ty, $field:ident) => {{
(($ptr as usize) - core::mem::offset_of!($container, $field)) as *mut $container
}};
}
pub fn ascii_strip(s: &[u8]) -> &str {
core::str::from_utf8(s).unwrap().trim_matches(char::from(0))
}
pub fn ucs2_as_ascii_length(input: *const u16) -> usize {
let mut len = 0;
loop {
let v = (unsafe { *(((input as u64) + (2 * len as u64)) as *const u16) } & 0xffu16) as u8;
if v == 0 {
break;
}
len += 1;
}
len
}
pub fn ascii_length(input: &str) -> usize {
let mut len = 0;
for c in input.chars() {
if c == '\0' {
break;
}
len += 1;
}
len
}
pub fn ucs2_to_ascii(input: *const u16, output: &mut [u8]) {
let mut i: usize = 0;
assert!(output.len() >= ucs2_as_ascii_length(input));
while i < output.len() {
unsafe {
output[i] = (*(((input as u64) + (2 * i as u64)) as *const u16) & 0xffu16) as u8;
}
if output[i] == 0 {
break;
}
i += 1;
}
}
pub fn ascii_to_ucs2(input: &str, output: &mut [u16]) {
assert!(output.len() >= input.len() * 2);
for (i, c) in input.bytes().enumerate() {
output[i] = u16::from(c);
}
}