use crate::hts_ffi::{BCF_BT_CHAR, BCF_BT_FLOAT, BCF_BT_INT16, BCF_BT_INT32, BCF_BT_INT8};
use crate::TypedValue;
use std::borrow::Cow;
impl<'a> TypedValue<'a> {
pub fn try_get_string(&self) -> Option<Cow<str>> {
if let Self::SStr(raw) = self {
return Some(String::from_utf8_lossy(raw));
}
None
}
fn cast_and_pack<T: Sized + 'static, F: Fn(&'a [T]) -> TypedValue<'a>>(
ptr: *const u8,
size: usize,
pack: F,
) -> TypedValue<'a> {
let slice =
unsafe { std::slice::from_raw_parts(ptr as *const T, size / std::mem::size_of::<T>()) };
pack(slice)
}
pub(crate) fn from_type_and_raw_data(type_code: i32, ptr: *const u8, nbytes: u32) -> Self {
use TypedValue::*;
let nbytes = nbytes as usize;
match type_code as u32 {
BCF_BT_CHAR => Self::cast_and_pack::<u8, _>(ptr, nbytes, SStr),
BCF_BT_FLOAT => Self::cast_and_pack(ptr, nbytes, F),
BCF_BT_INT8 => Self::cast_and_pack(ptr, nbytes, I8),
BCF_BT_INT16 => Self::cast_and_pack(ptr, nbytes, I16),
BCF_BT_INT32 => Self::cast_and_pack(ptr, nbytes, I32),
_ => Null,
}
}
}