beap/mem.rs
1//! Memory management.
2use super::Beap;
3use std::collections::TryReserveError;
4
5impl<T> Beap<T> {
6 /// Creates an empty `Beap` as a max-beap.
7 ///
8 /// # Examples
9 ///
10 /// Basic usage:
11 ///
12 /// ```
13 /// use beap::Beap;
14 /// let mut beap = Beap::new();
15 /// assert!(beap.is_empty());
16 ///
17 /// beap.push(4);
18 /// assert_eq!(beap.len(), 1);
19 /// ```
20 #[must_use]
21 pub fn new() -> Beap<T> {
22 Beap {
23 data: vec![],
24 height: 0,
25 }
26 }
27
28 /// Creates an empty `Beap` with a specific capacity.
29 /// This preallocates enough memory for `capacity` elements,
30 /// so that the `Beap` does not have to be reallocated
31 /// until it contains at least that many values.
32 ///
33 /// # Examples
34 ///
35 /// Basic usage:
36 ///
37 /// ```
38 /// use beap::Beap;
39 /// let mut beap = Beap::with_capacity(10);
40 /// beap.push(4);
41 /// ```
42 #[must_use]
43 pub fn with_capacity(capacity: usize) -> Beap<T> {
44 Beap {
45 data: Vec::with_capacity(capacity),
46 height: 0,
47 }
48 }
49
50 /// Returns the number of elements the beap can hold without reallocating.
51 ///
52 /// # Examples
53 ///
54 /// Basic usage:
55 ///
56 /// ```
57 /// use beap::Beap;
58 /// let mut beap = Beap::with_capacity(100);
59 /// assert!(beap.capacity() >= 100);
60 /// beap.push(4);
61 /// ```
62 #[must_use]
63 #[inline]
64 pub fn capacity(&self) -> usize {
65 self.data.capacity()
66 }
67
68 /// Extracts a slice containing the underlying vector.
69 ///
70 /// # Example
71 ///
72 /// ```
73 /// use beap::Beap;
74 /// let b = Beap::from([1, 2]);
75 /// assert_eq!(b.as_slice(), &[2, 1]);
76 /// ```
77 #[inline]
78 pub fn as_slice(&self) -> &[T] {
79 self.data.as_slice()
80 }
81
82 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
83 /// given `Beap`. Does nothing if the capacity is already sufficient.
84 ///
85 /// Note that the allocator may give the collection more space than it requests. Therefore
86 /// capacity can not be relied upon to be precisely minimal. Prefer [`reserve`] if future
87 /// insertions are expected.
88 ///
89 /// # Panics
90 ///
91 /// Panics if the new capacity overflows `usize`.
92 ///
93 /// # Examples
94 ///
95 /// Basic usage:
96 ///
97 /// ```
98 /// use beap::Beap;
99 /// let mut beap = Beap::new();
100 /// beap.reserve_exact(100);
101 /// assert!(beap.capacity() >= 100);
102 /// beap.push(4);
103 /// ```
104 ///
105 /// [`reserve`]: Beap::reserve
106 #[inline]
107 pub fn reserve_exact(&mut self, additional: usize) {
108 self.data.reserve_exact(additional);
109 }
110
111 /// Reserves capacity for at least `additional` more elements to be inserted in the
112 /// `Beap`. The collection may reserve more space to avoid frequent reallocations.
113 ///
114 /// # Panics
115 ///
116 /// Panics if the new capacity overflows `usize`.
117 ///
118 /// # Examples
119 ///
120 /// Basic usage:
121 ///
122 /// ```
123 /// use beap::Beap;
124 /// let mut beap = Beap::new();
125 /// beap.reserve(100);
126 /// assert!(beap.capacity() >= 100);
127 /// beap.push(4);
128 /// ```
129 #[inline]
130 pub fn reserve(&mut self, additional: usize) {
131 self.data.reserve(additional);
132 }
133
134 /// Discards as much additional capacity as possible.
135 ///
136 /// # Examples
137 ///
138 /// Basic usage:
139 ///
140 /// ```
141 /// use beap::Beap;
142 /// let mut beap: Beap<i32> = Beap::with_capacity(100);
143 ///
144 /// assert!(beap.capacity() >= 100);
145 /// beap.shrink_to_fit();
146 /// assert!(beap.capacity() == 0);
147 /// ```
148 #[inline]
149 pub fn shrink_to_fit(&mut self) {
150 self.data.shrink_to_fit();
151 }
152
153 /// Discards capacity with a lower bound.
154 ///
155 /// The capacity will remain at least as large as both the length
156 /// and the supplied value.
157 ///
158 /// If the current capacity is less than the lower limit, this is a no-op.
159 ///
160 /// # Examples
161 ///
162 /// ```
163 /// use beap::Beap;
164 /// let mut beap: Beap<i32> = Beap::with_capacity(100);
165 ///
166 /// assert!(beap.capacity() >= 100);
167 /// beap.shrink_to(10);
168 /// assert!(beap.capacity() >= 10);
169 /// ```
170 #[inline]
171 pub fn shrink_to(&mut self, min_capacity: usize) {
172 self.data.shrink_to(min_capacity);
173 }
174
175 /// Consumes the `Beap<T>` and returns the underlying vector `Vec<T>`
176 /// in arbitrary order.
177 ///
178 /// # Examples
179 ///
180 /// Basic usage:
181 ///
182 /// ```
183 /// use beap::Beap;
184 /// let beap = Beap::from(vec![1, 2, 3, 4, 5, 6, 7]);
185 /// let vec = beap.into_vec();
186 ///
187 /// // Will print in some order
188 /// for x in vec {
189 /// println!("{}", x);
190 /// }
191 /// ```
192 #[must_use = "`self` will be dropped if the result is not used"]
193 pub fn into_vec(self) -> Vec<T> {
194 self.data
195 }
196
197 /// Returns the length of the beap.
198 ///
199 /// # Examples
200 ///
201 /// Basic usage:
202 ///
203 /// ```
204 /// use beap::Beap;
205 /// let beap = Beap::from(vec![1, 3]);
206 ///
207 /// assert_eq!(beap.len(), 2);
208 /// ```
209 #[must_use]
210 #[inline]
211 pub fn len(&self) -> usize {
212 self.data.len()
213 }
214
215 /// Checks if the beap is empty.
216 ///
217 /// # Examples
218 ///
219 /// Basic usage:
220 ///
221 /// ```
222 /// use beap::Beap;
223 /// let mut beap = Beap::new();
224 ///
225 /// assert!(beap.is_empty());
226 ///
227 /// beap.push(3);
228 /// beap.push(5);
229 /// beap.push(1);
230 ///
231 /// assert!(!beap.is_empty());
232 /// ```
233 #[must_use]
234 #[inline]
235 pub fn is_empty(&self) -> bool {
236 self.len() == 0
237 }
238
239 /// Drops all items from the beap.
240 ///
241 /// # Examples
242 ///
243 /// Basic usage:
244 ///
245 /// ```
246 /// use beap::Beap;
247 /// let mut beap = Beap::from([1, 3, 5]);
248 ///
249 /// assert!(!beap.is_empty());
250 ///
251 /// beap.clear();
252 ///
253 /// assert!(beap.is_empty());
254 /// ```
255 #[inline]
256 pub fn clear(&mut self) {
257 self.drain();
258 }
259
260 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, `&'a mut [T]`.
261 ///
262 /// This calls [Vec::leak], accordingly, there are all lifetime restrictions.
263 ///
264 /// # Example
265 ///
266 /// ```
267 /// use beap::Beap;
268 /// let mut x = Beap::from([1usize, 2, 3]);
269 ///
270 /// let static_ref: &'static mut [usize] = x.leak();
271 /// assert_eq!(static_ref, &[3, 2, 1]);
272 ///
273 /// static_ref[0] += 1;
274 /// assert_eq!(static_ref, &[4, 2, 1]);
275 ///
276 /// // Manually free it later.
277 /// unsafe {
278 /// let _b = Box::from_raw(static_ref as *mut [usize]);
279 /// }
280 /// ```
281 #[inline]
282 pub fn leak<'a>(self) -> &'a mut [T] {
283 self.data.leak()
284 }
285
286 /// Converts the beap into `Box<[T]>`.
287 ///
288 /// It just calls [`Vec::into_boxed_slice`] on underlying `Vec`.
289 /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
290 ///
291 /// [`shrink_to_fit`]: Beap::shrink_to_fit
292 ///
293 /// # Examples
294 ///
295 /// ```
296 /// use beap::Beap;
297 /// let b = Beap::from([1, 2, 3]);
298 /// let slice = b.into_boxed_slice();
299 /// ```
300 ///
301 /// Any excess capacity is removed:
302 ///
303 /// ```
304 /// use beap::Beap;
305 /// let mut b = Vec::with_capacity(10);
306 /// b.extend([1, 2, 3]);
307 ///
308 /// assert!(b.capacity() >= 10);
309 /// let slice = b.into_boxed_slice();
310 /// assert_eq!(slice.into_vec().capacity(), 3);
311 /// ```
312 #[inline]
313 pub fn into_boxed_slice(self) -> Box<[T]> {
314 self.data.into_boxed_slice()
315 }
316
317 /// Tries to reserve capacity for at least `additional` more elements to be inserted
318 /// in the underlying `Vec<T>`. The underlying `Vec` may reserve more space to speculatively avoid
319 /// frequent reallocations. After calling `try_reserve`, capacity will be
320 /// greater than or equal to `self.len() + additional` if it returns
321 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
322 /// preserves the contents even if an error occurs.
323 ///
324 /// # Errors
325 ///
326 /// If the capacity overflows, or the allocator reports a failure, then an error
327 /// is returned.
328 ///
329 /// # Examples
330 ///
331 /// ```
332 /// use beap::Beap;
333 /// use std::collections::TryReserveError;
334 ///
335 /// fn process_data(data: &[u32]) -> Result<Beap<u32>, TryReserveError> {
336 /// let mut output = Beap::new();
337 ///
338 /// // Pre-reserve the memory, exiting if we can't
339 /// output.try_reserve(data.len())?;
340 ///
341 /// // Now we know this can't OOM in the middle of our complex work
342 /// output.extend(data.iter().map(|&val| {
343 /// val * 2 + 5 // very complicated
344 /// }));
345 ///
346 /// Ok(output)
347 /// }
348 /// process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
349 /// ```
350 #[inline]
351 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
352 self.data.try_reserve(additional)
353 }
354
355 /// Tries to reserve the minimum capacity for at least `additional`
356 /// elements to be inserted in the underlying `Vec<T>`. Unlike [`try_reserve`],
357 /// this will not deliberately over-allocate to speculatively avoid frequent
358 /// allocations. After calling `try_reserve_exact`, capacity will be greater
359 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
360 /// Does nothing if the capacity is already sufficient.
361 ///
362 /// Note that the allocator may give the collection more space than it
363 /// requests. Therefore, capacity can not be relied upon to be precisely
364 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
365 ///
366 /// [`try_reserve`]: Beap::try_reserve
367 ///
368 /// # Errors
369 ///
370 /// If the capacity overflows, or the allocator reports a failure, then an error
371 /// is returned.
372 ///
373 /// # Examples
374 ///
375 /// ```
376 /// use beap::Beap;
377 /// use std::collections::TryReserveError;
378 ///
379 /// fn process_data(data: &[u32]) -> Result<Beap<u32>, TryReserveError> {
380 /// let mut output = Beap::new();
381 ///
382 /// // Pre-reserve the memory, exiting if we can't
383 /// output.try_reserve_exact(data.len())?;
384 ///
385 /// // Now we know this can't OOM in the middle of our complex work
386 /// output.extend(data.iter().map(|&val| {
387 /// val * 2 + 5 // very complicated
388 /// }));
389 ///
390 /// Ok(output)
391 /// }
392 /// process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
393 /// ```
394 #[inline]
395 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
396 self.data.try_reserve_exact(additional)
397 }
398}
399
400impl<T: Ord> From<Vec<T>> for Beap<T> {
401 /// Converts a `Vec<T>` into a `Beap<T>`.
402 ///
403 /// This conversion happens in-place, and has *O*(*n*) time complexity.
404 ///
405 /// # Examples
406 ///
407 /// Basic usage:
408 ///
409 /// ```
410 /// use beap::Beap;
411 /// let beap = Beap::from(vec![5, 3, 2, 4, 1]);
412 /// assert_eq!(beap.into_sorted_vec(), vec![1, 2, 3, 4, 5]);
413 /// ```
414 fn from(mut vec: Vec<T>) -> Beap<T> {
415 vec.sort_unstable_by(|x, y| y.cmp(x));
416 let h = ((vec.len() * 2) as f64).sqrt().round() as usize;
417 Beap {
418 data: vec,
419 height: h,
420 }
421 }
422}
423
424impl<T: Ord, const N: usize> From<[T; N]> for Beap<T> {
425 /// Converts a `[T, N]` into a `Beap<T>`.
426 ///
427 /// This conversion has *O*(*nlog(n)*) time complexity.
428 ///
429 /// # Examples
430 ///
431 /// Basic usage:
432 ///
433 /// ```
434 /// use beap::Beap;
435 ///
436 /// let mut b1 = Beap::from([1, 4, 2, 3]);
437 /// let mut b2: Beap<_> = [1, 4, 2, 3].into();
438 /// assert_eq!(b1.into_vec(), vec![4, 3, 2, 1]);
439 /// assert_eq!(b2.into_vec(), vec![4, 3, 2, 1]);
440 /// ```
441 fn from(arr: [T; N]) -> Self {
442 Beap::from(Vec::from(arr))
443 }
444}
445
446impl<T: Ord> FromIterator<T> for Beap<T> {
447 /// Building Beap from iterator.
448 ///
449 /// This conversion has *O*(*nlog(n)*) time complexity.
450 ///
451 /// # Examples
452 ///
453 /// Basic usage:
454 ///
455 /// ```
456 /// use beap::Beap;
457 ///
458 /// let mut b1 = Beap::from([1, 4, 2, 3]);
459 /// let mut b2: Beap<i32> = [1, 4, 2, 3].into_iter().collect();
460 /// while let Some((a, b)) = b1.pop().zip(b2.pop()) {
461 /// assert_eq!(a, b);
462 /// }
463 /// ```
464 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Beap<T> {
465 Beap::from(iter.into_iter().collect::<Vec<_>>())
466 }
467}
468
469impl<T: Ord> Extend<T> for Beap<T> {
470 /// Extend Beap with elements from the iterator.
471 ///
472 /// # Examples
473 ///
474 /// Basic usage:
475 ///
476 /// ```
477 /// use beap::Beap;
478 ///
479 /// let mut beap = Beap::new();
480 /// beap.extend(vec![7, 1, 0, 4, 5, 3]);
481 /// assert_eq!(beap.into_sorted_vec(), [0, 1, 3, 4, 5, 7]);
482 /// ```
483 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
484 for x in iter {
485 self.push(x);
486 }
487 }
488}
489
490impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for Beap<T> {
491 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
492 self.extend(iter.into_iter().cloned());
493 }
494}