xcp_registry 0.1.0

Measurement and Calibration registry for XCP - pure Rust, no C dependency
Documentation
// Module mc_text
// 'static str version
// Warn on heap allocations
// Types:
//  McText - used for all text in the registry
//  McIdentifier - used for all named objects in the registry
// Immutable, as_str is &'static str
// May leak memory when converting from String

use std::ops::Deref;

use serde::Deserialize;
use serde::Serialize;

//-------------------------------------------------------------------------------------------------
// McText

/// Text with `'static` lifetime, e.g. a comment or a unit
/// Created from a `&'static str` without cost, created from a `String` the string is leaked
#[derive(Debug, Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize)]
pub struct McText(&'static str);

impl McText {
    /// Create an empty text
    pub fn empty() -> Self {
        McText("")
    }

    /// Create from a string literal
    pub fn new(s: &'static str) -> Self {
        McText(s)
    }

    /// Get the text as string slice
    pub fn as_str(&self) -> &'static str {
        self.0
    }

    /// Check if the text is empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Deref for McText {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}

impl std::fmt::Display for McText {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl<'de> Deserialize<'de> for McText {
    fn deserialize<D>(deserializer: D) -> Result<McText, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(McText::from(s))
    }
}

// From McText to &'static str, String
//-----------------------------------

impl From<McText> for &'static str {
    fn from(name: McText) -> &'static str {
        name.0
    }
}

impl From<McText> for String {
    fn from(t: McText) -> String {
        log::debug!("From<McText> to String: &'static str '{t}' to_string()");

        t.0.to_string()
    }
}

// From String, &'static str
//--------------------------

impl From<Option<&String>> for McText {
    fn from(s: Option<&String>) -> Self {
        if let Some(s) = s {
            log::trace!("From<String> to McText: Leak String '{s}' to &'static str");
            let s = s.clone().into_boxed_str();
            let s = Box::leak(s);

            McText(s)
        } else {
            McText::empty()
        }
    }
}

impl From<&String> for McText {
    fn from(s: &String) -> Self {
        log::trace!("From<String> to McText: Leak String '{s}' to &'static str");
        let s = s.clone().into_boxed_str();
        let s = Box::leak(s);

        McText(s)
    }
}

impl From<String> for McText {
    fn from(s: String) -> Self {
        log::trace!("From<String> to McText: Leak String '{s}' to &'static str");
        let s = s.into_boxed_str();
        let s = Box::leak(s);

        McText(s)
    }
}

impl From<&'static str> for McText {
    fn from(s: &'static str) -> Self {
        McText(s)
    }
}

// Eq
//--------------------------

impl PartialEq<&str> for McText {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<McText> for &str {
    fn eq(&self, other: &McText) -> bool {
        *self == other.0
    }
}

//-------------------------------------------------------------------------------------------------
// McIdentifier

/// Name of a registry object with `'static` lifetime
/// Only ASCII letters, digits, `_` and `.` are allowed, every other byte is replaced by `_`
/// Created from a valid `&'static str` without cost, otherwise the string is leaked
#[derive(Debug, Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize)]
pub struct McIdentifier(&'static str);

impl McIdentifier {
    /// Create an empty identifier
    pub fn empty() -> Self {
        McIdentifier("")
    }

    /// Create from a string literal, invalid characters are replaced by `_`
    pub fn new(s: &'static str) -> Self {
        s.into()
    }

    /// Get the identifier as string slice
    pub fn as_str(&self) -> &'static str {
        self.0
    }

    /// Check if the identifier is empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Deref for McIdentifier {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}

impl std::fmt::Display for McIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl<'de> Deserialize<'de> for McIdentifier {
    fn deserialize<D>(deserializer: D) -> Result<McIdentifier, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(McIdentifier::from(s))
    }
}

// From McIdentifier to &'static str, String
//-----------------------------------

impl From<McIdentifier> for &'static str {
    fn from(name: McIdentifier) -> &'static str {
        name.0
    }
}

impl From<McIdentifier> for String {
    fn from(t: McIdentifier) -> String {
        log::debug!("From<McIdentifier> to String: &'static str '{t}' to_string()");

        t.0.to_string()
    }
}

// From String, &'static str
//--------------------------

// Replace every byte which is not alphanumeric, an underscore or a dot with an underscore
fn to_identifier(s: &str) -> String {
    s.bytes()
        .map(|b| if b.is_ascii_alphanumeric() || b == b'_' || b == b'.' { char::from(b) } else { '_' })
        .collect()
}

fn check_identifier(s: &str) -> bool {
    // Convert the string into a mutable byte slice
    let bytes = s.as_bytes();
    for byte in bytes.iter() {
        // Check if the character is not alphanumeric or an underscore
        if !byte.is_ascii_alphanumeric() && *byte != b'_' && *byte != b'.' {
            log::warn!("Invalid identifier: {s}");
            return false; // Invalid identifier
        }
    }
    true // Valid identifier
}

impl From<String> for McIdentifier {
    fn from(s: String) -> Self {
        log::trace!("From<String> to McIdentifier: Leak String '{s}' to &'static str");
        let s = to_identifier(&s);
        let s = s.into_boxed_str();
        let s = Box::leak(s);

        McIdentifier(s)
    }
}

impl From<&'static str> for McIdentifier {
    fn from(s: &'static str) -> Self {
        if check_identifier(s) {
            McIdentifier(s)
        } else {
            // Replace invalid characters like From<String> does, this needs a leaked copy
            McIdentifier::from(s.to_string())
        }
    }
}

// Eq
//--------------------------

impl PartialEq<&str> for McIdentifier {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<McIdentifier> for &str {
    fn eq(&self, other: &McIdentifier) -> bool {
        *self == other.0
    }
}

//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Test module

#[cfg(test)]
mod mc_text_tests {

    use super::*;

    fn is_copy<T: Sized + Copy>() {}
    fn is_send<T: Sized + Send>() {}
    fn is_sync<T: Sized + Sync>() {}
    fn is_clone<T: Sized + Clone>() {}

    #[test]
    fn test_mc_text() {
        // Check markers
        is_sync::<McText>();
        is_copy::<McText>();
        is_send::<McText>();
        is_clone::<McText>();

        let t1 = McText::new("Hello");
        assert_eq!(t1.as_str(), "Hello");
        let t2 = t1;
        assert_eq!(t2.as_str(), "Hello");

        let t: McText = "Hello".into();
        assert_eq!(t, "Hello");

        let s1 = McText::from("String".to_string());
        let s2: &'static str = s1.as_str();
        assert!(s1 == s2);
        assert!(s2 == "String");

        let s3: McText = "String".into();
        assert_eq!(s3, "String");

        let s4 = McText::from("String".to_string());
        assert_eq!(s4, "String");
        let s5: String = s4.into();
        assert_eq!(s5, "String");

        let a = McText::new("A");
        let b = McText::new("B");
        assert!(a != b);
        assert!(a == "A");
        assert!(a < b)
    }

    #[test]
    fn test_mc_identifier() {
        // Check markers
        is_sync::<McIdentifier>();
        is_copy::<McIdentifier>();
        is_send::<McIdentifier>();
        is_clone::<McIdentifier>();

        let t1 = McIdentifier::new("Identifier");
        assert_eq!(t1.as_str(), "Identifier");
        let t2 = t1;
        assert_eq!(t2.as_str(), "Identifier");
        let t: McIdentifier = "Identifier".into();
        assert_eq!(t, "Identifier");

        // A literal with invalid characters is sanitized like a String
        let t3 = McIdentifier::new("Illegal Identifier");
        assert_eq!(t3.as_str(), "Illegal_Identifier");

        let s1 = McIdentifier::from("&Legal .Identifier ".to_string());
        assert_eq!(s1.as_str(), "_Legal_.Identifier_");
    }
}