Skip to content

Commit

Permalink
Add serialize/deserialize example.
Browse files Browse the repository at this point in the history
  • Loading branch information
gz committed Mar 1, 2023
1 parent 9778922 commit 2d13588
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
50 changes: 45 additions & 5 deletions examples/serialize_deserialize.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,51 @@
use raw_cpuid::CpuId;
//! An example that serializes CpuId state, deserializes it back and passes it to a
//! CpuId instance with a custom reader.
//!
//! Run using:
//! `cargo run --features serialize --features serde_json --example serialize_deserialize`

fn take_cpuid(cpuid: CpuId) -> CpuId {
cpuid
use raw_cpuid::{CpuId, CpuIdReader, CpuIdResult};
use std::collections::HashMap;

#[derive(Clone)]
struct HashMapCpuIdReader {
ht: HashMap<u64, CpuIdResult>,
}

impl CpuIdReader for HashMapCpuIdReader {
fn cpuid2(&self, eax: u32, ecx: u32) -> CpuIdResult {
let key = (eax as u64) << u32::BITS | ecx as u64;
self.ht
.get(&key)
.unwrap_or(&CpuIdResult {
eax: 0,
ebx: 0,
ecx: 0,
edx: 0,
})
.clone()
}
}

fn main() {
let cpuid = CpuId::new();
let mut ht = HashMap::new();
ht.insert(
0x00000000_00000000u64,
CpuIdResult {
eax: 0x00000020,
ebx: 0x756e6547,
ecx: 0x6c65746e,
edx: 0x49656e69,
},
);

}
// Serialize to JSON and back
let cpuid_as_json = serde_json::to_string(&ht).unwrap();
let deserialized_ht: HashMap<u64, CpuIdResult> = serde_json::from_str(&cpuid_as_json).unwrap();

// Create a CpuId instance with a custom reader
let cpuid = CpuId::with_cpuid_reader(HashMapCpuIdReader {
ht: deserialized_ht,
});
assert!(cpuid.get_vendor_info().unwrap().as_str() == "GenuineIntel");
}
11 changes: 10 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ impl<R: CpuIdReader> CpuId<R> {
///
/// This is useful for example when testing code or if we want to interpose
/// on the CPUID calls this library makes.
pub fn with_cpuid_fn(cpuid_fn: R) -> Self {
pub fn with_cpuid_reader(cpuid_fn: R) -> Self {
let vendor_leaf = cpuid_fn.cpuid1(EAX_VENDOR_INFO);
let extended_leaf = cpuid_fn.cpuid1(EAX_EXTENDED_FUNCTION_INFO);
CpuId {
Expand All @@ -358,6 +358,15 @@ impl<R: CpuIdReader> CpuId<R> {
}
}

/// See [`CpuId::with_cpuid_reader`].
///
/// # Note
/// This function will likely be deprecated in the future. Use the identical
/// `with_cpuid_reader` function instead.
pub fn with_cpuid_fn(cpuid_fn: R) -> Self {
CpuId::with_cpuid_reader(cpuid_fn)
}

/// Check if a non extended leaf (`val`) is supported.
fn leaf_is_supported(&self, val: u32) -> bool {
// Exclude reserved functions/leafs on AMD
Expand Down

0 comments on commit 2d13588

Please sign in to comment.