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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
use crate::raw::{RawAlignedBuffer, RawBufferError};
use core::fmt;
use std::{cmp, ops, ptr, slice::SliceIndex};

#[derive(Debug, thiserror::Error)]
#[error("failed to reserve capacity")]
pub struct TryReserveError {
	#[source]
	source: Box<RawBufferError>,
}

impl From<RawBufferError> for TryReserveError {
	#[inline]
	fn from(source: RawBufferError) -> Self {
		Self {
			source: Box::new(source),
		}
	}
}

/// A unique (owned) aligned buffer. This can be used to write data to the buffer,
/// before converting it to a [`SharedAlignedBuffer`] to get cheap clones and sharing
/// of the buffer data. This type is effectively a `Vec<u8>` with a custom alignment.
///
/// [`SharedAlignedBuffer`]: crate::SharedAlignedBuffer
pub struct UniqueAlignedBuffer<const ALIGNMENT: usize> {
	pub(crate) buf: RawAlignedBuffer<ALIGNMENT>,
	len: usize,
}

impl<const ALIGNMENT: usize> UniqueAlignedBuffer<ALIGNMENT> {
	/// Constructs a new, empty `UniqueAlignedBuffer`.
	///
	/// The buffer will not allocate until elements are pushed onto it.
	///
	/// # Examples
	///
	/// ```
	/// # #![allow(unused_mut)]
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<32>::new();
	/// ```
	#[inline]
	#[must_use]
	pub const fn new() -> Self {
		let buf = RawAlignedBuffer::new();
		Self { buf, len: 0 }
	}

	/// Constructs a new, empty `UniqueAlignedBuffer` with at least the specified capacity.
	///
	/// The buffer will be able to hold at least `capacity` elements without
	/// reallocating. This method is allowed to allocate for more elements than
	/// `capacity`. If `capacity` is 0, the vector will not allocate.
	///
	/// It is important to note that although the returned vector has the
	/// minimum *capacity* specified, the vector will have a zero *length*. For
	/// an explanation of the difference between length and capacity, see
	/// *[Capacity and reallocation]*.
	///
	/// If it is important to know the exact allocated capacity of a `UniqueAlignedBuffer`,
	/// always use the [`capacity`] method after construction.
	///
	/// [Capacity and reallocation]: #capacity-and-reallocation
	/// [`capacity`]: UniqueAlignedBuffer::capacity
	///
	/// # Panics
	///
	/// Panics if the new capacity is too large.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<32>::with_capacity(10);
	///
	/// // The vector contains no items, even though it has capacity for more
	/// assert_eq!(buf.len(), 0);
	/// assert!(buf.capacity() >= 10);
	///
	/// // These are all done without reallocating...
	/// for i in 0..10 {
	///     buf.push(i);
	/// }
	/// assert_eq!(buf.len(), 10);
	/// assert!(buf.capacity() >= 10);
	///
	/// // ...but this may make the vector reallocate
	/// buf.push(11);
	/// assert_eq!(buf.len(), 11);
	/// assert!(buf.capacity() >= 11);
	/// ```
	#[inline]
	#[must_use]
	pub fn with_capacity(capacity: usize) -> Self {
		let buf = RawAlignedBuffer::with_capacity(capacity);
		Self { buf, len: 0 }
	}

	/// Returns the total number of elements the buffer can hold without
	/// reallocating.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<32>::with_capacity(10);
	/// buf.push(42);
	/// assert!(buf.capacity() >= 10);
	/// ```
	#[inline]
	pub fn capacity(&self) -> usize {
		self.buf.capacity()
	}

	/// Reserves capacity for at least `additional` more elements to be inserted
	/// in the given `UniqueAlignedBuffer`. The collection may reserve more space to
	/// speculatively avoid frequent reallocations. After calling `reserve`,
	/// capacity will be greater than or equal to `self.len() + additional`.
	/// Does nothing if capacity is already sufficient.
	///
	/// # Panics
	///
	/// Panics if the new capacity is too large.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<32>::with_capacity(10);
	/// buf.reserve(20);
	/// assert!(buf.capacity() >= 20);
	/// ```
	pub fn reserve(&mut self, additional: usize) {
		// SAFETY: We're the unieue owner of the buffer.
		unsafe {
			self.buf.reserve(self.len, additional);
		}
	}

	/// Reserves the minimum capacity for at least `additional` more elements to
	/// be inserted in the given `UniqueAlignedBuffer`. Unlike [`reserve`], this will not
	/// deliberately over-allocate to speculatively avoid frequent allocations.
	/// After calling `reserve_exact`, capacity will be greater than or equal to
	/// `self.len() + additional`. Does nothing if the capacity is already
	/// sufficient.
	///
	/// Note that the allocator may give the collection more space than it
	/// requests. Therefore, capacity can not be relied upon to be precisely
	/// minimal. Prefer [`reserve`] if future insertions are expected.
	///
	/// [`reserve`]: UniqueAlignedBuffer::reserve
	///
	/// # Panics
	///
	/// Panics if the new capacity is too large.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<32>::with_capacity(10);
	/// buf.reserve_exact(20);
	/// assert!(buf.capacity() >= 20);
	/// ```
	pub fn reserve_exact(&mut self, additional: usize) {
		// SAFETY: We're the unieue owner of the buffer.
		unsafe {
			self.buf.reserve_exact(self.len, additional);
		}
	}

	/// Tries to reserve capacity for at least `additional` more elements to be inserted
	/// in the given `UniqueAlignedBuffer`. The collection may reserve more space to speculatively avoid
	/// frequent reallocations. After calling `try_reserve`, capacity will be
	/// greater than or equal to `self.len() + additional` if it returns
	/// `Ok(())`. Does nothing if capacity is already sufficient. This method
	/// preserves the contents even if an error occurs.
	///
	/// # Errors
	///
	/// If the capacity overflows, or the allocator reports a failure, then an error
	/// is returned.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// # use aligned_buffer::TryReserveError;
	/// fn process_data(data: &[u32]) -> Result<UniqueAlignedBuffer<64>, TryReserveError> {
	///     let mut output = UniqueAlignedBuffer::<64>::new();
	///
	///     // Pre-reserve the memory, exiting if we can't
	///     output.try_reserve(data.len() * std::mem::size_of::<u32>())?;
	///
	///     // Now we know this can't OOM in the middle of our complex work
	///     output.extend(data.iter().flat_map(|&val| {
	///         u32::to_le_bytes(val * 2 + 5) // very complicated
	///     }));
	///
	///     Ok(output)
	/// }
	/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
	/// ```
	pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
		// SAFETY: We're the unieue owner of the buffer.
		unsafe {
			self
				.buf
				.try_reserve(self.len, additional)
				.map_err(TryReserveError::from)
		}
	}

	/// Tries to reserve the minimum capacity for at least `additional`
	/// elements to be inserted in the given `UniqueAlignedBuffer`. Unlike [`try_reserve`],
	/// this will not deliberately over-allocate to speculatively avoid frequent
	/// allocations. After calling `try_reserve_exact`, capacity will be greater
	/// than or equal to `self.len() + additional` if it returns `Ok(())`.
	/// Does nothing if the capacity is already sufficient.
	///
	/// Note that the allocator may give the collection more space than it
	/// requests. Therefore, capacity can not be relied upon to be precisely
	/// minimal. Prefer [`try_reserve`] if future insertions are expected.
	///
	/// [`try_reserve`]: Vec::try_reserve
	///
	/// # Errors
	///
	/// If the capacity overflows, or the allocator reports a failure, then an error
	/// is returned.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// # use aligned_buffer::TryReserveError;
	///
	/// fn process_data(data: &[u32]) -> Result<UniqueAlignedBuffer<64>, TryReserveError> {
	///     let mut output = UniqueAlignedBuffer::<64>::new();
	///
	///     // Pre-reserve the memory, exiting if we can't
	///     output.try_reserve_exact(data.len() * std::mem::size_of::<u32>())?;
	///
	///     // Now we know this can't OOM in the middle of our complex work
	///     output.extend(data.iter().flat_map(|&val| {
	///         u32::to_le_bytes(val * 2 + 5) // very complicated
	///     }));
	///
	///     Ok(output)
	/// }
	/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
	/// ```
	pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
		// SAFETY: We're the unieue owner of the buffer.
		unsafe {
			self
				.buf
				.try_reserve_exact(self.len, additional)
				.map_err(TryReserveError::from)
		}
	}

	/// Shrinks the capacity of the buffer as much as possible.
	///
	/// It will drop down as close as possible to the length but the allocator
	/// may still inform the buffer that there is space for a few more elements.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3]);
	/// assert!(buf.capacity() >= 10);
	/// buf.shrink_to_fit();
	/// assert!(buf.capacity() >= 3);
	/// ```
	pub fn shrink_to_fit(&mut self) {
		// The capacity is never less than the length, and there's nothing to do when
		// they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
		// by only calling it with a greater capacity.
		if self.capacity() > self.len {
			// SAFETY: We're the unieue owner of the buffer.
			unsafe {
				self.buf.shrink_to_fit(self.len);
			}
		}
	}

	/// Shrinks the capacity of the buffer with a lower bound.
	///
	/// The capacity will remain at least as large as both the length
	/// and the supplied value.
	///
	/// If the current capacity is less than the lower limit, this is a no-op.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3]);
	/// assert!(buf.capacity() >= 10);
	/// buf.shrink_to(4);
	/// assert!(buf.capacity() >= 4);
	/// buf.shrink_to(0);
	/// assert!(buf.capacity() >= 3);
	/// ```
	pub fn shrink_to(&mut self, min_capacity: usize) {
		if self.capacity() > min_capacity {
			// SAFETY: We're the unieue owner of the buffer.
			unsafe {
				self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
			}
		}
	}

	/// Shortens the buffer, keeping the first `len` elements and dropping
	/// the rest.
	///
	/// If `len` is greater or equal to the vector's current length, this has
	/// no effect.
	///
	/// Note that this method has no effect on the allocated capacity
	/// of the buffer.
	///
	/// # Examples
	///
	/// Truncating a five element buffer to two elements:
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3, 4, 5]);
	/// buf.truncate(2);
	/// assert_eq!(&*buf, &[1, 2]);
	/// ```
	///
	/// No truncation occurs when `len` is greater than the vector's current
	/// length:
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3, 4, 5]);
	/// buf.truncate(8);
	/// assert_eq!(&*buf, &[1, 2, 3, 4, 5]);
	/// ```
	///
	/// Truncating when `len == 0` is equivalent to calling the [`clear`]
	/// method.
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3, 4, 5]);
	/// buf.truncate(0);
	/// assert_eq!(&*buf, &[]);
	/// assert!(buf.is_empty());
	/// ```
	///
	/// [`clear`]: UniqueAlignedBuffer::clear
	pub fn truncate(&mut self, len: usize) {
		// Since we're dealing with plain old data, we can just change the len
		// without having to drop anything.
		self.len = cmp::min(len, self.len);
	}

	/// Extracts a slice containing the entire buffer.
	///
	/// Equivalent to `&s[..]`.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// use std::io::{self, Write};
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3, 5, 8]);
	/// io::sink().write(buf.as_slice()).unwrap();
	/// ```
	#[inline]
	pub fn as_slice(&self) -> &[u8] {
		self
	}

	/// Extracts a mutable slice of the entire buffer.
	///
	/// Equivalent to `&mut s[..]`.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// use std::io::{self, Read};
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([0; 3]);
	/// io::repeat(0b101).read_exact(buf.as_mut_slice()).unwrap();
	/// ```
	#[inline]
	pub fn as_mut_slice(&mut self) -> &mut [u8] {
		self
	}

	/// Returns a raw pointer to the buffer's data, or a dangling raw pointer
	/// valid for zero sized reads if the vector didn't allocate.
	///
	/// The caller must ensure that the buffer outlives the pointer this
	/// function returns, or else it will end up pointing to garbage.
	/// Modifying the buffer may cause its buffer to be reallocated,
	/// which would also make any pointers to it invalid.
	///
	/// The caller must also ensure that the memory the pointer (non-transitively) points to
	/// is never written to using this pointer or any pointer derived from it. If you need to
	/// mutate the contents of the slice, use [`as_mut_ptr`].
	///
	/// This method guarantees that for the purpose of the aliasing model, this method
	/// does not materialize a reference to the underlying slice, and thus the returned pointer
	/// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
	/// Note that calling other methods that materialize mutable references to the slice,
	/// or mutable references to specific elements you are planning on accessing through this pointer,
	/// as well as writing to those elements, may still invalidate this pointer.
	/// See the second example below for how this guarantee can be used.
	///
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 4]);
	/// let buf_ptr = buf.as_ptr();
	///
	/// unsafe {
	///     for i in 0..buf.len() {
	///         assert_eq!(*buf_ptr.add(i), 1 << i);
	///     }
	/// }
	/// ```
	///
	/// Due to the aliasing guarantee, the following code is legal:
	///
	/// ```rust
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// unsafe {
	///     let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	///     buf.extend([1, 2, 4]);
	///     let ptr1 = buf.as_ptr();
	///     let _ = ptr1.read();
	///     let ptr2 = buf.as_mut_ptr().offset(2);
	///     ptr2.write(2);
	///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`
	///     // because it mutated a different element:
	///     let _ = ptr1.read();
	/// }
	/// ```
	///
	/// [`as_mut_ptr`]: UniqueAlignedBuffer::as_mut_ptr
	/// [`as_ptr`]: UniqueAlignedBuffer::as_ptr
	#[inline]
	pub fn as_ptr(&self) -> *const u8 {
		// We shadow the slice method of the same name to avoid going through
		// `deref`, which creates an intermediate reference.
		self.buf.ptr()
	}

	/// Returns an unsafe mutable pointer to the buffer's data, or a dangling
	/// raw pointer valid for zero sized reads if the buffer didn't allocate.
	///
	/// The caller must ensure that the buffer outlives the pointer this
	/// function returns, or else it will end up pointing to garbage.
	/// Modifying the vector may cause its buffer to be reallocated,
	/// which would also make any pointers to it invalid.
	///
	/// This method guarantees that for the purpose of the aliasing model, this method
	/// does not materialize a reference to the underlying slice, and thus the returned pointer
	/// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
	/// Note that calling other methods that materialize references to the slice,
	/// or references to specific elements you are planning on accessing through this pointer,
	/// may still invalidate this pointer.
	/// See the second example below for how this guarantee can be used.
	///
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// // Allocate buffer big enough for 4 elements.
	/// let size = 4;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(size);
	/// let buf_ptr = buf.as_mut_ptr();
	///
	/// // Initialize elements via raw pointer writes, then set length.
	/// unsafe {
	///     for i in 0..size {
	///         *buf_ptr.add(i) = i as u8;
	///     }
	///     buf.set_len(size);
	/// }
	/// assert_eq!(&*buf, &[0, 1, 2, 3]);
	/// ```
	///
	/// Due to the aliasing guarantee, the following code is legal:
	///
	/// ```rust
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// unsafe {
	///     let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	///     buf.extend([0]);
	///     let ptr1 = buf.as_mut_ptr();
	///     ptr1.write(1);
	///     let ptr2 = buf.as_mut_ptr();
	///     ptr2.write(2);
	///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
	///     ptr1.write(3);
	/// }
	/// ```
	///
	/// [`as_mut_ptr`]: UniqueAlignedBuffer::as_mut_ptr
	/// [`as_ptr`]: UniqueAlignedBuffer::as_ptr
	#[inline]
	pub fn as_mut_ptr(&mut self) -> *mut u8 {
		// We shadow the slice method of the same name to avoid going through
		// `deref_mut`, which creates an intermediate reference.
		self.buf.ptr()
	}

	/// Forces the length of the buffer to `new_len`.
	///
	/// This is a low-level operation that maintains none of the normal
	/// invariants of the type. Normally changing the length of a buffer
	/// is done using one of the safe operations instead, such as
	/// [`truncate`], [`resize`], [`extend`], or [`clear`].
	///
	/// [`truncate`]: UniqueAlignedBuffer::truncate
	/// [`resize`]: UniqueAlignedBuffer::resize
	/// [`extend`]: Extend::extend
	/// [`clear`]: UniqueAlignedBuffer::clear
	///
	/// # Safety
	///
	/// - `new_len` must be less than or equal to [`capacity()`].
	/// - The elements at `old_len..new_len` must be initialized.
	///
	/// [`capacity()`]: UniqueAlignedBuffer::capacity
	///
	/// # Examples
	///
	/// This method can be useful for situations in which the buffer
	/// is serving as a buffer for other code, particularly over FFI:
	///
	/// ```no_run
	/// # #![allow(dead_code)]
	/// # // This is just a minimal skeleton for the doc example;
	/// # // don't use this as a starting point for a real library.
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
	/// # const Z_OK: i32 = 0;
	/// # extern "C" {
	/// #     fn deflateGetDictionary(
	/// #         strm: *mut std::ffi::c_void,
	/// #         dictionary: *mut u8,
	/// #         dictLength: *mut usize,
	/// #     ) -> i32;
	/// # }
	/// # impl StreamWrapper {
	/// pub fn get_dictionary(&self) -> Option<UniqueAlignedBuffer<16>> {
	///     // Per the FFI method's docs, "32768 bytes is always enough".
	///     let mut dict = UniqueAlignedBuffer::<16>::with_capacity(32_768);
	///     let mut dict_length = 0;
	///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
	///     // 1. `dict_length` elements were initialized.
	///     // 2. `dict_length` <= the capacity (32_768)
	///     // which makes `set_len` safe to call.
	///     unsafe {
	///         // Make the FFI call...
	///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
	///         if r == Z_OK {
	///             // ...and update the length to what was initialized.
	///             dict.set_len(dict_length);
	///             Some(dict)
	///         } else {
	///             None
	///         }
	///     }
	/// }
	/// # }
	/// ```
	///
	/// Normally, here, one would use [`clear`] instead to correctly drop
	/// the contents and thus not leak memory.
	#[inline]
	pub unsafe fn set_len(&mut self, new_len: usize) {
		debug_assert!(new_len <= self.capacity());

		self.len = new_len;
	}

	/// Appends an element to the back of a buffer.
	///
	/// # Panics
	///
	/// Panics if the new capacity is too large.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2]);
	/// buf.push(3);
	/// assert_eq!(&*buf, &[1, 2, 3]);
	/// ```
	#[inline]
	pub fn push(&mut self, value: u8) {
		// This will panic or abort if we would allocate too much.
		if self.len == self.buf.capacity() {
			// SAFETY: We're the unieue owner of the buffer.
			unsafe {
				self.buf.reserve(self.len, 1);
			}
		}

		unsafe {
			let end = self.as_mut_ptr().add(self.len);
			ptr::write(end, value);
			self.len += 1;
		}
	}

	/// Moves all the elements of `other` into `self`, leaving `other` empty.
	///
	/// # Panics
	///
	/// Panics if the new capacity exceeds `isize::MAX` bytes.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<128>::with_capacity(10);
	/// buf.extend([1, 2, 3]);
	/// let mut vec = vec![4u8, 5, 6];
	/// buf.append(&vec);
	/// assert_eq!(&*buf, &[1, 2, 3, 4, 5, 6]);
	/// assert_eq!(vec, [4, 5, 6]);
	/// ```
	#[inline]
	pub fn append(&mut self, other: &(impl AsRef<[u8]> + ?Sized)) {
		// Safety: `other` cannot overlap with `self.as_mut_slice()`,
		// because `self` is a unique reference.
		unsafe {
			self.append_elements(other.as_ref() as *const [u8]);
		}
	}

	/// Appends elements to `self` from other buffer.
	///
	/// # Safety
	/// This function requires that `other` does not overlap with `self.as_mut_slice()`.
	#[inline]
	unsafe fn append_elements(&mut self, other: *const [u8]) {
		let count = unsafe { (*other).len() };
		self.reserve(count);
		let len = self.len();
		unsafe { ptr::copy_nonoverlapping(other as *const u8, self.as_mut_ptr().add(len), count) };
		self.len += count;
	}

	/// Clears the buffer, removing all values.
	///
	/// Note that this method has no effect on the allocated capacity
	/// of the buffer.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3]);
	///
	/// buf.clear();
	///
	/// assert!(buf.is_empty());
	/// ```
	#[inline]
	pub fn clear(&mut self) {
		self.len = 0;
	}

	/// Returns the number of elements in the buffer, also referred to
	/// as its 'length'.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3]);
	/// assert_eq!(buf.len(), 3);
	/// ```
	#[inline]
	pub fn len(&self) -> usize {
		self.len
	}

	/// Returns `true` if the buffer contains no data.
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// assert!(buf.is_empty());
	///
	/// buf.push(1);
	/// assert!(!buf.is_empty());
	/// ```
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}

	/// Resizes the `UniqueAlignedBuffer` in-place so that `len` is equal to `new_len`.
	///
	/// If `new_len` is greater than `len`, the `UniqueAlignedBuffer` is extended by the
	/// difference, with each additional slot filled with `value`.
	/// If `new_len` is less than `len`, the `UniqueAlignedBuffer` is simply truncated.
	///
	/// If you only need to resize to a smaller size, use [`UniqueAlignedBuffer::truncate`].
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.resize(3, 42);
	/// assert_eq!(&*buf, &[42, 42, 42]);
	///
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1, 2, 3, 4]);
	/// buf.resize(2, 0);
	/// assert_eq!(&*buf, &[1, 2]);
	/// ```
	pub fn resize(&mut self, new_len: usize, value: u8) {
		let len = self.len();

		if new_len > len {
			self.extend_with(new_len - len, value)
		} else {
			self.truncate(new_len);
		}
	}

	/// Copies and appends all elements in a slice to the `UniqueAlignedBuffer`.
	///
	/// Iterates over the slice `other`, copies each element, and then appends
	/// it to this `UniqueAlignedBuffer`. The `other` slice is traversed in-order.
	///
	/// Note that this function is same as [`extend`] except that it is
	/// specialized to work with slices instead. If and when Rust gets
	/// specialization this function will likely be deprecated (but still
	/// available).
	///
	/// # Examples
	///
	/// ```
	/// # use aligned_buffer::UniqueAlignedBuffer;
	/// let mut buf = UniqueAlignedBuffer::<16>::with_capacity(10);
	/// buf.extend([1]);
	/// buf.extend_from_slice(&[2, 3, 4]);
	/// assert_eq!(&*buf, &[1, 2, 3, 4]);
	/// ```
	///
	/// [`extend`]: UniqueAlignedBuffer::extend
	pub fn extend_from_slice(&mut self, other: &[u8]) {
		self.append(other);
	}

	/// Extend the vector by `n` clones of value.
	fn extend_with(&mut self, n: usize, value: u8) {
		self.reserve(n);

		unsafe {
			let mut ptr = self.as_mut_ptr().add(self.len());
			// Use SetLenOnDrop to work around bug where compiler
			// might not realize the store through `ptr` through self.set_len()
			// don't alias.
			let mut local_len = SetLenOnDrop::new(&mut self.len);

			// Write all elements
			for _ in 0..n {
				ptr::write(ptr, value);
				ptr = ptr.add(1);
			}

			local_len.increment_len(n);
			// len set by scope guard
		}
	}
}

impl<const ALIGNMENT: usize> ops::Deref for UniqueAlignedBuffer<ALIGNMENT> {
	type Target = [u8];

	#[inline]
	fn deref(&self) -> &Self::Target {
		unsafe { std::slice::from_raw_parts(self.as_ptr(), self.len()) }
	}
}

impl<const ALIGNMENT: usize> ops::DerefMut for UniqueAlignedBuffer<ALIGNMENT> {
	#[inline]
	fn deref_mut(&mut self) -> &mut [u8] {
		unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len()) }
	}
}

impl<I: SliceIndex<[u8]>, const ALIGNMENT: usize> ops::Index<I> for UniqueAlignedBuffer<ALIGNMENT> {
	type Output = I::Output;

	#[inline]
	fn index(&self, index: I) -> &Self::Output {
		ops::Index::index(&**self, index)
	}
}

impl<I: SliceIndex<[u8]>, const ALIGNMENT: usize> ops::IndexMut<I>
	for UniqueAlignedBuffer<ALIGNMENT>
{
	#[inline]
	fn index_mut(&mut self, index: I) -> &mut Self::Output {
		ops::IndexMut::index_mut(&mut **self, index)
	}
}

impl<const ALIGNMENT: usize> FromIterator<u8> for UniqueAlignedBuffer<ALIGNMENT> {
	#[inline]
	fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
		let iter = iter.into_iter();
		let (lower, _) = iter.size_hint();
		let mut buf = Self::with_capacity(lower);
		buf.extend(iter);
		buf
	}
}

impl<const ALIGNMENT: usize> Extend<u8> for UniqueAlignedBuffer<ALIGNMENT> {
	#[inline]
	fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
		let mut iter = iter.into_iter();
		let (lower, _) = iter.size_hint();
		self.reserve(lower);
		let free = self.capacity() - self.len();

		unsafe {
			let mut ptr = self.as_mut_ptr().add(self.len());
			// Use SetLenOnDrop to work around bug where compiler
			// might not realize the store through `ptr` through self.set_len()
			// don't alias.
			let mut local_len = SetLenOnDrop::new(&mut self.len);

			// Write elements until we run out of space or the iterator ends
			// (whichever comes first). We don't use `for-each` because we need to
			// keep the iterator alive in case not all elements fit in the
			// allocated capacity. This can happen if the iterator is not an
			// exact size iterator, or simply gives out a lower bound that is
			// not exact.
			// Note: if we could specialize on the iterator type, we could use
			// ExactSizeIterator to avoid the free check.
			for _ in 0..free {
				let Some(byte) = iter.next() else {
					// We're done, so we can just return
					return;
				};

				ptr::write(ptr, byte);
				ptr = ptr.add(1);
				// Increment the length in every step in case next() panics
				local_len.increment_len(1);
			}

			// len set by scope guard
		}

		// write the remainder of the iter using push
		for byte in iter {
			self.push(byte);
		}
	}
}

impl<const ALIGNMENT: usize> Default for UniqueAlignedBuffer<ALIGNMENT> {
	fn default() -> Self {
		Self::new()
	}
}

impl<const ALIGNMENT: usize> fmt::Debug for UniqueAlignedBuffer<ALIGNMENT> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Debug::fmt(&**self, f)
	}
}

impl<const ALIGNMENT: usize> AsRef<[u8]> for UniqueAlignedBuffer<ALIGNMENT> {
	#[inline]
	fn as_ref(&self) -> &[u8] {
		self
	}
}

impl<const ALIGNMENT: usize> AsMut<[u8]> for UniqueAlignedBuffer<ALIGNMENT> {
	#[inline]
	fn as_mut(&mut self) -> &mut [u8] {
		self
	}
}

struct SetLenOnDrop<'a> {
	len: &'a mut usize,
	local_len: usize,
}

impl<'a> SetLenOnDrop<'a> {
	#[inline]
	pub(super) fn new(len: &'a mut usize) -> Self {
		SetLenOnDrop {
			local_len: *len,
			len,
		}
	}

	#[inline]
	pub(super) fn increment_len(&mut self, increment: usize) {
		self.local_len += increment;
	}
}

impl Drop for SetLenOnDrop<'_> {
	#[inline]
	fn drop(&mut self) {
		*self.len = self.local_len;
	}
}