iceoryx2_bb_container/
semantic_string.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// Copyright (c) 2023 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache Software License 2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
// which is available at https://opensource.org/licenses/MIT.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! The [`SemanticString`](crate::semantic_string::SemanticString) is a trait for
//! [`FixedSizeByteString`](crate::byte_string::FixedSizeByteString) to create
//! strong string types with semantic content contracts. They can be created
//! with the help of the [`semantic_string`](crate::semantic_string!) macro.
//!
//! # Example, create a string that can contain a posix group name
//!
//! ```
//! pub use iceoryx2_bb_container::semantic_string::SemanticString;
//!
//! use core::hash::{Hash, Hasher};
//! use iceoryx2_bb_container::semantic_string;
//!
//! const GROUP_NAME_LENGTH: usize = 31;
//! semantic_string! {
//!   // Name of the type
//!   name: GroupName,
//!   // The underlying capacity of the FixedSizeByteString
//!   capacity: GROUP_NAME_LENGTH,
//!   // Callable that shall return true when the provided string contains invalid content
//!   invalid_content: |string: &[u8]| {
//!     if string.is_empty() {
//!         // group names are not allowed to be empty
//!         return true;
//!     }
//!
//!     // group names are not allowed to start with a number or -
//!     matches!(string[0], b'-' | b'0'..=b'9')
//!   },
//!   // Callable that shall return true when the provided string contains invalid characters
//!   invalid_characters: |string: &[u8]| {
//!     for value in string {
//!         match value {
//!             // only non-capital letters, numbers and - is allowed
//!             b'a'..=b'z' | b'0'..=b'9' | b'-' => (),
//!             _ => return true,
//!         }
//!     }
//!
//!     false
//!   },
//!   // When a SemanticString has multiple representations of the same semantic content, this
//!   // callable shall convert the content to a uniform representation.
//!   // Example: The path to `/tmp` can be also expressed as `/tmp/` or `////tmp////`
//!   normalize: |this: &GroupName| {
//!       *this
//!   }
//! }
//! ```

use crate::byte_string::FixedSizeByteStringModificationError;
use crate::byte_string::{as_escaped_string, strnlen, FixedSizeByteString};
use iceoryx2_bb_log::fail;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::ops::Deref;

/// Failures that can occur when a [`SemanticString`] is created or modified
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SemanticStringError {
    /// The modification would lead to a [`SemanticString`] with invalid content.
    InvalidContent,
    /// The added content would exceed the maximum capacity of the [`SemanticString`]
    ExceedsMaximumLength,
}

impl From<FixedSizeByteStringModificationError> for SemanticStringError {
    fn from(_value: FixedSizeByteStringModificationError) -> Self {
        SemanticStringError::ExceedsMaximumLength
    }
}

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

impl std::error::Error for SemanticStringError {}

#[doc(hidden)]
pub mod internal {
    use super::*;

    pub trait SemanticStringAccessor<const CAPACITY: usize> {
        unsafe fn new_empty() -> Self;
        unsafe fn get_mut_string(&mut self) -> &mut FixedSizeByteString<CAPACITY>;
        fn is_invalid_content(string: &[u8]) -> bool;
        fn does_contain_invalid_characters(string: &[u8]) -> bool;
    }
}

/// Trait that defines the methods a [`FixedSizeByteString`] with context semantics, a
/// [`SemanticString`] shares. A new [`SemanticString`] can be created with the [`crate::semantic_string!`]
/// macro. For the usage, see [`mod@crate::semantic_string`].
pub trait SemanticString<const CAPACITY: usize>:
    internal::SemanticStringAccessor<CAPACITY>
    + Debug
    + Display
    + Sized
    + Deref<Target = [u8]>
    + PartialEq
    + Eq
    + Hash
{
    /// Returns a reference to the underlying [`FixedSizeByteString`]
    fn as_string(&self) -> &FixedSizeByteString<CAPACITY>;

    /// Creates a new content. If it contains invalid characters or exceeds the maximum supported
    /// length of the system or contains illegal strings it fails.
    fn new(value: &[u8]) -> Result<Self, SemanticStringError> {
        let msg = "Unable to create SemanticString";
        let origin = "SemanticString::new()";

        let mut new_self =
            unsafe { <Self as internal::SemanticStringAccessor<CAPACITY>>::new_empty() };
        fail!(from origin, when new_self.push_bytes(value),
            "{} due to an invalid value \"{}\".", msg, as_escaped_string(value));

        Ok(new_self)
    }

    /// Creates a new content but does not verify that it does not contain invalid characters.
    ///
    /// # Safety
    ///
    ///   * The slice must contain only valid characters.
    ///   * The slice must have a length that is less or equal CAPACITY
    ///   * The slice must not contain invalid UTF-8 characters
    ///
    unsafe fn new_unchecked(bytes: &[u8]) -> Self;

    /// Creates a new content from a given ptr. The user has to ensure that it is null-terminated.
    ///
    /// # Safety
    ///
    ///   * The pointer must be '\0' (null) terminated
    ///   * The pointer must be valid and non-null
    ///   * The contents must have a length that is less or equal CAPACITY
    ///   * The contents must not contain invalid UTF-8 characters
    ///
    unsafe fn from_c_str(ptr: *const std::ffi::c_char) -> Result<Self, SemanticStringError> {
        Self::new(std::slice::from_raw_parts(
            ptr.cast(),
            strnlen(ptr, CAPACITY + 1),
        ))
    }

    /// Returns the contents as a slice
    fn as_bytes(&self) -> &[u8] {
        self.as_string().as_bytes()
    }

    /// Returns a zero terminated slice of the underlying bytes
    fn as_c_str(&self) -> *const std::ffi::c_char {
        self.as_string().as_c_str()
    }

    /// Returns the capacity of the file system type
    fn capacity(&self) -> usize {
        self.as_string().capacity()
    }

    /// Returns true when the string is full, otherwise false
    fn is_full(&self) -> bool {
        self.as_string().is_full()
    }

    /// Returns true when the string is empty, otherwise false
    fn is_empty(&self) -> bool {
        self.as_string().is_empty()
    }

    /// Returns the length of the string
    fn len(&self) -> usize {
        self.as_string().len()
    }

    /// Inserts a single byte at a specific position. When the capacity is exceeded, the byte is an
    /// illegal character or the content would result in an illegal content it fails.
    fn insert(&mut self, idx: usize, byte: u8) -> Result<(), SemanticStringError> {
        self.insert_bytes(idx, &[byte; 1])
    }

    /// Inserts a byte slice at a specific position. When the capacity is exceeded, the byte slice contains
    /// illegal characters or the content would result in an illegal content it fails.
    fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) -> Result<(), SemanticStringError> {
        let msg = "Unable to insert byte string";
        fail!(from self, when unsafe { self.get_mut_string().insert_bytes(idx, bytes) },
                with SemanticStringError::ExceedsMaximumLength,
                    "{} \"{}\" since it would exceed the maximum allowed length of {}.",
                        msg, as_escaped_string(bytes), CAPACITY);

        if Self::is_invalid_content(self.as_bytes()) {
            unsafe { self.get_mut_string().remove_range(idx, bytes.len()) };
            fail!(from self, with SemanticStringError::InvalidContent,
                "{} \"{}\" since it would result in an illegal content.",
                msg, as_escaped_string(bytes));
        }

        Ok(())
    }

    /// Adds bytes to the string without checking if they only contain valid characters or
    /// would result in a valid result.
    ///
    /// # Safety
    ///
    ///   * The user must ensure that the bytes contain only valid characters.
    ///   * The user must ensure that the result, after the bytes were added, is valid.
    ///   * The slice must have a length that is less or equal CAPACITY
    ///   * The slice is not contain invalid UTF-8 characters
    ///
    unsafe fn insert_bytes_unchecked(&mut self, idx: usize, bytes: &[u8]);

    /// Normalizes the string. This function is used as basis for [`core::hash::Hash`] and
    /// [`PartialEq`]. Normalizing a [`SemanticString`] means to bring it to some format so that it
    /// contains still the same semantic content but in an uniform way so that strings, with the
    /// same semantic content but different representation compare as equal.
    fn normalize(&self) -> Self;

    /// Removes the last character. If the string is empty it returns [`None`].
    /// If the removal would create an illegal content it fails.
    fn pop(&mut self) -> Result<Option<u8>, SemanticStringError> {
        if self.len() == 0 {
            return Ok(None);
        }

        Ok(Some(self.remove(self.len() - 1)?))
    }

    /// Adds a single byte at the end. When the capacity is exceeded, the byte is an
    /// illegal character or the content would result in an illegal content it fails.
    fn push(&mut self, byte: u8) -> Result<(), SemanticStringError> {
        self.insert(self.len(), byte)
    }

    /// Adds a byte slice at the end. When the capacity is exceeded, the byte slice contains
    /// illegal characters or the content would result in an illegal content it fails.
    fn push_bytes(&mut self, bytes: &[u8]) -> Result<(), SemanticStringError> {
        self.insert_bytes(self.len(), bytes)
    }

    /// Removes a byte at a specific position and returns it.
    /// If the removal would create an illegal content it fails.
    fn remove(&mut self, idx: usize) -> Result<u8, SemanticStringError> {
        let value = unsafe { self.get_mut_string().remove(idx) };

        if Self::is_invalid_content(self.as_bytes()) {
            unsafe { self.get_mut_string().insert(idx, value).unwrap() };
            fail!(from self, with SemanticStringError::InvalidContent,
                "Unable to remove character at position {} since it would result in an illegal content.",
                idx);
        }

        Ok(value)
    }

    /// Removes a range.
    /// If the removal would create an illegal content it fails.
    fn remove_range(&mut self, idx: usize, len: usize) -> Result<(), SemanticStringError> {
        let mut temp = *self.as_string();
        temp.remove_range(idx, len);
        if Self::is_invalid_content(temp.as_bytes()) {
            fail!(from self, with SemanticStringError::InvalidContent,
                "Unable to remove range from {} with lenght {} since it would result in the illegal content \"{}\".",
                    idx, len, temp);
        }

        unsafe { self.get_mut_string().remove_range(idx, len) };
        Ok(())
    }

    /// Removes all bytes which satisfy the provided clojure f.
    /// If the removal would create an illegal content it fails.
    fn retain<F: FnMut(u8) -> bool>(&mut self, f: F) -> Result<(), SemanticStringError> {
        let mut temp = *self.as_string();
        let f = temp.retain_impl(f);

        if Self::is_invalid_content(temp.as_bytes()) {
            fail!(from self, with SemanticStringError::InvalidContent,
                "Unable to retain characters from string since it would result in the illegal content \"{}\".",
                temp);
        }

        unsafe { self.get_mut_string().retain(f) };
        Ok(())
    }

    /// Removes a prefix. If the prefix does not exist it returns false. If the removal would lead
    /// to an invalid string content it fails and returns [`SemanticStringError::InvalidContent`].
    /// After a successful removal it returns true.
    fn strip_prefix(&mut self, bytes: &[u8]) -> Result<bool, SemanticStringError> {
        let mut temp = *self.as_string();
        if !temp.strip_prefix(bytes) {
            return Ok(false);
        }

        if Self::is_invalid_content(temp.as_bytes()) {
            let mut prefix = FixedSizeByteString::<123>::new();
            unsafe { prefix.insert_bytes_unchecked(0, bytes) };
            fail!(from self, with SemanticStringError::InvalidContent,
                "Unable to strip prefix \"{}\" from string since it would result in the illegal content \"{}\".",
                prefix, temp);
        }

        unsafe { self.get_mut_string().strip_prefix(bytes) };

        Ok(true)
    }

    /// Removes a suffix. If the suffix does not exist it returns false. If the removal would lead
    /// to an invalid string content it fails and returns [`SemanticStringError::InvalidContent`].
    /// After a successful removal it returns true.
    fn strip_suffix(&mut self, bytes: &[u8]) -> Result<bool, SemanticStringError> {
        let mut temp = *self.as_string();
        if !temp.strip_suffix(bytes) {
            return Ok(false);
        }

        if Self::is_invalid_content(temp.as_bytes()) {
            let mut prefix = FixedSizeByteString::<123>::new();
            unsafe { prefix.insert_bytes_unchecked(0, bytes) };
            fail!(from self, with SemanticStringError::InvalidContent,
                "Unable to strip prefix \"{}\" from string since it would result in the illegal content \"{}\".",
                prefix, temp);
        }

        unsafe { self.get_mut_string().strip_suffix(bytes) };

        Ok(true)
    }

    /// Truncates the string to new_len.
    fn truncate(&mut self, new_len: usize) -> Result<(), SemanticStringError> {
        let mut temp = *self.as_string();
        temp.truncate(new_len);

        if Self::is_invalid_content(temp.as_bytes()) {
            fail!(from self, with SemanticStringError::InvalidContent,
                "Unable to truncate characters to {} since it would result in the illegal content \"{}\".",
                new_len, temp);
        }

        unsafe { self.get_mut_string().truncate(new_len) };
        Ok(())
    }
}

/// Helper macro to create a new [`SemanticString`]. Usage example can be found here:
/// [`mod@crate::semantic_string`].
#[macro_export(local_inner_macros)]
macro_rules! semantic_string {
    {$(#[$documentation:meta])*
     /// Name of the struct
     name: $string_name:ident,
     /// Capacity of the underlying FixedSizeByteString
     capacity: $capacity:expr,
     /// Callable that gets a [`&[u8]`] as input and shall return true when the slice contains
     /// invalid content.
     invalid_content: $invalid_content:expr,
     /// Callable that gets a [`&[u8]`] as input and shall return true when the slice contains
     /// invalid characters.
     invalid_characters: $invalid_characters:expr,
     /// Normalizes the content. Required when the same semantical content has multiple
     /// representations like paths for instance (`/tmp` == `/tmp/`)
     normalize: $normalize:expr} => {
        $(#[$documentation])*
        #[derive(Debug, Clone, Copy, Eq)]
        pub struct $string_name {
            value: iceoryx2_bb_container::byte_string::FixedSizeByteString<$capacity>
        }

        // BEGIN: serde
        pub(crate) mod VisitorType {
            pub(crate) struct $string_name;
        }

        impl<'de> serde::de::Visitor<'de> for VisitorType::$string_name {
            type Value = $string_name;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a string containing the service name")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                match $string_name::new(v.as_bytes()) {
                    Ok(v) => Ok(v),
                    Err(v) => Err(E::custom(std::format!("invalid {} provided {:?}.", std::stringify!($string_name), v))),
                }
            }
        }

        impl<'de> serde::Deserialize<'de> for $string_name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                deserializer.deserialize_str(VisitorType::$string_name)
            }
        }

        impl serde::Serialize for $string_name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(std::str::from_utf8(self.as_bytes()).unwrap())
            }
        }
        // END: serde

        impl iceoryx2_bb_container::semantic_string::SemanticString<$capacity> for $string_name {
            fn as_string(&self) -> &iceoryx2_bb_container::byte_string::FixedSizeByteString<$capacity> {
                &self.value
            }

            fn normalize(&self) -> Self {
                $normalize(self)
            }

            unsafe fn new_unchecked(bytes: &[u8]) -> Self {
                Self {
                    value: iceoryx2_bb_container::byte_string::FixedSizeByteString::new_unchecked(bytes),
                }
            }

            unsafe fn insert_bytes_unchecked(&mut self, idx: usize, bytes: &[u8]) {
                self.value.insert_bytes_unchecked(idx, bytes);
            }
        }

        impl $string_name {
            /// Returns the maximum length of [`$string`]
            pub const fn max_len() -> usize {
                $capacity
            }
        }

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

        impl Hash for $string_name {
            fn hash<H: Hasher>(&self, state: &mut H) {
                self.normalize().as_bytes().hash(state)
            }
        }

        impl From<$string_name> for String {
            fn from(value: $string_name) -> String {
                // SAFETY: It is ensured that the semantic string contains only valid utf-8 strings
                unsafe { String::from_utf8_unchecked(value.as_bytes().to_vec()) }
            }
        }

        impl From<&$string_name> for String {
            fn from(value: &$string_name) -> String {
                // SAFETY: It is ensured that the semantic string contains only valid utf-8 strings
                unsafe { String::from_utf8_unchecked(value.as_bytes().to_vec()) }
            }
        }

        impl std::convert::TryFrom<&str> for $string_name {
            type Error = iceoryx2_bb_container::semantic_string::SemanticStringError;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::new(value.as_bytes())
            }
        }

        impl PartialEq<$string_name> for $string_name {
            fn eq(&self, other: &$string_name) -> bool {
                *self.normalize().as_bytes() == *other.normalize().as_bytes()
            }
        }

        impl PartialEq<&[u8]> for $string_name {
            fn eq(&self, other: &&[u8]) -> bool {
                let other = match $string_name::new(other) {
                    Ok(other) => other,
                    Err(_) => return false,
                };

                *self == other
            }
        }

        impl PartialEq<&[u8]> for &$string_name {
            fn eq(&self, other: &&[u8]) -> bool {
                let other = match $string_name::new(other) {
                    Ok(other) => other,
                    Err(_) => return false,
                };

                **self == other
            }
        }

        impl<const CAPACITY: usize> PartialEq<[u8; CAPACITY]> for $string_name {
            fn eq(&self, other: &[u8; CAPACITY]) -> bool {
                let other = match $string_name::new(other) {
                    Ok(other) => other,
                    Err(_) => return false,
                };

                *self == other
            }
        }

        impl<const CAPACITY: usize> PartialEq<&[u8; CAPACITY]> for $string_name {
            fn eq(&self, other: &&[u8; CAPACITY]) -> bool {
                let other = match $string_name::new(*other) {
                    Ok(other) => other,
                    Err(_) => return false,
                };

                *self == other
            }
        }

        impl std::ops::Deref for $string_name {
            type Target = [u8];

            fn deref(&self) -> &Self::Target {
                self.value.as_bytes()
            }
        }

        impl iceoryx2_bb_container::semantic_string::internal::SemanticStringAccessor<$capacity> for $string_name {
            unsafe fn new_empty() -> Self {
                Self {
                    value: iceoryx2_bb_container::byte_string::FixedSizeByteString::new(),
                }
            }

            unsafe fn get_mut_string(&mut self) -> &mut iceoryx2_bb_container::byte_string::FixedSizeByteString<$capacity> {
                &mut self.value
            }

            fn is_invalid_content(string: &[u8]) -> bool {
                if Self::does_contain_invalid_characters(string) {
                    return true;
                }

                $invalid_content(string)
            }

            fn does_contain_invalid_characters(string: &[u8]) -> bool {
                if core::str::from_utf8(string).is_err() {
                    return true;
                }

                $invalid_characters(string)
            }
        }

    };
}