-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1752 lines (1557 loc) · 60.7 KB
/
lib.rs
File metadata and controls
1752 lines (1557 loc) · 60.7 KB
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
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Machinery to support functions that return unsized values.
//!
//! Written to support the [`unsized-vec`] crate, but is independent of it.
//! Requires nightly Rust.
//!
//! Unsized values can take many forms:
//!
//! - On stable Rust, values of unsized types like [`str`],
//! `[u8]`, and `dyn Any` are generally encountered behind a pointer,
//! like `&str` or `Box<dyn Any>`.
//!
//! - Nightly Rust provides limited support for passing unsized values
//! by value as arguments to functions, using the `unsized_fn_params`
//! feature. There is also `unsized_locals`, for storing these values
//! on the stack using alloca. (However, that feature is "incomplete" and
//! this crate doesn't make use of it). But even with thse two feature
//! gates enabled, functions cannot return unsized values directly.
//! Also, the only way to produce a by-value unsized value in today's Rust
//! is by dereferencing a [`Box`]; this crate provides the [`unsize`] macro
//! to work around this limitation.
//!
//! - For functions that return unsized values, this crate
//! provides the [`Emplacable`] type. Functions that want
//! to return a value of type `T`, where `T` is unsized, return an
//! `Emplacable<T, _>` instead. `Emplacable<T>` wraps a closure;
//! that closure contains instructions for writing out a `T` to
//! a caller-provided region of memory. Other functions accept the `Emplacable`
//! as an argument and call its contained closure to write out the
//! `T` to some allocation provided by them. For example, this crate
//! provides the [`box_new_with`] function, which turns an `Emplacable<T>`
//! into a [`Box<T>`].
//!
//! ## Converting between types
//!
//! | I have | I want | I can use |
//! |---------------------------|----------------------------|------------------------------|
//! | `[i32; 2]` | `[i32]` | [`unsize`] |
//! | `[i32; 2]` | `Emplacable<[i32; 2], _>` | [`Into::into`] |
//! | `[i32]` | `Emplacable<[i32], _>` | [`with_emplacable_for`] |
//! | `[i32]` | `Box<[i32]>` | [`box_new`] |
//! | `Box<[i32; 2]>` | `Box<[i32]>` | [`CoerceUnsized`] |
//! | `Box<[i32]>` | `[i32]` | dereference the box with `*` |
//! | `Box<[i32]>` | `Emplacable<[i32], _>` | [`Into::into`] |
//! | `Vec<i32>` | `Emplacable<[i32], _>` | [`Into::into`] |
//! | `Emplacable<[i32; 2], _>` | `[i32; 2]` | [`Emplacable::get`] |
//! | `Emplacable<[i32; 2], _>` | `Emplacable<[i32], _>` | [`Into::into`] |
//! | `Emplacable<[i32; 2], _>` | `Emplacable<dyn Debug, _>` | [`Emplacable::unsize`] |
//! | `Emplacable<[i32], _>` | `Box<[i32]>` | [`box_new_with`] |
//! | `Emplacable<[i32], _>` | `Vec<i32>` | [`Into::into`] |
//! | `Emplacable<[i32], _>` | `Rc<[i32]>` | [`Into::into`] |
//! | `Emplacable<[i32], _>` | `Arc<[i32]>` | [`Into::into`] |
//! | `&[i32]` | `Box<[i32]>` | [`Into::into`] |
//! | `&[i32]` | `Emplacable<[i32], _>` | [`Into::into`] |
//!
//! You can replace `[i32; 2]` and `[i32]` above by any pair of types (`T`, `U`)
//! such that [`T: Unsize<U>`][`Unsize`].
//!
//! ## A note on examples
//!
//! This crate has very few examples, as it provides tools to work with unsized types
//! but no fun things that use the tools. If you want more usage examples,
//! check out `unsized-vec`'s documentation and the `examples` folder on GitHub.
//!
//! [`unsized-vec`]: https://docs.rs/unsized-vec/
//! [`Unsize`]: core::marker::Unsize
//! [`CoerceUnsized`]: core::ops::CoerceUnsized
#![forbid(
clippy::alloc_instead_of_core,
clippy::std_instead_of_alloc,
clippy::std_instead_of_core
)]
#![allow(internal_features)] // for `unsized_fn_params`
#![feature(
allocator_api,
closure_lifetime_binder,
forget_unsized,
impl_trait_in_assoc_type,
min_specialization,
ptr_metadata,
super_let,
type_alias_impl_trait,
unsize,
unsized_fn_params
)]
#![no_std]
#[cfg(feature = "alloc")]
#[doc(hidden)]
pub extern crate alloc as alloc_crate;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "alloc")]
use alloc_crate::{alloc, boxed::Box, ffi::CString, rc::Rc, string::String, sync::Arc, vec::Vec};
use core::{
alloc::Layout,
ffi::CStr,
marker::{PhantomData, Unsize},
mem::{self, ManuallyDrop, MaybeUninit},
ops::FnMut,
pin::Pin,
ptr::{self, addr_of, Pointee},
};
#[cfg(feature = "std")]
use std::{
ffi::{OsStr, OsString},
path::{Path, PathBuf},
};
#[doc(hidden)]
pub mod macro_exports {
#[cfg(feature = "alloc")]
pub use alloc_crate;
pub use core;
pub use u8;
use alloc_crate::boxed::Box;
use core::{
alloc::{AllocError, Allocator, Layout},
cell::Cell,
marker::{PhantomData, Unsize},
mem::{self, MaybeUninit},
ptr::{self, NonNull},
};
// Implementation detail of `unsize` macro.
#[cfg_attr(not(debug_assertions), repr(transparent))]
pub struct ImplementationDetailDoNotUse<T> {
storage: Cell<MaybeUninit<T>>,
#[cfg(debug_assertions)]
allocated: bool,
}
pub type ImplementationDetailDoNotUseBox<'a, T, S> =
Box<T, &'a ImplementationDetailDoNotUse<S>>;
pub fn do_not_use_box_unsize<T, S>(
val: S,
a: &ImplementationDetailDoNotUse<S>,
) -> ImplementationDetailDoNotUseBox<'_, T, S>
where
T: ?Sized,
S: Unsize<T>,
{
let boxed: ImplementationDetailDoNotUseBox<'_, S, S> = Box::new_in(val, a);
boxed
}
impl<T> ImplementationDetailDoNotUse<T> {
#[allow(clippy::declare_interior_mutable_const)]
pub const NEW: Self = Self {
storage: Cell::new(MaybeUninit::uninit()),
#[cfg(debug_assertions)]
allocated: false,
};
}
// SAFETY: this is an unsound implementation of the trait,
// you can't `allocate` more than once without UB. We are careful not
// to break this invariant inside the macro, but `ImplementationDetailDoNotUse`
// should not be leaked to arbritrary code!
unsafe impl<T> Allocator for &ImplementationDetailDoNotUse<T> {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
debug_assert_eq!(layout, Layout::new::<T>());
#[cfg(debug_assertions)]
debug_assert!(!self.allocated);
// SAFETY: Address of `self.0` can't be null
let thin_ptr = unsafe { NonNull::new_unchecked(self.storage.as_ptr()) };
Ok(NonNull::from_raw_parts(thin_ptr, mem::size_of::<T>()))
}
unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {}
}
// Implementation detail of `by_value_str`.
pub struct NonAllocator<'a>(PhantomData<&'a mut ()>);
// SAFETY: `allocate` is a stub that is never run and always panics
unsafe impl Allocator for NonAllocator<'_> {
fn allocate(&self, _: Layout) -> Result<NonNull<[u8]>, AllocError> {
unreachable!()
}
#[inline]
unsafe fn deallocate(&self, _: NonNull<u8>, _: Layout) {}
}
pub type FakeBoxStr<'a> = Box<str, NonAllocator<'a>>;
pub fn fake_box_str<const LEN: usize>(buf: &mut [MaybeUninit<u8>; LEN]) -> FakeBoxStr<'_> {
let wide_ptr: *mut str = ptr::from_raw_parts_mut(buf.as_mut_ptr(), LEN);
// SAFETY: `NonAllocator::deallocate()` is a no-op
unsafe { Box::from_raw_in(wide_ptr, NonAllocator(PhantomData)) }
}
}
/// Helper for coercing values to unsized types.
///
/// The `unsized_fn_params` has some rough edges when it comes to coercing
/// sized values to unsized ones by value. This macro works around that.
///
/// If you have a value `val` of type `SizedType`, and you want to coerce it
/// to `UnsizedType`, write `unsize!(val, (SizedType) -> UnsizedType))`.
///
/// Probably useless without the `unsized_fn_params` or `unsized_locals` nightly features.
///
/// Requires the `alloc` crate feature
/// (though doesn't actually allocate on the heap),
/// as well as the `super_let` Rust feature.
///
/// # Example
///
/// ```
/// #![allow(internal_features)] // for `unsized_fn_params`
/// #![feature(unsized_fn_params, super_let)]
///
/// use core::fmt::Debug;
///
/// use emplacable::{box_new, unsize};
///
/// let mut my_box: Box<dyn Debug> = box_new(unsize!("hello world!", (&str) -> dyn Debug));
///
/// dbg!(&my_box);
/// ```
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! unsize {
($e:expr, ($src:ty) -> $dst:ty) => {*{
// To make the coercion happen, we:
// 1. Make a fake "allocator" that just stores
// `mem::size_of<$src>()` bytes on the stack
// 2. Allocate our sized value in a `Box` in our fake allocator
// 3. Coerce the box to hold an unsized value
// 4. Move out of the box
use $crate::{
macro_exports::{
do_not_use_box_unsize,
ImplementationDetailDoNotUse,
ImplementationDetailDoNotUseBox,
},
};
let val: $src = $e;
super let new_alloc: ImplementationDetailDoNotUse<$src> = ImplementationDetailDoNotUse::NEW;
let boxed_unsized: ImplementationDetailDoNotUseBox<$dst, $src> = do_not_use_box_unsize(val, &new_alloc);
boxed_unsized
}};
}
/// Construct a `str` from a string literal,
/// in its dereferenced form.
///
/// Probably useless without the `unsized_fn_params` or `unsized_locals` nightly features.
///
/// Requires the `alloc` crate feature
/// (though doesn't actually allocate on the heap).
///
/// # Example
///
/// ```
/// #![allow(internal_features)] // for `unsized_fn_params`
/// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
///
/// use emplacable::{box_new, by_value_str};
///
/// let boxed_str: Box<str> = box_new(by_value_str!("why hello there"));
/// dbg!(&*boxed_str);
/// ```
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! by_value_str {
($s:literal) => {{
// This implementation is similar to the one from `unsize`.
// 1. Declare a constant `&str` for the string
// 2. Copy the contents of the constant into a buffer
// 5. Convert a pointer into the buffer into a `Box<str>`
// 4. Move out of the box
use $crate::macro_exports::{
alloc_crate::boxed::Box,
core::{
mem::MaybeUninit,
ptr::{self, addr_of_mut},
},
fake_box_str, u8,
};
const STRING: &str = $s;
const LEN: usize = STRING.len();
let mut buf: [MaybeUninit<u8>; LEN] = [MaybeUninit::uninit(); LEN];
// SAFETY: `buf` has compatible layout
unsafe {
ptr::copy(STRING.as_ptr().cast::<u8>(), addr_of_mut!(buf).cast(), LEN);
}
let boxed = fake_box_str(&mut buf);
*boxed
}};
}
mod with_emplacable_for {
use super::*;
/// `EmplacableFn` used by [`with_emplacable_for`].
pub type WithEmplacableForFn<'a, T: ?Sized + 'a> = impl EmplacableFn<T> + 'a;
#[define_opaque(WithEmplacableForFn)]
pub fn with_emplacable_closure<T: ?Sized>(val: &mut T) -> WithEmplacableForFn<'_, T> {
move |emplacer: &mut Emplacer<'_, T>| {
let layout = Layout::for_value(val);
let metadata = ptr::metadata(val);
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(layout, metadata, &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: copying value where it belongs.
// We `forget` right after to prevent double-free.
// `Emplacer` preconditions say this can only be run once.
unsafe {
ptr::copy_nonoverlapping(
ptr::addr_of_mut!(*val).cast::<u8>(),
out_ptr.cast(),
layout.size(),
);
}
} else {
// SAFETY: we `mem::forget` `val` later to avoid double-drop
unsafe { ptr::drop_in_place(val) }
}
});
}
}
}
use with_emplacable_for::with_emplacable_closure;
pub use with_emplacable_for::WithEmplacableForFn;
/// Accepts a possibly-unsized value as a first argument,
/// turns it into an [`Emplacable`], and passes the emplacer to
/// the given closure.
///
/// If `T` is sized, you can use [`Into::into`] instead.
///
/// # Example
///
/// ```
/// #![allow(internal_features)] // for `unsized_fn_params`
/// #![feature(allocator_api, ptr_metadata, unsized_fn_params)]
///
/// use emplacable::{box_new_with, unsize, with_emplacable_for};
///
/// let b = with_emplacable_for(unsize!([23_i32, 4, 32], ([i32; 3]) -> [i32]), |e| {
/// box_new_with(e)
/// });
/// assert_eq!(&*b, &[23_i32, 4, 32]);
/// ```
#[cfg(not(all(doctest, not(feature = "alloc"))))]
#[inline]
pub fn with_emplacable_for<T, F, R>(mut val: T, mut f: F) -> R
where
T: ?Sized + 'static,
F: FnMut(Emplacable<T, WithEmplacableForFn<'_, T>>) -> R,
{
/// SAFETY: `val` must not be dropped after this function completes.
#[inline]
unsafe fn with_emplacable_for_inner<'a, T: ?Sized + 'a, R>(
val: &'a mut T,
f: &mut dyn FnMut(Emplacable<T, WithEmplacableForFn<'a, T>>) -> R,
) -> R {
// SAFETY: closure fulfills safety preconditions
let emplacable = unsafe { Emplacable::from_fn(with_emplacable_closure(val)) };
f(emplacable)
}
// SAFETY: we `forget_unsized` val immediately after this call
let ret = unsafe { with_emplacable_for_inner(&mut val, &mut f) };
mem::forget_unsized(val);
ret
}
/// Alias of [`for<'a> FnOnce(&'a mut Emplacer<T>)`](Emplacer<T>).
pub trait EmplacableFn<T>: for<'a> FnOnce(&'a mut Emplacer<'_, T>)
where
T: ?Sized,
{
}
impl<T, F> EmplacableFn<T> for F
where
T: ?Sized,
F: for<'a> FnOnce(&'a mut Emplacer<'_, T>),
{
}
/// A wrapped closure that you can pass to functions like `box_new_with`,
/// that describes how to write a value of type `T` to a caller-provided
/// allocation. You can get a `T` out of an `Emplacable` through functions like
/// [`box_new_with`]. Alternately, you can drop the value of type `T` by dropping
/// the `Emplacable`. Or you can forget the value of type `T` with [`Emplacable::forget`].
///
/// ## How it works
///
/// To make an [`Emplacable<T, _>`], you must first produce an [`EmplacableFn<T>`],
/// which is an [`FnOnce`] that accepts an [`Emplacer<T>`]. Your [`EmplacableFn<T>`] perform the follwoing steps:
///
/// 1. Call [`into_fn`][`Emplacer::into_fn`] on the [`Emplacer<T>`] to obtain a [`EmplacerFn<T>`], which is an alias for
/// `dyn FnMut(Layout, <T as Pointee>::Metadata, &mut (dyn FnMut(*mut PhantomData<T>)))`.
/// 2. Call the [`EmplacerFn<T>`] with the following arguments:
///
/// 1. `Layout`: The layout of the value of type `T` you want to emplace
/// 2. `<T as Pointee>::Metadata`: The pointer metadata of the value of type `T` you want to emplace
/// 3. `&mut (dyn FnMut(*mut PhantomData<T>)))`: The closure you must pass for this thrid argument
/// must do one of two things, depending on the `*mut PhantomData<T>` pointer it recieves.
/// - if the pointer is null, it should drop the value of type `T`.
/// - otherwise, it should write the value of type `T` to the pointer,
/// which it can assume points to the start of an allocation with the size and alignment of
/// the `Layout` from above.
///
/// Once you have an [`EmplacableFn<T>`], use [`Emplacable::from_fn`] to turn it into an [`Emplacable<T, _>`].
///
/// There are **safety preconditions** at every step of this process that **must be respected to avoid UB.**
/// Read the documentation of all the methods involved to learn about them.
#[repr(transparent)]
pub struct Emplacable<T, F>
where
T: ?Sized,
F: EmplacableFn<T>,
{
closure: ManuallyDrop<F>,
phantom: PhantomData<fn(&mut Emplacer<'_, T>)>,
}
impl<T, F> Emplacable<T, F>
where
T: ?Sized,
F: EmplacableFn<T>,
{
/// Create a new `Emplacable` from a closure.
/// This is only useful if you are implementing
/// a function that returns an unsized value as
/// an [`Emplacable`].
///
/// # Safety
///
/// The closure `closurse` *must*, either diverge
/// without returning, or, if it returns, then
/// it must have used the emplacer to fully
/// initalize the value.
#[must_use]
#[inline]
pub unsafe fn from_fn(closure: F) -> Self {
Emplacable {
closure: ManuallyDrop::new(closure),
phantom: PhantomData,
}
}
/// Returns the closure inside this `Emplacable`.
///
/// This is only useful if you are implementing
/// a function like [`box_new_with`].
#[must_use]
#[inline]
pub fn into_fn(self) -> F {
let mut manually_drop_self = ManuallyDrop::new(self);
// SAFETY: `self` is in a `ManuallyDrop`, so no double drop
unsafe { ManuallyDrop::take(&mut manually_drop_self.closure) }
}
/// Emplaces this sized `T` onto the stack.
#[must_use]
#[inline]
pub fn get(self) -> T
where
T: Sized,
{
let mut buf: MaybeUninit<T> = MaybeUninit::uninit();
let emplacer_closure =
&mut |_: Layout, (), inner_closure: &mut dyn FnMut(*mut PhantomData<T>)| {
inner_closure(buf.as_mut_ptr().cast());
};
// SAFETY: emplacer passes in pointer to `MaybeUninit` buffer, which is of the right size/align
let emplacer = unsafe { Emplacer::from_fn(emplacer_closure) };
let closure = self.into_fn();
closure(emplacer);
// SAFETY: `buf` was initialized by the emplacer
unsafe { buf.assume_init() }
}
/// Runs the `Emplacable` closure,
/// but doesn't run the "inner closure",
/// so the value of type `T` is forgotten,
/// and its destructor is not run.
///
/// If you want to drop the `T` and run its destructor,
/// drop the `Emplacable` instead.
#[inline]
pub fn forget(self) {
#[inline]
fn forgetting_emplacer_closure<T: ?Sized>(
_: Layout,
_: <T as Pointee>::Metadata,
_: &mut dyn FnMut(*mut PhantomData<T>),
) {
// Do nothing. Just forget the value ever existed.
}
let emplacable_closure = self.into_fn();
let ref_to_fn = &mut forgetting_emplacer_closure::<T>;
// SAFETY: `forgetting_emplacer` fulfills the requirements
let forgetting_emplacer = unsafe { Emplacer::from_fn(ref_to_fn) };
emplacable_closure(forgetting_emplacer);
}
/// Turns an emplacer for a sized type into one for an unsized type
/// via an unsizing coercion (for example, array -> slice or
/// concrete type -> trait object).
#[must_use]
#[inline]
pub fn unsize<U: ?Sized>(self) -> Emplacable<U, impl EmplacableFn<U>>
where
T: Sized + Unsize<U>,
{
const fn metadata<T: Unsize<U>, U: ?Sized>() -> <U as Pointee>::Metadata {
// Do an unsizing coercion to get the right metadata.
let null_ptr_to_t: *const T = ptr::null();
let null_ptr_to_u: *const U = null_ptr_to_t;
ptr::metadata(null_ptr_to_u)
}
let sized_emplacable_closure = self.into_fn();
let unsized_emplacable_closure = move |unsized_emplacer: &mut Emplacer<'_, U>| {
// SAFETY: We are just wrapping this emplacer
let unsized_emplacer_closure = unsafe { unsized_emplacer.into_fn() };
let mut sized_emplacer_closure =
|_: Layout, _: (), sized_inner_closure: &mut dyn FnMut(*mut PhantomData<T>)| {
let unsized_inner_closure: &mut dyn FnMut(*mut PhantomData<U>) =
&mut |unsized_ptr: *mut PhantomData<U>| {
sized_inner_closure(unsized_ptr.cast());
};
unsized_emplacer_closure(
Layout::new::<T>(),
metadata::<T, U>(),
unsized_inner_closure,
);
};
// SAFETY: just wrapping the emplacer we got, fulfills the preconditions if the inner one does
let sized_emplacer = unsafe { Emplacer::from_fn(&mut sized_emplacer_closure) };
sized_emplacable_closure(sized_emplacer);
};
// SAFETY: Again, just wrapping our input
unsafe { Emplacable::from_fn(unsized_emplacable_closure) }
}
/// Creates an `Emplacable` for a slice of values of type `T` out of an iterator
/// of values of type `T`.
///
/// This function differs from [`FromIterator::from_iter`] in that the iterator is required to
/// be an [`ExactSizeIterator`]. If `ExactSizeIterator` is incorrectly implemented,
/// this function may panic or otherwise misbehave (but will not trigger UB).
#[allow(clippy::should_implement_trait)] // We only take `ExactSizeIterator`s
#[inline]
pub fn from_iter<I>(iter: I) -> Emplacable<[T], impl EmplacableFn<[T]>>
where
T: Sized,
I: IntoIterator<Item = Self>,
I::IntoIter: ExactSizeIterator,
{
fn from_iter_inner<
T,
F: EmplacableFn<T>,
I: Iterator<Item = Emplacable<T, F>> + ExactSizeIterator,
>(
iter: I,
) -> Emplacable<[T], impl EmplacableFn<[T]>> {
let len = iter.len();
// Panics if size overflows `isize::MAX`.
let layout = Layout::from_size_align(
mem::size_of::<T>().checked_mul(len).unwrap(),
mem::align_of::<T>(),
)
.unwrap();
let slice_emplacer_closure = move |slice_emplacer: &mut Emplacer<'_, [T]>| {
// Move ite into closure
let emplacables_iter = ManuallyDrop::new(iter);
// SAFETY: we fulfill the preconditions
let slice_emplacer_fn = unsafe { slice_emplacer.into_fn() };
slice_emplacer_fn(layout, len, &mut |arr_out_ptr: *mut PhantomData<[T]>| {
if !arr_out_ptr.is_null() {
let elem_emplacables: I =
// SAFETY: this "inner closure" can only be called once,
// per preconditions of `Emplacer::new`.
// `elem_emplacables` is inside a `ManuallyDrop`, so avoid double-drop.
unsafe { ptr::read(&*emplacables_iter) };
// We can't trust `ExactSizeIterator`'s `len()`,
// so we keep track of how many
// elements were actually returned.
let mut num_elems_copied: usize = 0;
let indexed_elem_emplacables = (0..len).zip(elem_emplacables);
indexed_elem_emplacables.for_each(|(index, elem_emplacable)| {
let elem_emplacable_closure = elem_emplacable.into_fn();
let elem_emplacer_closure = &mut move |
_: Layout,
(),
inner_closure: &mut dyn FnMut(*mut PhantomData<T>),
| {
// SAFETY: by fn precondition
inner_closure(unsafe { arr_out_ptr.cast::<T>().add(index).cast() });
};
// SAFETY: `elem_emplacer_closure` passes a pointer with the correct offset from the
// start of the allocation
let elem_emplacer = unsafe { Emplacer::from_fn(elem_emplacer_closure) };
elem_emplacable_closure(elem_emplacer);
num_elems_copied += 1;
});
assert_eq!(num_elems_copied, len);
} else {
let emplacables_iter: I =
// SAFETY: this "inner closure" can only be called once,
// per preconditions of `Emplacer::new`.
// `elem_emplacables` is inside a `ManuallyDrop`, so avoid double-drop.
unsafe { ptr::read(&*emplacables_iter) };
for _emplacable in emplacables_iter {
// drop `emplacable`
}
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(slice_emplacer_closure) }
}
let emplacables_iter = iter.into_iter();
from_iter_inner(emplacables_iter)
}
}
impl<T, F> Drop for Emplacable<T, F>
where
T: ?Sized,
F: EmplacableFn<T>,
{
/// Runs the contained closure to completion,
/// instructing it to drop the value of type `T`.
fn drop(&mut self) {
#[inline]
fn dropping_emplacer_closure<T: ?Sized>(
_: Layout,
_: <T as Pointee>::Metadata,
inner_closure: &mut dyn FnMut(*mut PhantomData<T>),
) {
// null ptr signals we wish to drop the value.
inner_closure(ptr::null_mut());
}
let ref_to_fn = &mut dropping_emplacer_closure::<T>;
// SAFETY: `dropping_emplacer_closure` fulfills the requirements
let dropping_emplacer = unsafe { Emplacer::from_fn(ref_to_fn) };
// SAFETY: we are inside `drop`, so no one else will access this
// `ManuallyDrop` after us
let emplacable_closure = unsafe { ManuallyDrop::take(&mut self.closure) };
emplacable_closure(dropping_emplacer);
}
}
/// Implementation detail for the `From` impls.
#[doc(hidden)]
pub trait IntoEmplacable<T: ?Sized> {
type Closure: EmplacableFn<T>;
#[must_use]
fn into_emplacable(self) -> Emplacable<T, Self::Closure>;
}
impl<T> IntoEmplacable<T> for T {
type Closure = impl EmplacableFn<Self>;
#[inline]
fn into_emplacable(self) -> Emplacable<T, Self::Closure> {
let closure = move |emplacer: &mut Emplacer<'_, T>| {
let mut manually_drop_self = ManuallyDrop::new(self);
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(Layout::new::<T>(), (), &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: copying value where it belongs.
// We use `ManuallyDrop` prevent double-free.
// `Emplacer` preconditions say this can only be run once.
unsafe {
ptr::copy_nonoverlapping(
addr_of!(*manually_drop_self).cast::<T>(),
out_ptr.cast(),
1,
);
}
} else {
// SAFETY: we use `ManuallyDrop` to avoid double drop
unsafe { ManuallyDrop::drop(&mut manually_drop_self) }
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(closure) }
}
}
impl<T> From<T> for Emplacable<T, <T as IntoEmplacable<T>>::Closure> {
#[inline]
fn from(value: T) -> Self {
value.into_emplacable()
}
}
// Implementation detail for the `From<&[T]>` impl of `Emplacable<[T], _>`,
// allows us to specialize on `T: Copy`
trait CopyToBuf: Sized {
/// # Safety
///
/// `buf` must be valid to write `slice.len() * mem::size_of<T>()`
/// bytes into, and bust be aligned to `mem::align_of<T>()`.
unsafe fn copy_to_buf(slice: &[Self], buf: *mut Self);
}
impl<T: Clone> CopyToBuf for T {
#[inline]
default unsafe fn copy_to_buf(slice: &[Self], buf: *mut Self) {
for (index, elem) in slice.iter().enumerate() {
let owned = elem.clone();
// SAFETY: copying value where it belongs. safe to write to
// `buf` by preconditions of function
unsafe { buf.cast::<T>().add(index).write(owned) };
}
}
}
impl<T: Copy> CopyToBuf for T {
#[inline]
unsafe fn copy_to_buf(slice: &[Self], buf: *mut Self) {
// SAFETY: copying value where it belongs. safe to write to
// `buf` by preconditions of function
unsafe {
ptr::copy_nonoverlapping(addr_of!(slice).cast(), buf, slice.len());
}
}
}
impl<'s, T: Clone + 's> IntoEmplacable<[T]> for &'s [T] {
type Closure = impl for<'a> FnOnce(&'a mut Emplacer<'_, [T]>) + 's;
#[inline]
fn into_emplacable(self) -> Emplacable<[T], Self::Closure> {
let metadata = ptr::metadata(self);
let layout = Layout::for_value(self);
let closure = move |emplacer: &mut Emplacer<'_, [T]>| {
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(layout, metadata, &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: by precondtion of `Emplacer::new`
unsafe { <T as CopyToBuf>::copy_to_buf(self, out_ptr.cast()) }
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(closure) }
}
}
impl<'s, T: Clone + 's> From<&'s [T]>
for Emplacable<[T], <&'s [T] as IntoEmplacable<[T]>>::Closure>
{
#[inline]
fn from(value: &'s [T]) -> Self {
<&[T] as IntoEmplacable<[T]>>::into_emplacable(value)
}
}
impl<'s> IntoEmplacable<str> for &'s str {
type Closure = impl for<'a> FnOnce(&'a mut Emplacer<'_, str>) + 's;
#[inline]
fn into_emplacable(self) -> Emplacable<str, Self::Closure> {
let metadata = ptr::metadata(self);
let layout = Layout::for_value(self);
let closure = move |emplacer: &mut Emplacer<'_, str>| {
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(layout, metadata, &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: copying value where it belongs.
unsafe {
ptr::copy_nonoverlapping(
addr_of!(*self).cast::<u8>(),
out_ptr.cast(),
layout.size(),
);
}
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(closure) }
}
}
impl<'s> From<&'s str> for Emplacable<str, <&'s str as IntoEmplacable<str>>::Closure> {
#[inline]
fn from(value: &'s str) -> Self {
<&str as IntoEmplacable<str>>::into_emplacable(value)
}
}
impl<'s> IntoEmplacable<CStr> for &'s CStr {
type Closure = impl for<'a> FnOnce(&'a mut Emplacer<'_, CStr>) + 's;
#[inline]
fn into_emplacable(self) -> Emplacable<CStr, Self::Closure> {
let metadata = ptr::metadata(self);
let layout = Layout::for_value(self);
let closure = move |emplacer: &mut Emplacer<'_, CStr>| {
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(layout, metadata, &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: copying value where it belongs.
unsafe {
ptr::copy_nonoverlapping(
addr_of!(*self).cast::<u8>(),
out_ptr.cast(),
layout.size(),
);
}
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(closure) }
}
}
impl<'s> From<&'s CStr> for Emplacable<CStr, <&'s CStr as IntoEmplacable<CStr>>::Closure> {
#[inline]
fn from(value: &'s CStr) -> Self {
<&CStr as IntoEmplacable<CStr>>::into_emplacable(value)
}
}
#[cfg(feature = "std")]
impl<'s> IntoEmplacable<OsStr> for &'s OsStr {
type Closure = impl for<'a> FnOnce(&'a mut Emplacer<'_, OsStr>) + 's;
#[inline]
fn into_emplacable(self) -> Emplacable<OsStr, Self::Closure> {
let metadata = ptr::metadata(self);
let layout = Layout::for_value(self);
let closure = move |emplacer: &mut Emplacer<'_, OsStr>| {
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(layout, metadata, &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: copying value where it belongs.
// We `forget` right after to prevent double-free.
// `Emplacer` preconditions say this can only be run once.
unsafe {
ptr::copy_nonoverlapping(
addr_of!(*self).cast::<u8>(),
out_ptr.cast(),
layout.size(),
);
}
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(closure) }
}
}
#[cfg(feature = "std")]
impl<'s> From<&'s OsStr> for Emplacable<OsStr, <&'s OsStr as IntoEmplacable<OsStr>>::Closure> {
#[inline]
fn from(value: &'s OsStr) -> Self {
<&OsStr as IntoEmplacable<OsStr>>::into_emplacable(value)
}
}
#[cfg(feature = "std")]
impl<'s> IntoEmplacable<Path> for &'s Path {
type Closure = impl for<'a> FnOnce(&'a mut Emplacer<'_, Path>) + 's;
#[inline]
fn into_emplacable(self) -> Emplacable<Path, Self::Closure> {
let metadata = ptr::metadata(self);
let layout = Layout::for_value(self);
let closure = move |emplacer: &mut Emplacer<'_, Path>| {
// Safety: we call the closure right after
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(layout, metadata, &mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: copying value where it belongs.
// We `forget` right after to prevent double-free.
// `Emplacer` preconditions say this can only be run once.
unsafe {
ptr::copy_nonoverlapping(
addr_of!(*self).cast::<u8>(),
out_ptr.cast(),
layout.size(),
);
}
}
});
};
// SAFETY: `closure` properly emplaces `val`
unsafe { Emplacable::from_fn(closure) }
}
}
#[cfg(feature = "std")]
impl<'s> From<&'s Path> for Emplacable<Path, <&'s Path as IntoEmplacable<Path>>::Closure> {
#[inline]
fn from(value: &'s Path) -> Self {
<&Path as IntoEmplacable<Path>>::into_emplacable(value)
}
}
/// Implementation detail of `From<Emplacable<str, _>> for Emplacable<u8, _>`.
#[doc(hidden)]
pub trait FromEmplacable<T: ?Sized> {
type OutputClosure<F: EmplacableFn<T>>: EmplacableFn<Self>;
fn from_emplacable<F: EmplacableFn<T>>(
emplacable: Emplacable<T, F>,
) -> Emplacable<Self, Self::OutputClosure<F>>;
}
impl<F: EmplacableFn<str>> IntoEmplacable<[u8]> for Emplacable<str, F> {
type Closure = impl EmplacableFn<[u8]>;
#[inline]
fn into_emplacable(self) -> Emplacable<[u8], Self::Closure> {
let str_closure = self.into_fn();
#[allow(clippy::unused_unit)] // https://github.com/rust-lang/rust-clippy/issues/9748
let u8_emplacer_closure = for<'a, 'b> move |u8_emplacer: &'a mut Emplacer<'b, [u8]>| -> () {
let u8_emplacer_fn: &mut EmplacerFn<'_, [u8]> =
// SAFETY: just wrapping this in another emplacer
unsafe { u8_emplacer.into_fn() };
let mut str_emplacer_fn =
|layout: Layout,
metadata: usize,
str_inner_closure: &mut dyn FnMut(*mut PhantomData<str>)| {
let u8_inner_closure: &mut dyn FnMut(*mut PhantomData<[u8]>) =