use core::alloc::{AllocError, Allocator, Layout};
use crate::{
node::{AllocateError, Header, Node},
DynList, Ends, MaybeUninitNode,
};
impl<A> DynList<str, A>
where
A: Allocator,
{
pub unsafe fn from_utf8_unchecked(bytes: DynList<[u8], A>) -> Self {
let (ends, allocator) = bytes.into_raw_parts();
unsafe { Self::from_raw_parts(ends, allocator) }
}
pub fn into_bytes(self) -> DynList<[u8], A> {
let (ends, allocator) = self.into_raw_parts();
unsafe { DynList::from_raw_parts(ends, allocator) }
}
#[inline]
fn try_allocate_uninit_str_front_internal(
&mut self,
length: usize,
) -> Result<MaybeUninitNode<str, A>, AllocateError> {
let value_layout = Layout::array::<u8>(length)?;
let header = Header {
next: self
.ends
.map(|Ends { front, .. }| unsafe { front.to_transparent() }),
previous: None,
metadata: length,
};
unsafe { Node::try_new_uninit(self, value_layout, header) }
}
#[inline]
fn try_allocate_uninit_str_back_internal(
&mut self,
length: usize,
) -> Result<MaybeUninitNode<str, A>, AllocateError> {
let value_layout = Layout::array::<u8>(length)?;
let header = Header {
next: None,
previous: self
.ends
.map(|Ends { back, .. }| unsafe { back.to_transparent() }),
metadata: length,
};
unsafe { Node::try_new_uninit(self, value_layout, header) }
}
pub fn try_allocate_uninit_str_front(
&mut self,
length: usize,
) -> Result<MaybeUninitNode<str, A>, AllocError> {
self.try_allocate_uninit_str_front_internal(length)
.map_err(Into::into)
}
pub fn try_allocate_uninit_str_back(
&mut self,
length: usize,
) -> Result<MaybeUninitNode<str, A>, AllocError> {
self.try_allocate_uninit_str_back_internal(length)
.map_err(Into::into)
}
#[must_use]
pub fn allocate_uninit_str_front(&mut self, length: usize) -> MaybeUninitNode<str, A> {
AllocateError::unwrap_alloc(self.try_allocate_uninit_str_front_internal(length))
}
#[must_use]
pub fn allocate_uninit_str_back(&mut self, length: usize) -> MaybeUninitNode<str, A> {
AllocateError::unwrap_alloc(self.try_allocate_uninit_str_back_internal(length))
}
pub fn try_push_front_copy_str(&mut self, src: &str) -> Result<(), AllocError> {
let mut node = self.try_allocate_uninit_str_front(src.len())?;
node.copy_from_str(src);
unsafe { node.insert() };
Ok(())
}
pub fn try_push_back_copy_str(&mut self, src: &str) -> Result<(), AllocError> {
let mut node = self.try_allocate_uninit_str_back(src.len())?;
node.copy_from_str(src);
unsafe { node.insert() };
Ok(())
}
pub fn push_front_copy_str(&mut self, src: &str) {
let mut node = self.allocate_uninit_str_front(src.len());
node.copy_from_str(src);
unsafe { node.insert() };
}
pub fn push_back_copy_str(&mut self, src: &str) {
let mut node = self.allocate_uninit_str_back(src.len());
node.copy_from_str(src);
unsafe { node.insert() };
}
}