use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeType {
Int,
Int64,
Short,
Char,
UChar,
UShort,
UInt,
UInt64,
Float,
Double,
Ptr,
UPtr,
Str,
WStr,
AStr,
}
impl NativeType {
pub fn width(&self) -> usize {
match self {
NativeType::Char | NativeType::UChar => 1,
NativeType::Short | NativeType::UShort => 2,
NativeType::Int | NativeType::UInt | NativeType::Float => 4,
_ => 8,
}
}
pub fn is_float(&self) -> bool {
matches!(self, NativeType::Float | NativeType::Double)
}
pub fn is_text(&self) -> bool {
matches!(self, NativeType::Str | NativeType::WStr | NativeType::AStr)
}
pub fn is_integer(&self) -> bool {
!self.is_float() && !self.is_text()
}
pub fn is_unsigned(&self) -> bool {
matches!(
self,
NativeType::UChar
| NativeType::UShort
| NativeType::UInt
| NativeType::UInt64
| NativeType::UPtr
)
}
pub fn character_width(&self) -> usize {
match self {
NativeType::AStr => 1,
_ => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Convention {
Standard,
Cdecl,
}
#[derive(Debug, Clone, PartialEq)]
pub enum NativeValue {
Integer(i64),
Float(f64),
Bytes(Vec<u8>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct NativeArg {
pub kind: NativeType,
pub address: bool,
pub value: NativeValue,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NativeCall {
pub library: String,
pub function: String,
pub convention: Convention,
pub returns: NativeType,
pub arguments: Vec<NativeArg>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NativeResult {
pub kind: NativeType,
pub value: NativeValue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeFailureKind {
Invalid,
NoLibrary,
NoFunction,
}
#[derive(Debug, Clone, PartialEq)]
pub struct NativeFailure {
pub kind: NativeFailureKind,
pub reason: String,
}
impl NativeFailure {
pub fn invalid(reason: &str) -> Self {
NativeFailure {
kind: NativeFailureKind::Invalid,
reason: reason.to_string(),
}
}
pub fn no_library(reason: &str) -> Self {
NativeFailure {
kind: NativeFailureKind::NoLibrary,
reason: reason.to_string(),
}
}
pub fn no_function(reason: &str) -> Self {
NativeFailure {
kind: NativeFailureKind::NoFunction,
reason: reason.to_string(),
}
}
}
pub fn parse_type(text: &str) -> Option<(NativeType, bool)> {
let trimmed = text.trim();
let (body, address) = match trimmed
.strip_suffix('*')
.or_else(|| trimmed.strip_suffix('P'))
{
Some(body) => (body.trim(), true),
None => (trimmed, false),
};
let kind = match body.to_ascii_lowercase().as_str() {
"int" => NativeType::Int,
"int64" => NativeType::Int64,
"short" => NativeType::Short,
"char" => NativeType::Char,
"uchar" => NativeType::UChar,
"ushort" => NativeType::UShort,
"uint" => NativeType::UInt,
"uint64" => NativeType::UInt64,
"float" => NativeType::Float,
"double" => NativeType::Double,
"ptr" => NativeType::Ptr,
"uptr" => NativeType::UPtr,
"str" => NativeType::Str,
"wstr" => NativeType::WStr,
"astr" => NativeType::AStr,
_ => return None,
};
Some((kind, address))
}
pub fn split_target(text: &str) -> (String, String) {
let trimmed = text.trim();
match trimmed.rsplit_once('\\') {
Some((library, function)) => (library.to_string(), function.trim().to_string()),
None => (String::new(), trimmed.to_string()),
}
}
pub fn encode(text: &str, kind: NativeType) -> Vec<u8> {
let mut bytes = Vec::new();
match kind {
NativeType::AStr => {
bytes.extend_from_slice(text.as_bytes());
bytes.push(0);
}
_ => {
for unit in text.encode_utf16() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
bytes.extend_from_slice(&[0, 0]);
}
}
bytes
}
pub fn decode(bytes: &[u8], kind: NativeType) -> String {
match kind {
NativeType::AStr => {
let end = bytes
.iter()
.position(|byte| *byte == 0)
.unwrap_or(bytes.len());
String::from_utf8_lossy(&bytes[..end]).into_owned()
}
_ => {
let mut units: Vec<u16> = Vec::new();
let mut index = 0;
while index + 1 < bytes.len() {
let unit = u16::from_le_bytes([bytes[index], bytes[index + 1]]);
if unit == 0 {
break;
}
units.push(unit);
index += 2;
}
String::from_utf16_lossy(&units)
}
}
}
pub fn encode_number(number: f64, kind: NativeType) -> Vec<u8> {
let mut bytes = Vec::new();
match kind {
NativeType::Float => bytes.extend_from_slice(&(number as f32).to_le_bytes()),
NativeType::Double => bytes.extend_from_slice(&number.to_le_bytes()),
_ => {
let whole = number as i64;
match kind.width() {
1 => bytes.push(whole as u8),
2 => bytes.extend_from_slice(&(whole as u16).to_le_bytes()),
4 => bytes.extend_from_slice(&(whole as u32).to_le_bytes()),
_ => bytes.extend_from_slice(&whole.to_le_bytes()),
}
}
}
bytes
}
pub fn decode_number(bytes: &[u8], kind: NativeType) -> f64 {
match kind {
NativeType::Float => f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f64,
NativeType::Double => {
let mut whole = [0u8; 8];
whole.copy_from_slice(&bytes[..8]);
f64::from_le_bytes(whole)
}
_ => {
let mut whole = 0i64;
for byte in bytes.iter().take(kind.width()).rev() {
whole = (whole << 8) | *byte as i64;
}
let bits = kind.width() * 8;
if bits < 64 && !kind.is_unsigned() {
let sign = 1i64 << (bits - 1);
if whole & sign != 0 {
whole -= sign << 1;
}
}
whole as f64
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const WHOLE: [NativeType; 8] = [
NativeType::Int,
NativeType::Int64,
NativeType::Short,
NativeType::Char,
NativeType::UInt,
NativeType::UInt64,
NativeType::UShort,
NativeType::UChar,
];
#[test]
fn a_number_goes_out_and_comes_back() {
for kind in WHOLE {
let bytes = encode_number(42.0, kind);
assert_eq!(bytes.len(), kind.width(), "{kind:?}");
assert_eq!(decode_number(&bytes, kind), 42.0, "{kind:?}");
}
}
#[test]
fn a_negative_number_comes_back_negative() {
let bytes = encode_number(-1.0, NativeType::Int);
assert_eq!(decode_number(&bytes, NativeType::Int), -1.0);
let bytes = encode_number(-1.0, NativeType::Int64);
assert_eq!(decode_number(&bytes, NativeType::Int64), -1.0);
}
#[test]
fn an_unsigned_number_stays_positive() {
let bytes = encode_number(-1.0, NativeType::UInt);
assert_eq!(decode_number(&bytes, NativeType::UInt), 4294967295.0);
let bytes = encode_number(-1.0, NativeType::UChar);
assert_eq!(decode_number(&bytes, NativeType::UChar), 255.0);
}
#[test]
fn a_float_goes_out_and_comes_back() {
let bytes = encode_number(1.5, NativeType::Float);
assert_eq!(bytes.len(), 4);
assert_eq!(decode_number(&bytes, NativeType::Float), 1.5);
let bytes = encode_number(1.5, NativeType::Double);
assert_eq!(bytes.len(), 8);
assert_eq!(decode_number(&bytes, NativeType::Double), 1.5);
}
#[test]
fn a_text_goes_out_and_comes_back() {
let bytes = encode("hello", NativeType::Str);
assert_eq!(bytes.len(), 12);
assert_eq!(decode(&bytes, NativeType::Str), "hello");
let bytes = encode("hello", NativeType::AStr);
assert_eq!(bytes.len(), 6);
assert_eq!(decode(&bytes, NativeType::AStr), "hello");
}
#[test]
fn a_text_ends_at_the_first_nul() {
let bytes = encode("hello", NativeType::AStr);
let mut longer = bytes.clone();
longer.extend_from_slice(b"world");
assert_eq!(decode(&longer, NativeType::AStr), "hello");
}
#[test]
fn a_type_is_read_out_of_its_string() {
assert_eq!(parse_type("Int"), Some((NativeType::Int, false)));
assert_eq!(parse_type("Int64*"), Some((NativeType::Int64, true)));
assert_eq!(parse_type("Int64P"), Some((NativeType::Int64, true)));
assert_eq!(parse_type("UInt"), Some((NativeType::UInt, false)));
assert_eq!(parse_type("UPtr"), Some((NativeType::UPtr, false)));
assert_eq!(parse_type("nope"), None);
assert_eq!(parse_type("Bool"), None);
assert_eq!(parse_type("Byte"), None);
}
#[test]
fn the_target_is_read_out_of_its_string() {
assert_eq!(
split_target("kernel32\\GetLastError"),
("kernel32".into(), "GetLastError".into())
);
assert_eq!(
split_target("GetLastError"),
("".into(), "GetLastError".into())
);
assert_eq!(
split_target("C:\\dir\\file.dll\\Func"),
("C:\\dir\\file.dll".into(), "Func".into())
);
}
}