Dekejit/src/lib.rs

68 lines
1.9 KiB
Rust
Raw Normal View History

2023-04-28 12:18:07 +02:00
use std::mem::transmute;
pub mod assembler;
pub mod cli;
2023-04-28 12:18:07 +02:00
pub mod cpu;
pub mod jit;
pub mod loader;
pub mod pretty_printers;
2023-04-28 12:18:07 +02:00
pub fn interpret_as_signed(x: u16) -> i16 {
// the two types have the same size.
unsafe {
return transmute::<u16, i16>(x);
}
}
pub fn interpret_as_unsigned(x: i16) -> u16 {
// the two types have the same size.
unsafe {
return transmute::<i16, u16>(x);
}
}
pub fn transmute_to_vecu16_as_is(x: Vec<u8>) -> Vec<u16> {
let mut rb = x.iter();
// raw_bytes must be converted to u16.
//
let bytes: Vec<u16> = {
let mut res = vec![];
// Depends on the order in which the arguments of a tuple are
// evaluated. Rust guarantees to be left-to-right.
while let (Some(word0), Some(word1)) = (rb.next(), rb.next()) {
// println!("Pair: {}, {}, word: {:?}", word0, word1, raw_bytes);
res.push(((*word0 as u16) << 8) + (*word1 as u16));
}
// if we branch into this else, either there's a single word left or zero.
// since, in case a single word was left, the first rb.next() call in the line
// above would've consumed it, we have to gather that last element again
match x.len() {
0 => res,
n => {
if n % 2 != 0 {
// if there's an uneven number of chunks of 8 bits,
// we introduce padding!
// println!("Adding last one too");
res.push((*x.last().unwrap() as u16) << 8);
}
res
}
}
};
return bytes;
}
pub fn transmute_to_vecu8_as_is(x: Vec<u16>) -> Vec<u8> {
let mut bytes = vec![];
for b in x.iter() {
let x0 = (*b & 0xFF00) >> 8;
let x1 = *b & 0x00FF;
bytes.push(x0 as u8);
bytes.push(x1 as u8);
}
return bytes;
}