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
use super::*;

/// Record of the results of a copy operation
#[derive(Debug, Copy, Clone)]
pub struct CopyRecord {
    /// The offset from the start of the allocation, in bytes, at which the
    /// copy operation began to write data.
    ///
    /// Not necessarily equal to the `start_offset` provided to the copy function, since this offset
    /// includes necessary padding to assure alignment.
    pub start_offset: usize,

    /// The offset from the start of the allocation, in bytes, at which the
    /// copy operation no longer wrote data.
    ///
    /// This does not include any padding at the end necessary to maintain
    /// alignment requirements.
    ///
    /// Unless you have a good reason otherwise, you *likely* want to use
    /// [`end_offset_padded`][CopyRecord::end_offset_padded] instead.
    pub end_offset: usize,

    /// The offset from the start of the allocation, in bytes, at which the
    /// copy operation no longer wrote data, plus any padding necessary to
    /// maintain derived alignment requirements.
    pub end_offset_padded: usize,
}

impl From<ComputedOffsets> for CopyRecord {
    fn from(
        ComputedOffsets {
            start,
            end,
            end_padded,
        }: ComputedOffsets,
    ) -> Self {
        Self {
            start_offset: start,
            end_offset: end,
            end_offset_padded: end_padded,
        }
    }
}

/// Copies `src` into the memory represented by `dst` starting at *exactly*
/// `start_offset` bytes past the start of `dst`
///
/// - `start_offset` is the offset into the allocation represented by `dst`, in bytes,
/// where the first byte of the copied data will be placed. If the requested
/// start offset does not satisfy computed alignment requirements, an error will
/// be returned and no data will be copied.
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline(always)]
pub fn copy_to_offset_exact<T: Copy, S: Slab + ?Sized>(
    src: &T,
    dst: &mut S,
    start_offset: usize,
) -> Result<CopyRecord, Error> {
    copy_to_offset_with_align_exact(src, dst, start_offset, 1)
}

/// Copies `src` into the memory represented by `dst` starting at *exactly*
/// `start_offset` bytes past the start of `dst` and with minimum alignment
/// `min_alignment`. If the requested parameters would be violated by computed alignment requirements,
/// an error will be returned.
///
/// - `start_offset` is the offset into the allocation represented by `dst`, in bytes,
/// where the first byte of the copied data will be placed. If the requested
/// start offset does not satisfy computed alignment requirements, an error will
/// be returned and no data will be copied.
/// - `min_alignment` is the minimum alignment that you are requesting the copy be aligned to. The
/// copy may be aligned greater than `min_alignment` depending on the alignment requirements
/// of `T` (the actual alignment will be the greater of the two between `align_of::<T>()` and
/// `min_align.next_power_of_two()`).
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline(always)]
pub fn copy_to_offset_with_align_exact<T: Copy, S: Slab + ?Sized>(
    src: &T,
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<CopyRecord, Error> {
    let t_layout = Layout::new::<T>();
    let offsets = compute_and_validate_offsets(&*dst, start_offset, t_layout, min_alignment, true)?;

    // SAFETY: if compute_offsets succeeded, this has already been checked to be safe.
    let dst_ptr = unsafe { dst.base_ptr_mut().add(offsets.start) }.cast::<T>();

    // SAFETY:
    // - src is valid as we have a reference to it
    // - dst is valid so long as requirements for `slab` were met, i.e.
    // we have unique access to the region described and that it is valid for the duration
    // of 'a.
    // - areas not overlapping as long as safety requirements of creation of `self` were met,
    // i.e. that we have exclusive access to the region of memory described.
    // - dst aligned at least to align_of::<T>()
    // - checked that copy stays within bounds of our allocation
    unsafe {
        core::ptr::copy_nonoverlapping(src as *const T, dst_ptr, 1);
    }

    Ok(offsets.into())
}

/// Copies `src` into the memory represented by `dst` starting at a minimum location
/// of `start_offset` bytes past the start of `dst`.
///
/// - `start_offset` is the offset into the allocation represented by `dst`,
/// in bytes, before which any copied data will *certainly not* be placed. However,
/// the actual beginning of the copied data may not be exactly at `start_offset` if
/// padding bytes are needed to satisfy alignment requirements. The actual beginning
/// of the copied bytes is contained in the returned [`CopyRecord`].
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline]
pub fn copy_to_offset<T: Copy, S: Slab + ?Sized>(
    src: &T,
    dst: &mut S,
    start_offset: usize,
) -> Result<CopyRecord, Error> {
    copy_to_offset_with_align(src, dst, start_offset, 1)
}

/// Copies `src` into the memory represented by `dst` starting at a minimum location
/// of `start_offset` bytes past the start of `dst` and with minimum alignment
/// `min_alignment`.
///
/// - `start_offset` is the offset into the allocation represented by `dst`,
/// in bytes, before which any copied data will *certainly not* be placed. However,
/// the actual beginning of the copied data may not be exactly at `start_offset` if
/// padding bytes are needed to satisfy alignment requirements. The actual beginning
/// of the copied bytes is contained in the returned [`CopyRecord`].
/// - `min_alignment` is the minimum alignment to which the copy will be aligned. The
/// copy may not actually be aligned to `min_alignment` depending on the alignment requirements
/// of `T` (the actual alignment will be the greater between `align_of::<T>` and `min_align.next_power_of_two()`).
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline]
pub fn copy_to_offset_with_align<T: Copy, S: Slab + ?Sized>(
    src: &T,
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<CopyRecord, Error> {
    let t_layout = Layout::new::<T>();
    let offsets =
        compute_and_validate_offsets(&*dst, start_offset, t_layout, min_alignment, false)?;

    // SAFETY: if compute_offsets succeeded, this has already been checked to be safe.
    let dst_ptr = unsafe { dst.base_ptr_mut().add(offsets.start) }.cast::<T>();

    // SAFETY:
    // - src is valid as we have a reference to it
    // - dst is valid so long as requirements for `slab` were met, i.e.
    // we have unique access to the region described and that it is valid for the duration
    // of 'a.
    // - areas not overlapping as long as safety requirements of creation of `self` were met,
    // i.e. that we have exclusive access to the region of memory described.
    // - dst aligned at least to align_of::<T>()
    // - checked that copy stays within bounds of our allocation
    unsafe {
        core::ptr::copy_nonoverlapping(src as *const T, dst_ptr, 1);
    }

    Ok(offsets.into())
}

/// Copies from `slice` into the memory represented by `dst` starting at *exactly*
/// `start_offset` bytes past the start of `self`.
///
/// - `start_offset` is the offset into the allocation represented by `dst`, in bytes,
/// where the first byte of the copied data will be placed. If the requested
/// start offset does not satisfy computed alignment requirements, an error will
/// be returned and no data will be copied.
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline]
pub fn copy_from_slice_to_offset_exact<T: Copy, S: Slab + ?Sized>(
    src: &[T],
    dst: &mut S,
    start_offset: usize,
) -> Result<CopyRecord, Error> {
    copy_from_slice_to_offset_with_align(src, dst, start_offset, 1)
}

/// Copies from `slice` into the memory represented by `dst` starting at *exactly*
/// `start_offset` bytes past the start of `dst` and with minimum alignment `min_alignment`.
///
/// - `start_offset` is the offset into the allocation represented by `dst`, in bytes,
/// where the first byte of the copied data will be placed. If the requested
/// start offset does not satisfy computed alignment requirements, an error will
/// be returned and no data will be copied.
/// - `min_alignment` is the minimum alignment that you are requesting the copy be aligned to. The
/// copy may be aligned greater than `min_alignment` depending on the alignment requirements
/// of `T` (the actual alignment will be the greater of the two between `align_of::<T>()` and
/// `min_align.next_power_of_two()`).
///     - The whole data of the slice will be copied directly, so, alignment between elements
///     ignores `min_alignment`.
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline]
pub fn copy_from_slice_to_offset_with_align_exact<T: Copy, S: Slab + ?Sized>(
    src: &[T],
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<CopyRecord, Error> {
    let t_layout = Layout::for_value(src);
    let offsets = compute_and_validate_offsets(&*dst, start_offset, t_layout, min_alignment, true)?;

    // SAFETY: if compute_offsets succeeded, this has already been checked to be safe.
    let dst_ptr = unsafe { dst.base_ptr_mut().add(offsets.start) }.cast::<T>();

    // SAFETY:
    // - src is valid as we have a reference to it
    // - dst is valid so long as requirements for `slab` were met, i.e.
    // we have unique access to the region described and that it is valid for the duration
    // of 'a.
    // - areas not overlapping as long as safety requirements of creation of `self` were met,
    // i.e. that we have exclusive access to the region of memory described.
    // - dst aligned at least to align_of::<T>()
    // - checked that copy stays within bounds of our allocation
    unsafe {
        core::ptr::copy_nonoverlapping(src.as_ptr(), dst_ptr, src.len());
    }

    Ok(offsets.into())
}

/// Copies from `slice` into the memory represented by `dst` starting at a minimum location
/// of `start_offset` bytes past the start of `self`.
///
/// - `start_offset` is the offset into the allocation represented by `dst`,
/// in bytes, before which any copied data will *certainly not* be placed. However,
/// the actual beginning of the copied data may not be exactly at `start_offset` if
/// padding bytes are needed to satisfy alignment requirements. The actual beginning
/// of the copied bytes is contained in the returned [`CopyRecord`].
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline]
pub fn copy_from_slice_to_offset<T: Copy, S: Slab + ?Sized>(
    src: &[T],
    dst: &mut S,
    start_offset: usize,
) -> Result<CopyRecord, Error> {
    copy_from_slice_to_offset_with_align(src, dst, start_offset, 1)
}

/// Copies from `slice` into the memory represented by `dst` starting at a minimum location
/// of `start_offset` bytes past the start of `dst`.
///
/// - `start_offset` is the offset into the allocation represented by `dst`,
/// in bytes, before which any copied data will *certainly not* be placed. However,
/// the actual beginning of the copied data may not be exactly at `start_offset` if
/// padding bytes are needed to satisfy alignment requirements. The actual beginning
/// of the copied bytes is contained in the returned [`CopyRecord`].
/// - `min_alignment` is the minimum alignment that you are requesting the copy be aligned to. The
/// copy may be aligned greater than `min_alignment` depending on the alignment requirements
/// of `T` (the actual alignment will be the greater of the two between `align_of::<T>()` and
/// `min_align.next_power_of_two()`).
///     - The whole data of the slice will be copied directly, so alignment between elements
///     ignores `min_alignment`.
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[inline]
pub fn copy_from_slice_to_offset_with_align<T: Copy, S: Slab + ?Sized>(
    src: &[T],
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<CopyRecord, Error> {
    let t_layout = Layout::for_value(src);
    let offsets =
        compute_and_validate_offsets(&*dst, start_offset, t_layout, min_alignment, false)?;

    // SAFETY: if compute_offsets succeeded, this has already been checked to be safe.
    let dst_ptr = unsafe { dst.base_ptr_mut().add(offsets.start) }.cast::<T>();

    // SAFETY:
    // - src is valid as we have a reference to it
    // - dst is valid so long as requirements for `slab` were met, i.e.
    // we have unique access to the region described and that it is valid for the duration
    // of 'a.
    // - areas not overlapping as long as safety requirements of creation of `self` were met,
    // i.e. that we have exclusive access to the region of memory described.
    // - dst aligned at least to align_of::<T>()
    // - checked that copy stays within bounds of our allocation
    unsafe {
        core::ptr::copy_nonoverlapping(src.as_ptr(), dst_ptr, src.len());
    }

    Ok(offsets.into())
}

/// Copies from `src` iterator into the memory represented by `dst` starting at a minimum location
/// of `start_offset` bytes past the start of `dst`.
///
/// Returns a vector of [`CopyRecord`]s, one for each item in the `src` iterator.
///
/// - `start_offset` is the offset into the allocation represented by `dst`,
/// in bytes, before which any copied data will *certainly not* be placed. However,
/// the actual beginning of the copied data may not be exactly at `start_offset` if
/// padding bytes are needed to satisfy alignment requirements. The actual beginning
/// of the copied bytes is contained in the returned [`CopyRecord`]s.
/// - `min_alignment` is the minimum alignment that you are requesting the copy be aligned to. The
/// copy may be aligned greater than `min_alignment` depending on the alignment requirements
/// of `T` (the actual alignment will be the greater of the two between `align_of::<T>()` and
/// `min_align.next_power_of_two()`).
/// - For this variation, `min_alignment` will also be respected *between* elements yielded by
/// the iterator. To copy inner elements aligned only to `align_of::<T>()` (i.e. with the layout of
/// an `[T]`), see [`copy_from_iter_to_offset_with_align_packed`].
///
/// # Safety
///
/// This function is safe on its own, however it is very possible to do unsafe
/// things if you read the copied data in the wrong way. See the
/// [crate-level Safety documentation][`crate#safety`] for more.
#[cfg(feature = "std")]
#[inline]
pub fn copy_from_iter_to_offset_with_align<T: Copy, Iter: Iterator<Item = T>, S: Slab + ?Sized>(
    src: Iter,
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<Vec<CopyRecord>, Error> {
    let mut offset = start_offset;

    src.map(|item| {
        let copy_record = copy_to_offset_with_align(&item, dst, offset, min_alignment)?;
        offset = copy_record.end_offset;
        Ok(copy_record)
    })
    .collect::<Result<Vec<_>, _>>()
}

/// Like [`copy_from_iter_to_offset_with_align`] except that
/// alignment between elements yielded by the iterator will ignore `min_alignment`
/// and rather only be aligned to the alignment of `T`.
///
/// Because of this, only one [`CopyRecord`] is returned specifying the record of the
/// entire block of copied data. If the `src` iterator is empty, returns `None`.
#[inline]
pub fn copy_from_iter_to_offset_with_align_packed<
    T: Copy,
    Iter: Iterator<Item = T>,
    S: Slab + ?Sized,
>(
    mut src: Iter,
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<Option<CopyRecord>, Error> {
    let first_record = if let Some(first_item) = src.next() {
        copy_to_offset_with_align(&first_item, dst, start_offset, min_alignment)?
    } else {
        return Ok(None);
    };

    let mut prev_record = first_record;

    for item in src {
        let copy_record = copy_to_offset_with_align(&item, dst, prev_record.end_offset, 1)?;
        prev_record = copy_record;
    }

    Ok(Some(CopyRecord {
        start_offset: first_record.start_offset,
        end_offset: prev_record.end_offset,
        end_offset_padded: prev_record.end_offset_padded,
    }))
}

/// Like [`copy_from_iter_to_offset_with_align_packed`] except that it will return an error
/// and no data will be copied if the supplied `start_offset` doesn't meet the computed alignment
/// requirements.
#[inline]
pub fn copy_from_iter_to_offset_with_align_exact_packed<
    T: Copy,
    Iter: Iterator<Item = T>,
    S: Slab + ?Sized,
>(
    mut src: Iter,
    dst: &mut S,
    start_offset: usize,
    min_alignment: usize,
) -> Result<Option<CopyRecord>, Error> {
    let first_record = if let Some(first_item) = src.next() {
        copy_to_offset_with_align_exact(&first_item, dst, start_offset, min_alignment)?
    } else {
        return Ok(None);
    };

    let mut prev_record = first_record;

    for item in src {
        let copy_record = copy_to_offset_with_align_exact(&item, dst, prev_record.end_offset, 1)?;
        prev_record = copy_record;
    }

    Ok(Some(CopyRecord {
        start_offset: first_record.start_offset,
        end_offset: prev_record.end_offset,
        end_offset_padded: prev_record.end_offset_padded,
    }))
}