blob: 0b749d91083f9d85dddb664f6c2fd71e550a0004 [file] [log] [blame]
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -07001use std::borrow::Borrow;
2use std::cmp::Ordering;
3use std::default::Default;
4use std::fmt;
5use std::hash::Hash;
6use std::hash::Hasher;
7use std::iter::FromIterator;
8use std::iter::IntoIterator;
9use std::ops::Deref;
10use std::ops::DerefMut;
11use std::ops::Index;
12use std::ops::IndexMut;
13use std::slice;
14use std::vec;
15
David LeGare793d84b2022-03-02 16:21:10 +000016#[cfg(feature = "with-serde")]
17use serde;
18
Haibo Huangd32e6ee2020-08-12 13:52:04 -070019use crate::clear::Clear;
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -070020
21/// Wrapper around vector to avoid deallocations on clear.
22pub struct RepeatedField<T> {
23 vec: Vec<T>,
24 len: usize,
25}
26
27impl<T> RepeatedField<T> {
28 /// Return number of elements in this container.
29 #[inline]
30 pub fn len(&self) -> usize {
31 self.len
32 }
33
34 /// Clear.
35 #[inline]
36 pub fn clear(&mut self) {
37 self.len = 0;
38 }
39}
40
41impl<T> Clear for RepeatedField<T> {
42 #[inline]
43 fn clear(&mut self) {
44 self.len = 0;
45 }
46}
47
48impl<T> Default for RepeatedField<T> {
49 #[inline]
50 fn default() -> RepeatedField<T> {
51 RepeatedField {
52 vec: Vec::new(),
53 len: 0,
54 }
55 }
56}
57
58impl<T> RepeatedField<T> {
59 /// Create new empty container.
60 #[inline]
61 pub fn new() -> RepeatedField<T> {
62 Default::default()
63 }
64
65 /// Create a contained with data from given vec.
66 #[inline]
67 pub fn from_vec(vec: Vec<T>) -> RepeatedField<T> {
68 let len = vec.len();
69 RepeatedField { vec: vec, len: len }
70 }
71
72 /// Convert data into vec.
73 #[inline]
74 pub fn into_vec(self) -> Vec<T> {
75 let mut vec = self.vec;
76 vec.truncate(self.len);
77 vec
78 }
79
80 /// Return current capacity.
81 #[inline]
82 pub fn capacity(&self) -> usize {
83 self.vec.capacity()
84 }
85
86 /// View data as slice.
87 #[inline]
88 pub fn as_slice<'a>(&'a self) -> &'a [T] {
89 &self.vec[..self.len]
90 }
91
92 /// View data as mutable slice.
93 #[inline]
94 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
95 &mut self.vec[..self.len]
96 }
97
98 /// Get subslice of this container.
99 #[inline]
100 pub fn slice(&self, start: usize, end: usize) -> &[T] {
101 &self.as_ref()[start..end]
102 }
103
104 /// Get mutable subslice of this container.
105 #[inline]
106 pub fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
107 &mut self.as_mut_slice()[start..end]
108 }
109
110 /// Get slice from given index.
111 #[inline]
112 pub fn slice_from(&self, start: usize) -> &[T] {
113 &self.as_ref()[start..]
114 }
115
116 /// Get mutable slice from given index.
117 #[inline]
118 pub fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
119 &mut self.as_mut_slice()[start..]
120 }
121
122 /// Get slice to given index.
123 #[inline]
124 pub fn slice_to(&self, end: usize) -> &[T] {
125 &self.as_ref()[..end]
126 }
127
128 /// Get mutable slice to given index.
129 #[inline]
130 pub fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
131 &mut self.as_mut_slice()[..end]
132 }
133
134 /// View this container as two slices split at given index.
135 #[inline]
136 pub fn split_at<'a>(&'a self, mid: usize) -> (&'a [T], &'a [T]) {
137 self.as_ref().split_at(mid)
138 }
139
140 /// View this container as two mutable slices split at given index.
141 #[inline]
142 pub fn split_at_mut<'a>(&'a mut self, mid: usize) -> (&'a mut [T], &'a mut [T]) {
143 self.as_mut_slice().split_at_mut(mid)
144 }
145
146 /// View all but first elements of this container.
147 #[inline]
148 pub fn tail(&self) -> &[T] {
149 &self.as_ref()[1..]
150 }
151
152 /// Last element of this container.
153 #[inline]
154 pub fn last(&self) -> Option<&T> {
155 self.as_ref().last()
156 }
157
158 /// Mutable last element of this container.
159 #[inline]
160 pub fn last_mut<'a>(&'a mut self) -> Option<&'a mut T> {
161 self.as_mut_slice().last_mut()
162 }
163
164 /// View all but last elements of this container.
165 #[inline]
166 pub fn init<'a>(&'a self) -> &'a [T] {
167 let s = self.as_ref();
168 &s[0..s.len() - 1]
169 }
170
171 /// Push an element to the end.
172 #[inline]
173 pub fn push(&mut self, value: T) {
174 if self.len == self.vec.len() {
175 self.vec.push(value);
176 } else {
177 self.vec[self.len] = value;
178 }
179 self.len += 1;
180 }
181
182 /// Pop last element.
183 #[inline]
184 pub fn pop(&mut self) -> Option<T> {
185 if self.len == 0 {
186 None
187 } else {
188 self.vec.truncate(self.len);
189 self.len -= 1;
190 self.vec.pop()
191 }
192 }
193
194 /// Insert an element at specified position.
195 #[inline]
196 pub fn insert(&mut self, index: usize, value: T) {
197 assert!(index <= self.len);
198 self.vec.insert(index, value);
199 self.len += 1;
200 }
201
202 /// Remove an element from specified position.
203 #[inline]
204 pub fn remove(&mut self, index: usize) -> T {
205 assert!(index < self.len);
206 self.len -= 1;
207 self.vec.remove(index)
208 }
209
Haibo Huangd32e6ee2020-08-12 13:52:04 -0700210 /// Retains only the elements specified by the predicate.
211 ///
212 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
213 /// This method operates in place, visiting each element exactly once in the
214 /// original order, and preserves the order of the retained elements.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// # use protobuf::RepeatedField;
220 ///
221 /// let mut vec = RepeatedField::from(vec![1, 2, 3, 4]);
222 /// vec.retain(|&x| x % 2 == 0);
223 /// assert_eq!(vec, RepeatedField::from(vec![2, 4]));
224 /// ```
225 pub fn retain<F>(&mut self, f: F)
226 where
227 F: FnMut(&T) -> bool,
228 {
229 // suboptimal
230 self.vec.truncate(self.len);
231 self.vec.retain(f);
232 self.len = self.vec.len();
233 }
234
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -0700235 /// Truncate at specified length.
236 #[inline]
237 pub fn truncate(&mut self, len: usize) {
238 if self.len > len {
239 self.len = len;
240 }
241 }
242
243 /// Reverse in place.
244 #[inline]
245 pub fn reverse(&mut self) {
246 self.as_mut_slice().reverse()
247 }
248
249 /// Into owned iterator.
250 #[inline]
251 pub fn into_iter(mut self) -> vec::IntoIter<T> {
252 self.vec.truncate(self.len);
253 self.vec.into_iter()
254 }
255
256 /// Immutable data iterator.
257 #[inline]
258 pub fn iter<'a>(&'a self) -> slice::Iter<'a, T> {
259 self.as_ref().iter()
260 }
261
262 /// Mutable data iterator.
263 #[inline]
264 pub fn iter_mut<'a>(&'a mut self) -> slice::IterMut<'a, T> {
265 self.as_mut_slice().iter_mut()
266 }
267
268 /// Sort elements with given comparator.
269 #[inline]
270 pub fn sort_by<F>(&mut self, compare: F)
271 where
272 F: Fn(&T, &T) -> Ordering,
273 {
274 self.as_mut_slice().sort_by(compare)
275 }
276
277 /// Get data as raw pointer.
278 #[inline]
279 pub fn as_ptr(&self) -> *const T {
280 self.vec.as_ptr()
281 }
282
283 /// Get data a mutable raw pointer.
284 #[inline]
285 pub fn as_mut_ptr(&mut self) -> *mut T {
286 self.vec.as_mut_ptr()
287 }
288}
289
290impl<T: Default + Clear> RepeatedField<T> {
291 /// Push default value.
292 /// This operation could be faster than `rf.push(Default::default())`,
293 /// because it may reuse previously allocated and cleared element.
294 pub fn push_default<'a>(&'a mut self) -> &'a mut T {
295 if self.len == self.vec.len() {
296 self.vec.push(Default::default());
297 } else {
298 self.vec[self.len].clear();
299 }
300 self.len += 1;
301 self.last_mut().unwrap()
302 }
303}
304
305impl<T> From<Vec<T>> for RepeatedField<T> {
306 #[inline]
307 fn from(values: Vec<T>) -> RepeatedField<T> {
308 RepeatedField::from_vec(values)
309 }
310}
311
312impl<'a, T: Clone> From<&'a [T]> for RepeatedField<T> {
313 #[inline]
314 fn from(values: &'a [T]) -> RepeatedField<T> {
315 RepeatedField::from_slice(values)
316 }
317}
318
319impl<T> Into<Vec<T>> for RepeatedField<T> {
320 #[inline]
321 fn into(self) -> Vec<T> {
322 self.into_vec()
323 }
324}
325
326impl<T: Clone> RepeatedField<T> {
327 /// Copy slice data to `RepeatedField`
328 #[inline]
329 pub fn from_slice(values: &[T]) -> RepeatedField<T> {
330 RepeatedField::from_vec(values.to_vec())
331 }
332
333 /// Copy slice data to `RepeatedField`
334 #[inline]
335 pub fn from_ref<X: AsRef<[T]>>(values: X) -> RepeatedField<T> {
336 RepeatedField::from_slice(values.as_ref())
337 }
338
339 /// Copy this data into new vec.
340 #[inline]
341 pub fn to_vec(&self) -> Vec<T> {
342 self.as_ref().to_vec()
343 }
344}
345
346impl<T: Clone> Clone for RepeatedField<T> {
347 #[inline]
348 fn clone(&self) -> RepeatedField<T> {
349 RepeatedField {
350 vec: self.to_vec(),
351 len: self.len(),
352 }
353 }
354}
355
356impl<T> FromIterator<T> for RepeatedField<T> {
357 #[inline]
358 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> RepeatedField<T> {
359 RepeatedField::from_vec(FromIterator::from_iter(iter))
360 }
361}
362
363impl<'a, T> IntoIterator for &'a RepeatedField<T> {
364 type Item = &'a T;
365 type IntoIter = slice::Iter<'a, T>;
366
367 fn into_iter(self) -> slice::Iter<'a, T> {
368 self.iter()
369 }
370}
371
Haibo Huang914311b2021-01-07 18:06:15 -0800372impl<'a, T> IntoIterator for &'a mut RepeatedField<T> {
373 type Item = &'a mut T;
374 type IntoIter = slice::IterMut<'a, T>;
375
376 fn into_iter(self) -> slice::IterMut<'a, T> {
377 self.iter_mut()
378 }
379}
380
381impl<'a, T> IntoIterator for RepeatedField<T> {
382 type Item = T;
383 type IntoIter = vec::IntoIter<T>;
384
385 fn into_iter(self) -> vec::IntoIter<T> {
386 self.into_iter()
387 }
388}
389
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -0700390impl<T: PartialEq> PartialEq for RepeatedField<T> {
391 #[inline]
392 fn eq(&self, other: &RepeatedField<T>) -> bool {
393 self.as_ref() == other.as_ref()
394 }
395}
396
397impl<T: Eq> Eq for RepeatedField<T> {}
398
Joel Galensonf9dc51b2021-08-09 10:39:22 -0700399impl<T: PartialEq> PartialEq<[T]> for RepeatedField<T> {
400 fn eq(&self, other: &[T]) -> bool {
401 self.as_slice() == other
402 }
403}
404
405impl<T: PartialEq> PartialEq<RepeatedField<T>> for [T] {
406 fn eq(&self, other: &RepeatedField<T>) -> bool {
407 self == other.as_slice()
408 }
409}
410
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -0700411impl<T: PartialEq> RepeatedField<T> {
412 /// True iff this container contains given element.
413 #[inline]
414 pub fn contains(&self, value: &T) -> bool {
415 self.as_ref().contains(value)
416 }
417}
418
419impl<T: Hash> Hash for RepeatedField<T> {
420 fn hash<H: Hasher>(&self, state: &mut H) {
421 self.as_ref().hash(state);
422 }
423}
424
425impl<T> AsRef<[T]> for RepeatedField<T> {
426 #[inline]
427 fn as_ref<'a>(&'a self) -> &'a [T] {
428 &self.vec[..self.len]
429 }
430}
431
432impl<T> Borrow<[T]> for RepeatedField<T> {
433 #[inline]
434 fn borrow(&self) -> &[T] {
435 &self.vec[..self.len]
436 }
437}
438
439impl<T> Deref for RepeatedField<T> {
440 type Target = [T];
441 #[inline]
442 fn deref(&self) -> &[T] {
443 &self.vec[..self.len]
444 }
445}
446
447impl<T> DerefMut for RepeatedField<T> {
448 #[inline]
449 fn deref_mut(&mut self) -> &mut [T] {
450 &mut self.vec[..self.len]
451 }
452}
453
454impl<T> Index<usize> for RepeatedField<T> {
455 type Output = T;
456
457 #[inline]
458 fn index<'a>(&'a self, index: usize) -> &'a T {
459 &self.as_ref()[index]
460 }
461}
462
463impl<T> IndexMut<usize> for RepeatedField<T> {
464 #[inline]
465 fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut T {
466 &mut self.as_mut_slice()[index]
467 }
468}
469
Joel Galensonf9dc51b2021-08-09 10:39:22 -0700470impl<T> Extend<T> for RepeatedField<T> {
471 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
472 self.vec.truncate(self.len);
473 self.vec.extend(iter);
474 self.len = self.vec.len();
475 }
476}
477
478impl<'a, T: Copy + 'a> Extend<&'a T> for RepeatedField<T> {
479 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
480 self.vec.truncate(self.len);
481 self.vec.extend(iter);
482 self.len = self.vec.len();
483 }
484}
485
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -0700486impl<T: fmt::Debug> fmt::Debug for RepeatedField<T> {
487 #[inline]
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 self.as_ref().fmt(f)
490 }
491}
492
493#[cfg(feature = "with-serde")]
494impl<T: serde::Serialize> serde::Serialize for RepeatedField<T> {
495 fn serialize<S>(
496 &self,
497 serializer: S,
498 ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
499 where
500 S: serde::Serializer,
501 {
502 self.as_ref().serialize(serializer)
503 }
504}
505
506#[cfg(feature = "with-serde")]
507impl<'de, T: serde::Deserialize<'de> + Default> serde::Deserialize<'de> for RepeatedField<T> {
508 fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error>
509 where
510 D: serde::Deserializer<'de>,
511 {
512 Vec::deserialize(deserializer).map(RepeatedField::from)
513 }
514}
515
516#[cfg(test)]
517mod test {
518 use super::RepeatedField;
519
520 #[test]
521 fn as_mut_slice() {
522 let mut v = RepeatedField::new();
523 v.push(10);
524 v.push(20);
525 v.clear();
526 assert_eq!(v.as_mut_slice(), &mut []);
527 v.push(30);
528 assert_eq!(v.as_mut_slice(), &mut [30]);
529 }
530
531 #[test]
532 fn push_default() {
533 let mut v = RepeatedField::new();
534 v.push("aa".to_string());
535 v.push("bb".to_string());
536 v.clear();
537 assert_eq!("".to_string(), *v.push_default());
538 }
Joel Galensonf9dc51b2021-08-09 10:39:22 -0700539
540 #[test]
541 fn extend_values() {
542 let mut r = RepeatedField::new();
543 r.push(10);
544 r.push(20);
545 r.clear();
546 // self-check
547 assert_eq!(2, r.vec.len());
548 r.extend(vec![30, 40]);
549 assert_eq!(&[30, 40][..], &r);
550 }
551
552 #[test]
553 fn extend_copy() {
554 let mut r = RepeatedField::new();
555 r.push(10);
556 r.push(20);
557 r.clear();
558 // self-check
559 assert_eq!(2, r.vec.len());
560 r.extend(&[30, 40]);
561 assert_eq!(&[30, 40][..], &r);
562 }
Chih-Hung Hsiehcfc3a232020-06-10 20:13:05 -0700563}