Skip to content
Snippets Groups Projects
Commit a3c0243e authored by Per Lindgren's avatar Per Lindgren
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
/target
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "log-0"
version = "0.1.0"
[package]
name = "log-0"
version = "0.1.0"
authors = ["Per Lindgren <per.lindgren@ltu.se>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
use std::any::{Any, TypeId};
use std::convert::TryInto;
use std::fmt::Debug;
use std::mem::size_of;
use std::mem::transmute;
// log data and and move write pointer forward
fn log<T: Sized + Any>(s: &T, v: &mut [u8], p: &mut usize) {
let type_id = TypeId::of::<T>();
let size = size_of::<T>();
// store type_id
let bytes: [u8; 8] = unsafe { transmute(type_id) };
v[*p..*p + 8].copy_from_slice(&bytes);
*p += 8;
// store data
let view = s as *const _ as *const u8;
let slice = unsafe { std::slice::from_raw_parts(view, size) };
v[*p..*p + size].copy_from_slice(slice);
*p += size;
}
// helper to expand data and move read pointer forward
fn exp2<T>(v: &[u8], p: &mut usize)
where
T: Debug,
{
let size = size_of::<T>();
let data: &T = unsafe { transmute(&v[*p] as *const _ as *const T) };
println!("{:?}", data);
*p += size;
}
// expand data and move read pointer forward
fn exp(v: &[u8], p: &mut usize) {
let bytes: &[u8; 8] = v[*p..*p + 8].try_into().unwrap();
let type_id: &u64 = unsafe { transmute(bytes) };
let type_id: &TypeId = unsafe { transmute(type_id) };
*p += 8;
if *type_id == TypeId::of::<T1>() {
exp2::<T1>(v, p);
} else if *type_id == TypeId::of::<T2>() {
exp2::<T2>(v, p);
} else {
unreachable!();
}
}
#[derive(Debug)]
#[repr(C)]
struct T1 {
x: i32,
y: i32,
}
#[derive(Debug)]
#[repr(C)]
struct T2 {
y: i64,
}
fn main() {
let mut v = [0u8; 256];
let mut w = 0;
// example log two variables
let t1 = T1 { x: 72, y: 52 };
let t2 = T2 { y: 112 };
println!("{:?}", t1);
println!("{:?}", t2);
log(&t1, &mut v, &mut w);
log(&t2, &mut v, &mut w);
// example expand the logged data
let mut r = 0;
exp(&v, &mut r);
exp(&v, &mut r);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment