iceoryx2-bb-container 0.9.0

iceoryx2: IPC shared memory compatible containers
Documentation
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
// Copyright (c) 2025 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

//! Relocatable (inter-process shared memory compatible) string implementations.
//!
//! The [`StaticString`](crate::string::StaticString) has a fixed capacity defined at compile time.
//! It is memory-layout compatible to the C++ counterpart in the iceoryx2-bb-container C++ library
//! and can be used for zero-copy cross-language communication.
//!
//! # Example
//!
//! ```
//! # extern crate iceoryx2_bb_loggers;
//!
//! use iceoryx2_bb_container::string::*;
//!
//! const STRING_CAPACITY: usize = 123;
//!
//! let mut some_string = StaticString::<STRING_CAPACITY>::new();
//! some_string.push_bytes(b"hello").unwrap();
//! some_string.push('!' as u8).unwrap();
//! some_string.push('!' as u8).unwrap();
//!
//! println!("removed byte {:?}", some_string.remove(0));
//! ```

use alloc::format;
use core::str::FromStr;
use core::{
    cmp::Ordering,
    fmt::{Debug, Display},
    hash::Hash,
    mem::MaybeUninit,
    ops::{Deref, DerefMut},
};
use iceoryx2_bb_elementary_traits::atomic_copy::AtomicCopy;

use iceoryx2_bb_derive_macros::{PlacementDefault, ZeroCopySend};
use iceoryx2_bb_elementary::math::align_to;
use iceoryx2_bb_elementary_traits::placement_default::PlacementDefault;
use iceoryx2_bb_elementary_traits::zero_copy_send::ZeroCopySend;
use iceoryx2_log::fail;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Visitor};

use crate::string::{
    String, StringModificationError, as_escaped_string, internal::StringView, strnlen,
};

/// Variant of the [`String`] that has a compile-time fixed capacity and is
/// shared-memory compatible.
#[derive(PlacementDefault, ZeroCopySend, Clone, Copy)]
#[repr(C)]
pub struct StaticString<const CAPACITY: usize> {
    data: [MaybeUninit<u8>; CAPACITY],
    terminator: u8,
    len: u64,
}

unsafe impl<const CAPACITY: usize> AtomicCopy for StaticString<CAPACITY> {
    fn __for_each_field<F: FnMut(usize, usize)>(&self, base_offset: usize, callback: &mut F) {
        let aligned_base_offset = align_to::<Self>(base_offset);
        callback(
            aligned_base_offset + core::mem::offset_of!(Self, data),
            size_of::<u8>() * self.len(),
        );
        callback(
            aligned_base_offset + core::mem::offset_of!(Self, terminator),
            size_of::<u8>(),
        );
        callback(
            aligned_base_offset + core::mem::offset_of!(Self, len),
            size_of::<u64>(),
        );
    }
}

impl<const CAPACITY: usize> Serialize for StaticString<CAPACITY> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(core::str::from_utf8(self.as_bytes()).unwrap())
    }
}

struct StaticStringVisitor<const CAPACITY: usize>;

impl<const CAPACITY: usize> Visitor<'_> for StaticStringVisitor<CAPACITY> {
    type Value = StaticString<CAPACITY>;

    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
        formatter.write_str(&format!("a string with a length of at most {CAPACITY}"))
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        match StaticString::from_bytes(v.as_bytes()) {
            Ok(v) => Ok(v),
            Err(_) => Err(E::custom(format!(
                "the string exceeds the maximum length of {CAPACITY}"
            ))),
        }
    }
}

impl<'de, const CAPACITY: usize> Deserialize<'de> for StaticString<CAPACITY> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(StaticStringVisitor)
    }
}

unsafe impl<const CAPACITY: usize> Send for StaticString<CAPACITY> {}

impl<const CAPACITY: usize, const CAPACITY_OTHER: usize> PartialOrd<StaticString<CAPACITY_OTHER>>
    for StaticString<CAPACITY>
{
    fn partial_cmp(&self, other: &StaticString<CAPACITY_OTHER>) -> Option<Ordering> {
        self.as_bytes().partial_cmp(other.as_bytes())
    }
}

impl<const CAPACITY: usize> Ord for StaticString<CAPACITY> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_bytes().cmp(other.as_bytes())
    }
}

impl<const CAPACITY: usize> Hash for StaticString<CAPACITY> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        state.write(self.as_bytes())
    }
}

impl<const CAPACITY: usize> Deref for StaticString<CAPACITY> {
    type Target = [u8];

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

impl<const CAPACITY: usize> DerefMut for StaticString<CAPACITY> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_bytes()
    }
}

impl<const CAPACITY: usize, const OTHER_CAPACITY: usize> PartialEq<StaticString<OTHER_CAPACITY>>
    for StaticString<CAPACITY>
{
    fn eq(&self, other: &StaticString<OTHER_CAPACITY>) -> bool {
        *self.as_bytes() == *other.as_bytes()
    }
}

impl<const CAPACITY: usize> Eq for StaticString<CAPACITY> {}

impl<const CAPACITY: usize> PartialEq<&[u8]> for StaticString<CAPACITY> {
    fn eq(&self, other: &&[u8]) -> bool {
        *self.as_bytes() == **other
    }
}

impl<const CAPACITY: usize> PartialEq<&str> for StaticString<CAPACITY> {
    fn eq(&self, other: &&str) -> bool {
        *self.as_bytes() == *other.as_bytes()
    }
}

impl<const CAPACITY: usize> PartialEq<StaticString<CAPACITY>> for &str {
    fn eq(&self, other: &StaticString<CAPACITY>) -> bool {
        *self.as_bytes() == *other.as_bytes()
    }
}

impl<const CAPACITY: usize, const OTHER_CAPACITY: usize> PartialEq<[u8; OTHER_CAPACITY]>
    for StaticString<CAPACITY>
{
    fn eq(&self, other: &[u8; OTHER_CAPACITY]) -> bool {
        *self.as_bytes() == *other
    }
}

impl<const CAPACITY: usize, const OTHER_CAPACITY: usize> PartialEq<&[u8; OTHER_CAPACITY]>
    for StaticString<CAPACITY>
{
    fn eq(&self, other: &&[u8; OTHER_CAPACITY]) -> bool {
        *self.as_bytes() == **other
    }
}

impl<const CAPACITY: usize> Debug for StaticString<CAPACITY> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "StaticString<{}> {{ len: {}, data: \"{}\" }}",
            CAPACITY,
            self.len,
            as_escaped_string(self.as_bytes())
        )
    }
}

impl<const CAPACITY: usize> Display for StaticString<CAPACITY> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", as_escaped_string(self.as_bytes()))
    }
}

impl<const CAPACITY: usize> TryFrom<&str> for StaticString<CAPACITY> {
    type Error = StringModificationError;

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

impl<const CAPACITY: usize, const N: usize> TryFrom<&[u8; N]> for StaticString<CAPACITY> {
    type Error = StringModificationError;

    fn try_from(value: &[u8; N]) -> Result<Self, Self::Error> {
        Self::try_from(value.as_slice())
    }
}

impl<const CAPACITY: usize> TryFrom<&[u8]> for StaticString<CAPACITY> {
    type Error = StringModificationError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        if CAPACITY < value.len() {
            fail!(from "StaticString::from<&[u8]>()",
                with StringModificationError::InsertWouldExceedCapacity,
                "The provided string \"{}\" does not fit into the StaticString with capacity {}",
                as_escaped_string(value), CAPACITY);
        }

        let mut new_self = Self::new();
        new_self.push_bytes(value)?;
        Ok(new_self)
    }
}

impl<const CAPACITY: usize> Default for StaticString<CAPACITY> {
    fn default() -> Self {
        Self::new()
    }
}

impl<const CAPACITY: usize> StringView for StaticString<CAPACITY> {
    fn data(&self) -> &[MaybeUninit<u8>] {
        &self.data
    }

    unsafe fn data_mut(&mut self) -> &mut [MaybeUninit<u8>] {
        &mut self.data
    }

    unsafe fn set_len(&mut self, len: u64) {
        self.len = len
    }
}

impl<const CAPACITY: usize> FromStr for StaticString<CAPACITY> {
    type Err = StringModificationError;

    fn from_str(s: &str) -> Result<Self, StringModificationError> {
        Self::from_bytes(s.as_bytes())
    }
}

impl<const CAPACITY: usize> StaticString<CAPACITY> {
    /// Creates a new and empty [`StaticString`]
    pub const fn new() -> Self {
        let mut new_self = Self {
            len: 0,
            data: unsafe { MaybeUninit::uninit().assume_init() },
            terminator: 0,
        };
        new_self.data[0] = MaybeUninit::new(0);
        new_self
    }

    /// Creates a new [`StaticString`]. The user has to ensure that the string can hold the
    /// bytes.
    ///
    /// # Safety
    ///
    ///  * `bytes` len must be smaller or equal than [`StaticString::capacity()`]
    ///  * all unicode code points must be smaller 128 and not 0.
    ///
    pub const unsafe fn from_bytes_unchecked_restricted(bytes: &[u8], len: usize) -> Self {
        debug_assert!(bytes.len() <= CAPACITY);
        debug_assert!(len <= bytes.len());

        let mut new_self = Self::new();
        unsafe {
            core::ptr::copy_nonoverlapping(bytes.as_ptr(), new_self.data.as_mut_ptr().cast(), len);
            core::ptr::write::<u8>(new_self.data.as_mut_ptr().add(len).cast(), 0);
        }
        new_self.len = len as u64;
        new_self
    }

    /// Creates a new [`StaticString`]. The user has to ensure that the string can hold the
    /// bytes.
    ///
    /// # Safety
    ///
    ///  * `bytes` len must be smaller or equal than [`StaticString::capacity()`]
    ///  * all unicode code points must be smaller 128 and not 0.
    ///
    pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self {
        debug_assert!(bytes.len() <= CAPACITY);
        unsafe { Self::from_bytes_unchecked_restricted(bytes, bytes.len()) }
    }

    /// Creates a new [`StaticString`] from a byte slice
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, StringModificationError> {
        let mut new_self = Self::new();
        new_self.insert_bytes(0, bytes)?;

        Ok(new_self)
    }

    /// Creates a new [`StaticString`] from a byte slice. If the byte slice does not fit
    /// into the [`StaticString`] it will be truncated.
    pub fn from_bytes_truncated(bytes: &[u8]) -> Result<Self, StringModificationError> {
        let mut new_self = Self::new();
        new_self.insert_bytes(0, &bytes[0..core::cmp::min(bytes.len(), CAPACITY)])?;
        Ok(new_self)
    }

    /// Creates a new [`StaticString`] from a string slice. If the string slice does not fit
    /// into the [`StaticString`] it will be truncated.
    pub fn from_str_truncated(s: &str) -> Result<Self, StringModificationError> {
        Self::from_bytes_truncated(s.as_bytes())
    }

    /// Creates a new byte string from a given null-terminated string
    ///
    /// # Safety
    ///
    ///  * `ptr` must point to a valid memory position
    ///  * `ptr` must be '\0' (null) terminated
    ///
    pub unsafe fn from_c_str(
        ptr: *const core::ffi::c_char,
    ) -> Result<Self, StringModificationError> {
        let string_length = unsafe { strnlen(ptr, CAPACITY + 1) };
        if CAPACITY < string_length {
            return Err(StringModificationError::InsertWouldExceedCapacity);
        }

        Self::from_bytes(unsafe { core::slice::from_raw_parts(ptr.cast(), string_length) })
    }

    /// Returns the capacity of the [`StaticString`]
    pub const fn capacity() -> usize {
        CAPACITY
    }

    /// Returns a slice to the underlying bytes
    pub const fn as_bytes_const(&self) -> &[u8] {
        unsafe { core::slice::from_raw_parts(self.data.as_ptr().cast(), self.len as usize) }
    }
}

impl<const CAPACITY: usize> String for StaticString<CAPACITY> {
    fn capacity(&self) -> usize {
        CAPACITY
    }

    fn len(&self) -> usize {
        self.len as usize
    }
}

#[allow(missing_docs)]
pub struct StringMemoryLayoutMetrics {
    pub string_size: usize,
    pub string_alignment: usize,
    pub size_data: usize,
    pub offset_data: usize,
    pub size_len: usize,
    pub offset_len: usize,
    pub len_is_unsigned: bool,
}

trait _StringMemoryLayoutFieldLenInspection {
    fn is_unsigned(&self) -> bool;
}

impl _StringMemoryLayoutFieldLenInspection for u64 {
    fn is_unsigned(&self) -> bool {
        true
    }
}

impl StringMemoryLayoutMetrics {
    #[allow(missing_docs)]
    pub fn from_string<const CAPACITY: usize>(v: &StaticString<CAPACITY>) -> Self {
        StringMemoryLayoutMetrics {
            string_size: core::mem::size_of_val(v),
            string_alignment: core::mem::align_of_val(v),
            size_data: core::mem::size_of_val(&v.data) + core::mem::size_of_val(&v.terminator),
            offset_data: core::mem::offset_of!(StaticString<CAPACITY>, data),
            size_len: core::mem::size_of_val(&v.len),
            offset_len: core::mem::offset_of!(StaticString<CAPACITY>, len),
            len_is_unsigned: v.len.is_unsigned(),
        }
    }
}