ittapi/
string.rs

1use crate::util::access_sys_fn;
2use std::ffi::CString;
3
4/// String handles are ITT's mechanism for efficiently naming objects. See the [String Handle API]
5/// documentation for more information.
6///
7/// [String Handle API]:
8///     https://www.intel.com/content/www/us/en/develop/documentation/vtune-help/top/api-support/instrumentation-and-tracing-technology-apis/instrumentation-tracing-technology-api-reference/string-handle-api.html
9#[derive(PartialEq, Eq, Debug)]
10pub struct StringHandle(*mut ittapi_sys::__itt_string_handle);
11impl StringHandle {
12    /// Create a new string handle; repeated calls with the same `name` will return the same handle.
13    ///
14    /// ```
15    /// # use ittapi::StringHandle;
16    /// let a = StringHandle::new("test");
17    /// let b: StringHandle = "test".into();
18    /// assert_eq!(a, b);
19    /// ```
20    #[must_use]
21    pub fn new(name: &str) -> Self {
22        #[cfg(unix)]
23        let create_fn = access_sys_fn!(__itt_string_handle_create_ptr__3_0);
24        #[cfg(windows)]
25        let create_fn = access_sys_fn!(__itt_string_handle_createA_ptr__3_0);
26        let c_string =
27            CString::new(name).expect("unable to create a CString; does it contain a 0 byte?");
28        let handle = unsafe { create_fn(c_string.as_ptr()) };
29        Self(handle)
30    }
31
32    /// Use the `__itt_string_handle` pointer internally.
33    pub(crate) fn as_ptr(&self) -> *mut ittapi_sys::__itt_string_handle {
34        self.0
35    }
36}
37
38impl From<&str> for StringHandle {
39    fn from(name: &str) -> Self {
40        Self::new(name)
41    }
42}
43
44mod tests {
45    #[test]
46    fn with_dynamic_part_specified() {
47        // When INTEL_LIBITTNOTIFY64 is set in the environment, the static part of ittnotify will
48        // allocate; otherwise, if the dynamic part is not present, the pointer will be null.
49        let _env_path = scoped_env::ScopedEnv::remove("INTEL_LIBITTNOTIFY64");
50        let sh = super::StringHandle::new("test2");
51        assert!(sh.as_ptr().is_null());
52    }
53}