ion_c_sys/
string.rs

1// Copyright Amazon.com, Inc. or its affiliates.
2
3//! Provides higher-level APIs for borrowing `str` slices safely from Ion C.
4
5use std::marker::PhantomData;
6use std::ops::Deref;
7
8use crate::*;
9
10/// Represents a `str` slice that is borrowed from some source.
11///
12/// This struct provides the mutable borrowing context for the given slice to avoid
13/// destructive APIs from being called from the referent.
14#[derive(Debug, Copy, Clone)]
15pub struct StrSliceRef<'a> {
16    string: &'a str,
17    /// Placeholder to tie our lifetime back to the source of the data as a mutable borrow.
18    referent: PhantomData<&'a mut u8>,
19}
20
21impl<'a> StrSliceRef<'a> {
22    /// Creates a new reference to an `ION_STRING` mutably borrowed from `src`.
23    #[inline]
24    pub fn new<T>(_src: &'a mut T, string: &'a str) -> Self {
25        StrSliceRef {
26            string,
27            referent: PhantomData::default(),
28        }
29    }
30
31    /// Convenience method to get the underlying `&str`.
32    #[inline]
33    pub fn as_str(&self) -> &str {
34        self.string
35    }
36}
37
38impl Deref for StrSliceRef<'_> {
39    type Target = str;
40
41    #[inline]
42    fn deref(&self) -> &Self::Target {
43        self.string
44    }
45}
46
47impl AsRef<str> for StrSliceRef<'_> {
48    fn as_ref(&self) -> &str {
49        self.string
50    }
51}
52
53/// Represents a slice of `str` slices that are borrowed from some source.
54///
55/// This struct provides the mutable borrowing context for the given slice to avoid
56/// destructive APIs from being called from the referent.
57#[derive(Debug, Clone)]
58pub struct StrSlicesRef<'a> {
59    /// holder for the slices--we don't currently have built in storage for the array itself
60    /// from Ion C, so we hold it here in a `Vec`.
61    strs: Vec<&'a str>,
62
63    /// Placeholder to tie our lifetime back to the source of the data.
64    referent: PhantomData<&'a mut u8>,
65}
66
67impl<'a> StrSlicesRef<'a> {
68    #[inline]
69    pub fn new<T>(_src: &'a mut T, strs: Vec<&'a str>) -> Self {
70        Self {
71            strs,
72            referent: Default::default(),
73        }
74    }
75
76    /// Convenience method to get the underlying slice of `&str`.
77    #[inline]
78    pub fn as_slice(&self) -> &[&str] {
79        self.strs.as_slice()
80    }
81}
82
83impl<'a> Deref for StrSlicesRef<'a> {
84    type Target = [&'a str];
85
86    #[inline]
87    fn deref(&self) -> &Self::Target {
88        self.strs.as_slice()
89    }
90}
91
92impl<'a> AsRef<[&'a str]> for StrSlicesRef<'a> {
93    fn as_ref(&self) -> &[&'a str] {
94        self.strs.as_slice()
95    }
96}