micromegas_tracing/
static_string_ref.rs

1//! StaticStringRef points to a string dependency keeping track of the codec.
2//! Necessary for unreal instrumentation where ansi and wide strings can coexist.
3//! In cases where the event format does not have to be compatible with unreal, StringId can be used.
4use micromegas_transit::{
5    Member, StaticStringDependency, UserDefinedType, prelude::*, string_codec::StringCodec,
6};
7use std::{
8    hash::{Hash, Hasher},
9    sync::Arc,
10};
11
12#[derive(Eq, PartialEq, Debug, Clone)]
13pub struct StaticStringRef {
14    pub ptr: u64,
15    pub len: u32,
16    pub codec: StringCodec,
17}
18
19impl Hash for StaticStringRef {
20    fn hash<H: Hasher>(&self, state: &mut H) {
21        self.ptr.hash(state);
22    }
23}
24
25impl Reflect for StaticStringRef {
26    fn reflect() -> UserDefinedType {
27        lazy_static::lazy_static! {
28            static ref TYPE_NAME: Arc<String> = Arc::new("StaticStringRef".into());
29            static ref ID: Arc<String> = Arc::new("id".into());
30        }
31        UserDefinedType {
32            name: TYPE_NAME.clone(),
33            size: std::mem::size_of::<Self>(),
34            members: vec![Member {
35                name: ID.clone(),
36                type_name: "usize".to_string(),
37                offset: memoffset::offset_of!(Self, ptr),
38                size: std::mem::size_of::<*const u8>(),
39                is_reference: true,
40            }],
41            is_reference: true,
42            secondary_udts: vec![],
43        }
44    }
45}
46
47impl StaticStringRef {
48    pub fn id(&self) -> u64 {
49        self.ptr
50    }
51
52    pub fn into_dependency(&self) -> StaticStringDependency {
53        StaticStringDependency {
54            codec: self.codec,
55            len: self.len,
56            ptr: self.ptr as *const u8,
57        }
58    }
59
60    pub fn as_str(&self) -> &str {
61        unsafe {
62            let slice = std::slice::from_raw_parts(self.ptr as *const u8, self.len as usize);
63            std::str::from_utf8_unchecked(slice)
64        }
65    }
66}
67
68impl std::convert::From<&'static str> for StaticStringRef {
69    fn from(src: &'static str) -> Self {
70        Self {
71            len: src.len() as u32,
72            ptr: src.as_ptr() as u64,
73            codec: StringCodec::Utf8,
74        }
75    }
76}