abi_stable_derive/
composite_collections.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
//! Helper types for constructing strings and arrays composed of other strings and arrays.
//!
//! These datatypes are special-cased for small composite collections ,
//! whose indices fit in a u16.

use std::{
    borrow::Borrow,
    convert::TryFrom,
    fmt::{Debug, Display},
    marker::PhantomData,
    ops::{Add, Range},
};

use as_derive_utils::{return_syn_err, to_stream};

use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::ToTokens;

use crate::common_tokens::StartLenTokens;

/// A `{start:16,len:u16}` range.
pub type SmallStartLen = StartLen<u16>;

/// A `{start:N,len:N}` range.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub struct StartLen<N> {
    pub start: N,
    pub len: N,
}

impl StartLen<u16> {
    abi_stable_shared::declare_start_len_bit_methods! {}
}

impl<N> StartLen<N> {
    #[inline]
    pub(crate) fn from_start_len(start: usize, len: usize) -> Self
    where
        N: TryFrom<usize>,
        N::Error: Debug,
    {
        Self {
            start: N::try_from(start).unwrap(),
            len: N::try_from(len).unwrap(),
        }
    }

    #[inline]
    pub const fn new(start: N, len: N) -> Self {
        Self { start, len }
    }

    #[allow(dead_code)]
    pub(crate) fn into_range(self) -> Range<N>
    where
        N: Copy + Add<N, Output = N>,
    {
        self.start..(self.start + self.len)
    }

    #[inline]
    pub(crate) fn tokenizer(self, ctokens: &StartLenTokens) -> StartLenTokenizer<'_, N> {
        StartLenTokenizer {
            start: self.start,
            len: self.len,
            ctokens,
        }
    }
}

impl StartLen<u16> {
    pub const DUMMY: Self = Self {
        start: (1u16 << 15) + 1,
        len: (1u16 << 15) + 1,
    };

    pub const EMPTY: Self = Self { start: 0, len: 0 };

    /// The start of this range.
    #[inline]
    pub const fn start(self) -> usize {
        self.start as usize
    }

    #[inline]
    pub const fn len(self) -> usize {
        self.len as usize
    }

    /// Converts this StartLen to a u32.
    pub const fn to_u32(self) -> u32 {
        self.start as u32 | ((self.len as u32) << 16)
    }

    pub fn check_ident_length(&self, span: Span) -> Result<(), syn::Error> {
        if self.len > Self::IDENT_MAX_LEN {
            return_syn_err!(
                span,
                "Identifier is too long,it must be at most {} bytes.",
                Self::IDENT_MAX_LEN,
            );
        }
        Ok(())
    }
}

pub struct StartLenTokenizer<'a, N> {
    start: N,
    len: N,
    ctokens: &'a StartLenTokens,
}

impl<'a, N> ToTokens for StartLenTokenizer<'a, N>
where
    N: ToTokens,
{
    fn to_tokens(&self, ts: &mut TokenStream2) {
        use syn::token::{Colon2, Comma, Paren};

        let ct = self.ctokens;
        to_stream!(ts; ct.start_len,Colon2::default(),ct.new );
        Paren::default().surround(ts, |ts| {
            to_stream!(ts; self.start,Comma::default(),self.len );
        });
    }
}

///////////////////////////////////////////////////////////////////////

#[allow(dead_code)]
pub type SmallCompositeString = CompositeString<u16>;

/// A String-like type,
/// returning a `{start:16,len:u16}` range from methods that extend it.
pub struct CompositeString<N> {
    buffer: String,
    _integer: PhantomData<N>,
}

#[allow(dead_code)]
impl<N> CompositeString<N>
where
    N: TryFrom<usize>,
    N::Error: Debug,
{
    pub fn new() -> Self {
        Self {
            buffer: String::with_capacity(128),
            _integer: PhantomData,
        }
    }

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

    pub fn push_str(&mut self, s: &str) -> StartLen<N> {
        let start = self.len();
        self.buffer.push_str(s);
        StartLen::from_start_len(start, s.len())
    }

    pub fn push_display<D>(&mut self, s: &D) -> StartLen<N>
    where
        D: Display,
    {
        use std::fmt::Write;
        let start = self.len();
        let _ = write!(self.buffer, "{}", s);
        StartLen::from_start_len(start, self.len() - start)
    }

    #[allow(dead_code)]
    pub fn extend_with_str<I>(&mut self, separator: &str, iter: I) -> StartLen<N>
    where
        I: IntoIterator,
        I::Item: Borrow<str>,
    {
        let start = self.len();
        for s in iter {
            self.buffer.push_str(s.borrow());
            self.buffer.push_str(separator);
        }
        StartLen::from_start_len(start, self.len() - start)
    }

    pub fn extend_with_display<I>(&mut self, separator: &str, iter: I) -> StartLen<N>
    where
        I: IntoIterator,
        I::Item: Display,
    {
        use std::fmt::Write;
        let start = self.len();
        for elem in iter {
            let _ = write!(self.buffer, "{}", elem);
            self.buffer.push_str(separator);
        }
        StartLen::from_start_len(start, self.len() - start)
    }

    pub fn into_inner(self) -> String {
        self.buffer
    }
    pub fn as_inner(&self) -> &str {
        &self.buffer
    }
}

///////////////////////////////////////////////////////////////////////

pub type SmallCompositeVec<T> = CompositeVec<T, u16>;

/// A Vec-like type,
/// returning a `{start:16,len:u16}` range from methods that extend it.
pub struct CompositeVec<T, N> {
    list: Vec<T>,
    _integer: PhantomData<N>,
}

#[allow(dead_code)]
impl<T, N> CompositeVec<T, N>
where
    N: TryFrom<usize>,
    N::Error: Debug,
{
    pub fn new() -> Self {
        Self {
            list: Vec::new(),
            _integer: PhantomData,
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            list: Vec::with_capacity(capacity),
            _integer: PhantomData,
        }
    }

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

    pub fn push(&mut self, elem: T) -> u16 {
        let ind = self.len();
        self.list.push(elem);
        ind as u16
    }

    pub fn extend<I>(&mut self, iter: I) -> StartLen<N>
    where
        I: IntoIterator<Item = T>,
    {
        let start = self.len();
        self.list.extend(iter);
        StartLen::from_start_len(start, self.len() - start)
    }

    pub fn into_inner(self) -> Vec<T> {
        self.list
    }
    pub fn as_inner(&self) -> &[T] {
        &self.list
    }
}