Repository navigation
Expand file tree
/
Copy pathalloc.rs
More file actions
76 lines (66 loc) · 2.33 KB
/
Copy pathalloc.rs
File metadata and controls
76 lines (66 loc) · 2.33 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
//! Allocation APIs replaced by `alloc_light.rs` when none of the `nightly` or
//! `allocator-api2` feature is enabled.
#![no_implicit_prelude]
extern crate core;
#[cfg(feature = "nightly")]
extern crate alloc as src;
#[cfg(not(feature = "nightly"))]
extern crate allocator_api2 as src;
use core::result::{Result, Result::Ok};
pub use src::alloc::{AllocError, Allocator, Global};
pub use src::vec;
// Workaround to allow exporting a type and a macro with the same name.
mod reexport {
pub use super::src::{boxed::Box, collections::TryReserveError, vec::Vec};
}
pub(crate) use reexport::*;
// These cannot be type aliases as Rust would complain about unused generic
// arguments in `alloc_light.rs`.
macro_rules! Box {
( $T:ty, $A:ty $(,)? ) => { $crate::alloc::Box<$T, $A> };
}
macro_rules! Vec {
( $T:ty, $A:ty $(,)? ) => { $crate::alloc::Vec<$T, $A> };
}
macro_rules! Event {
( $parser:lifetime, $input:lifetime, $A:ty $(,)? ) => { Event<$parser, $input, $A> };
}
macro_rules! InvalidToken {
( $($lt:lifetime,)+ $A:ident $(,)? ) => { InvalidToken<$($lt,)+ $A> };
}
macro_rules! Str {
( $($lt:lifetime,)+ $A:ident $(,)? ) => { Str<$($lt,)+ $A> };
}
macro_rules! Token {
( $($lt:lifetime,)+ $A:ident $(,)? ) => { Token<$($lt,)+ $A> };
}
macro_rules! Value {
( $input:lifetime, $A:ty $(,)? ) => { Value<$input, $A> };
}
pub(crate) use Box;
pub(crate) use Event;
pub(crate) use InvalidToken;
pub(crate) use Str;
pub(crate) use Token;
pub(crate) use Value;
pub(crate) use Vec;
pub fn try_new_boxed_str_in<A: Allocator>(
value: &str,
allocator: A,
) -> Result<Box<str, A>, AllocError> {
let mut vec = Vec::new_in(allocator);
vec.try_reserve_exact(value.len())
.map_err(|_: TryReserveError| AllocError)?;
vec.extend_from_slice(value.as_bytes());
core::debug_assert_eq!(vec.capacity(), value.len());
let (ptr, allocator) = Box::into_raw_with_allocator(vec.into_boxed_slice());
let ptr = ptr as *mut str;
// SAFETY: `ptr` is a valid pointer managed by `allocator` (obtained with
// `Box::into_raw_with_allocator`), which was cast from `*mut u8` to `*mut
// str`, which was valid because its contents equals that of `value`,
// which is a valid string.
Ok(unsafe { Box::from_raw_in(ptr, allocator) })
}
pub fn new_vec_in<T, A: Allocator>(allocator: A) -> Vec<T, A> {
Vec::new_in(allocator)
}