Moved the test and use compiler specific function

This commit is contained in:
zypeh 2022-08-25 21:12:25 +08:00 committed by Lucas
parent 7cff93e718
commit 10461779af
1 changed files with 2 additions and 16 deletions

View File

@ -1,7 +1,7 @@
pub fn to_usize(x: isize) -> usize { pub fn to_usize(x: isize) -> usize {
let double_x = x << 1; let double_x = x << 1;
if x >= 0 { if x.is_positive() || x == 0 {
double_x as usize double_x as usize
} else { } else {
(-double_x - 1) as usize (-double_x - 1) as usize
@ -9,19 +9,5 @@ pub fn to_usize(x: isize) -> usize {
} }
pub fn to_isize(u: usize) -> isize { pub fn to_isize(u: usize) -> isize {
let s = u as isize; ((u >> 1) as isize) ^ (-((u & 1) as isize))
(s >> 1) ^ -(s & 1)
}
#[cfg(test)]
mod test {
#[test]
fn convert() {
let n = -12;
let unsigned = super::to_usize(n);
let signed = super::to_isize(unsigned);
assert_eq!(n, signed)
}
} }