servers/
repeated_field.rs

1// Copyright (c) 2019 Stepan Koltsov
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
16// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
19// OR OTHER DEALINGS IN THE SOFTWARE.
20
21// The Clear trait is copied from https://github.com/stepancheg/rust-protobuf/blob/v2.28.0/protobuf/src/clear.rs
22// The RepeatedField struct is copied from https://github.com/stepancheg/rust-protobuf/blob/v2.28.0/protobuf/src/repeated.rs
23// This code is to leverage the pooling mechanism to avoid frequent heap allocation/de-allocation when decoding deeply nested structs.
24
25use std::borrow::Borrow;
26use std::cmp::Ordering;
27use std::default::Default;
28use std::hash::{Hash, Hasher};
29use std::iter::{FromIterator, IntoIterator};
30use std::ops::{Deref, DerefMut, Index, IndexMut};
31use std::{fmt, slice, vec};
32
33use bytes::Bytes;
34
35/// anything that can be cleared
36pub trait Clear {
37    /// Clear this make, make it equivalent to newly created object.
38    fn clear(&mut self);
39}
40
41impl<T> Clear for Option<T> {
42    fn clear(&mut self) {
43        self.take();
44    }
45}
46
47impl Clear for String {
48    fn clear(&mut self) {
49        String::clear(self);
50    }
51}
52
53impl<T> Clear for Vec<T> {
54    fn clear(&mut self) {
55        Vec::clear(self);
56    }
57}
58
59impl Clear for Bytes {
60    fn clear(&mut self) {
61        Bytes::clear(self);
62    }
63}
64
65/// Wrapper around vector to avoid deallocations on clear.
66pub struct RepeatedField<T> {
67    vec: Vec<T>,
68    len: usize,
69}
70
71impl<T> RepeatedField<T> {
72    /// Return number of elements in this container.
73    #[inline]
74    pub fn len(&self) -> usize {
75        self.len
76    }
77
78    /// Returns true if this container is empty.
79    #[inline]
80    pub fn is_empty(&self) -> bool {
81        self.len == 0
82    }
83
84    /// Clear.
85    #[inline]
86    pub fn clear(&mut self) {
87        self.len = 0;
88    }
89}
90
91impl<T> Default for RepeatedField<T> {
92    #[inline]
93    fn default() -> RepeatedField<T> {
94        RepeatedField {
95            vec: Vec::new(),
96            len: 0,
97        }
98    }
99}
100
101impl<T> RepeatedField<T> {
102    /// Create new empty container.
103    #[inline]
104    pub fn new() -> RepeatedField<T> {
105        Default::default()
106    }
107
108    /// Create a contained with data from given vec.
109    #[inline]
110    pub fn from_vec(vec: Vec<T>) -> RepeatedField<T> {
111        let len = vec.len();
112        RepeatedField { vec, len }
113    }
114
115    /// Convert data into vec.
116    #[inline]
117    pub fn into_vec(self) -> Vec<T> {
118        let mut vec = self.vec;
119        vec.truncate(self.len);
120        vec
121    }
122
123    /// Return current capacity.
124    #[inline]
125    pub fn capacity(&self) -> usize {
126        self.vec.capacity()
127    }
128
129    /// View data as slice.
130    #[inline]
131    pub fn as_slice(&self) -> &[T] {
132        &self.vec[..self.len]
133    }
134
135    /// View data as mutable slice.
136    #[inline]
137    pub fn as_mut_slice(&mut self) -> &mut [T] {
138        &mut self.vec[..self.len]
139    }
140
141    /// Get subslice of this container.
142    #[inline]
143    pub fn slice(&self, start: usize, end: usize) -> &[T] {
144        &self.as_ref()[start..end]
145    }
146
147    /// Get slice from given index.
148    #[inline]
149    pub fn slice_from(&self, start: usize) -> &[T] {
150        &self.as_ref()[start..]
151    }
152
153    /// Get slice to given index.
154    #[inline]
155    pub fn slice_to(&self, end: usize) -> &[T] {
156        &self.as_ref()[..end]
157    }
158
159    /// View this container as two slices split at given index.
160    #[inline]
161    pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
162        self.as_ref().split_at(mid)
163    }
164
165    /// View this container as two mutable slices split at given index.
166    #[inline]
167    pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
168        self.as_mut_slice().split_at_mut(mid)
169    }
170
171    /// View all but first elements of this container.
172    #[inline]
173    pub fn tail(&self) -> &[T] {
174        &self.as_ref()[1..]
175    }
176
177    /// Last element of this container.
178    #[inline]
179    pub fn last(&self) -> Option<&T> {
180        self.as_ref().last()
181    }
182
183    /// Mutable last element of this container.
184    #[inline]
185    pub fn last_mut(&mut self) -> Option<&mut T> {
186        self.as_mut_slice().last_mut()
187    }
188
189    /// View all but last elements of this container.
190    #[inline]
191    pub fn init(&self) -> &[T] {
192        let s = self.as_ref();
193        &s[0..s.len() - 1]
194    }
195
196    /// Push an element to the end.
197    #[inline]
198    pub fn push(&mut self, value: T) {
199        if self.len == self.vec.len() {
200            self.vec.push(value);
201        } else {
202            self.vec[self.len] = value;
203        }
204        self.len += 1;
205    }
206
207    /// Pop last element.
208    #[inline]
209    pub fn pop(&mut self) -> Option<T> {
210        if self.len == 0 {
211            None
212        } else {
213            self.vec.truncate(self.len);
214            self.len -= 1;
215            self.vec.pop()
216        }
217    }
218
219    /// Insert an element at specified position.
220    #[inline]
221    pub fn insert(&mut self, index: usize, value: T) {
222        assert!(index <= self.len);
223        self.vec.insert(index, value);
224        self.len += 1;
225    }
226
227    /// Remove an element from specified position.
228    #[inline]
229    pub fn remove(&mut self, index: usize) -> T {
230        assert!(index < self.len);
231        self.len -= 1;
232        self.vec.remove(index)
233    }
234
235    /// Retains only the elements specified by the predicate.
236    ///
237    /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
238    /// This method operates in place, visiting each element exactly once in the
239    /// original order, and preserves the order of the retained elements.
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use servers::repeated_field::RepeatedField;
245    ///
246    /// let mut vec = RepeatedField::from(vec![1, 2, 3, 4]);
247    /// vec.retain(|&x| x % 2 == 0);
248    /// assert_eq!(vec, RepeatedField::from(vec![2, 4]));
249    /// ```
250    pub fn retain<F>(&mut self, f: F)
251    where
252        F: FnMut(&T) -> bool,
253    {
254        // suboptimal
255        self.vec.truncate(self.len);
256        self.vec.retain(f);
257        self.len = self.vec.len();
258    }
259
260    /// Truncate at specified length.
261    #[inline]
262    pub fn truncate(&mut self, len: usize) {
263        if self.len > len {
264            self.len = len;
265        }
266    }
267
268    /// Reverse in place.
269    #[inline]
270    pub fn reverse(&mut self) {
271        self.as_mut_slice().reverse()
272    }
273
274    /// Immutable data iterator.
275    #[inline]
276    pub fn iter(&self) -> slice::Iter<T> {
277        self.as_ref().iter()
278    }
279
280    /// Mutable data iterator.
281    #[inline]
282    pub fn iter_mut(&mut self) -> slice::IterMut<T> {
283        self.as_mut_slice().iter_mut()
284    }
285
286    /// Sort elements with given comparator.
287    #[inline]
288    pub fn sort_by<F>(&mut self, compare: F)
289    where
290        F: Fn(&T, &T) -> Ordering,
291    {
292        self.as_mut_slice().sort_by(compare)
293    }
294
295    /// Get data as raw pointer.
296    #[inline]
297    pub fn as_ptr(&self) -> *const T {
298        self.vec.as_ptr()
299    }
300
301    /// Get data a mutable raw pointer.
302    #[inline]
303    pub fn as_mut_ptr(&mut self) -> *mut T {
304        self.vec.as_mut_ptr()
305    }
306}
307
308impl<T: Default + Clear> RepeatedField<T> {
309    /// Push default value.
310    /// This operation could be faster than `rf.push(Default::default())`,
311    /// because it may reuse previously allocated and cleared element.
312    pub fn push_default(&mut self) -> &mut T {
313        if self.len == self.vec.len() {
314            self.vec.push(Default::default());
315        } else {
316            self.vec[self.len].clear();
317        }
318        self.len += 1;
319        self.last_mut().unwrap()
320    }
321}
322
323impl<T> From<Vec<T>> for RepeatedField<T> {
324    #[inline]
325    fn from(values: Vec<T>) -> RepeatedField<T> {
326        RepeatedField::from_vec(values)
327    }
328}
329
330impl<'a, T: Clone> From<&'a [T]> for RepeatedField<T> {
331    #[inline]
332    fn from(values: &'a [T]) -> RepeatedField<T> {
333        RepeatedField::from_slice(values)
334    }
335}
336
337impl<T> From<RepeatedField<T>> for Vec<T> {
338    #[inline]
339    fn from(val: RepeatedField<T>) -> Self {
340        val.into_vec()
341    }
342}
343
344impl<T: Clone> RepeatedField<T> {
345    /// Copy slice data to `RepeatedField`
346    #[inline]
347    pub fn from_slice(values: &[T]) -> RepeatedField<T> {
348        RepeatedField::from_vec(values.to_vec())
349    }
350
351    /// Copy slice data to `RepeatedField`
352    #[inline]
353    pub fn from_ref<X: AsRef<[T]>>(values: X) -> RepeatedField<T> {
354        RepeatedField::from_slice(values.as_ref())
355    }
356
357    /// Copy this data into new vec.
358    #[inline]
359    pub fn to_vec(&self) -> Vec<T> {
360        self.as_ref().to_vec()
361    }
362}
363
364impl<T: Clone> Clone for RepeatedField<T> {
365    #[inline]
366    fn clone(&self) -> RepeatedField<T> {
367        RepeatedField {
368            vec: self.to_vec(),
369            len: self.len(),
370        }
371    }
372}
373
374impl<T> FromIterator<T> for RepeatedField<T> {
375    #[inline]
376    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> RepeatedField<T> {
377        RepeatedField::from_vec(FromIterator::from_iter(iter))
378    }
379}
380
381impl<'a, T> IntoIterator for &'a RepeatedField<T> {
382    type Item = &'a T;
383    type IntoIter = slice::Iter<'a, T>;
384
385    fn into_iter(self) -> slice::Iter<'a, T> {
386        self.iter()
387    }
388}
389
390impl<'a, T> IntoIterator for &'a mut RepeatedField<T> {
391    type Item = &'a mut T;
392    type IntoIter = slice::IterMut<'a, T>;
393
394    fn into_iter(self) -> slice::IterMut<'a, T> {
395        self.iter_mut()
396    }
397}
398
399impl<T> IntoIterator for RepeatedField<T> {
400    type Item = T;
401    type IntoIter = vec::IntoIter<T>;
402
403    fn into_iter(mut self) -> vec::IntoIter<T> {
404        self.vec.truncate(self.len);
405        self.vec.into_iter()
406    }
407}
408
409impl<T: PartialEq> PartialEq for RepeatedField<T> {
410    #[inline]
411    fn eq(&self, other: &RepeatedField<T>) -> bool {
412        self.as_ref() == other.as_ref()
413    }
414}
415
416impl<T: Eq> Eq for RepeatedField<T> {}
417
418impl<T: PartialEq> PartialEq<[T]> for RepeatedField<T> {
419    fn eq(&self, other: &[T]) -> bool {
420        self.as_slice() == other
421    }
422}
423
424impl<T: PartialEq> PartialEq<RepeatedField<T>> for [T] {
425    fn eq(&self, other: &RepeatedField<T>) -> bool {
426        self == other.as_slice()
427    }
428}
429
430impl<T: PartialEq> RepeatedField<T> {
431    /// True iff this container contains given element.
432    #[inline]
433    pub fn contains(&self, value: &T) -> bool {
434        self.as_ref().contains(value)
435    }
436}
437
438impl<T: Hash> Hash for RepeatedField<T> {
439    fn hash<H: Hasher>(&self, state: &mut H) {
440        self.as_ref().hash(state);
441    }
442}
443
444impl<T> AsRef<[T]> for RepeatedField<T> {
445    #[inline]
446    fn as_ref(&self) -> &[T] {
447        &self.vec[..self.len]
448    }
449}
450
451impl<T> Borrow<[T]> for RepeatedField<T> {
452    #[inline]
453    fn borrow(&self) -> &[T] {
454        &self.vec[..self.len]
455    }
456}
457
458impl<T> Deref for RepeatedField<T> {
459    type Target = [T];
460    #[inline]
461    fn deref(&self) -> &[T] {
462        &self.vec[..self.len]
463    }
464}
465
466impl<T> DerefMut for RepeatedField<T> {
467    #[inline]
468    fn deref_mut(&mut self) -> &mut [T] {
469        &mut self.vec[..self.len]
470    }
471}
472
473impl<T> Index<usize> for RepeatedField<T> {
474    type Output = T;
475
476    #[inline]
477    fn index(&self, index: usize) -> &T {
478        &self.as_ref()[index]
479    }
480}
481
482impl<T> IndexMut<usize> for RepeatedField<T> {
483    #[inline]
484    fn index_mut(&mut self, index: usize) -> &mut T {
485        &mut self.as_mut_slice()[index]
486    }
487}
488
489impl<T> Extend<T> for RepeatedField<T> {
490    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
491        self.vec.truncate(self.len);
492        self.vec.extend(iter);
493        self.len = self.vec.len();
494    }
495}
496
497impl<'a, T: Copy + 'a> Extend<&'a T> for RepeatedField<T> {
498    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
499        self.vec.truncate(self.len);
500        self.vec.extend(iter);
501        self.len = self.vec.len();
502    }
503}
504
505impl<T: fmt::Debug> fmt::Debug for RepeatedField<T> {
506    #[inline]
507    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
508        self.as_ref().fmt(f)
509    }
510}