use alloc::vec::{self, Vec};
use core::{
fmt,
ops::{Deref, DerefMut},
slice,
};
use crate::{Value, tree};
#[derive(Default)]
pub struct Array<'a> {
items: Vec<Value<'a>>,
}
impl<'a> Array<'a> {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { items: Vec::new() }
}
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
items: Vec::with_capacity(capacity),
}
}
#[inline]
#[must_use]
pub fn into_vec(mut self) -> Vec<Value<'a>> {
core::mem::take(&mut self.items)
}
#[must_use]
pub fn into_owned(self) -> Array<'static> {
match tree::into_owned(Value::Array(self)) {
Value::Array(a) => a,
_ => Array::new(),
}
}
#[inline]
pub(crate) fn items_mut(&mut self) -> &mut Vec<Value<'a>> {
&mut self.items
}
}
impl<'a> Deref for Array<'a> {
type Target = Vec<Value<'a>>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.items
}
}
impl DerefMut for Array<'_> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.items
}
}
impl Drop for Array<'_> {
fn drop(&mut self) {
tree::drop_items(&mut self.items);
}
}
impl Clone for Array<'_> {
fn clone(&self) -> Self {
Self {
items: tree::clone_items(&self.items),
}
}
}
impl PartialEq for Array<'_> {
fn eq(&self, other: &Self) -> bool {
self.items.len() == other.items.len()
&& self
.items
.iter()
.zip(&other.items)
.all(|(a, b)| tree::eq(a, b))
}
}
impl Eq for Array<'_> {}
impl fmt::Debug for Array<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.items.iter()).finish()
}
}
impl<'a> From<Vec<Value<'a>>> for Array<'a> {
#[inline]
fn from(items: Vec<Value<'a>>) -> Self {
Self { items }
}
}
impl<'a, T: Into<Value<'a>>> FromIterator<T> for Array<'a> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self {
items: iter.into_iter().map(Into::into).collect(),
}
}
}
impl<'a, T: Into<Value<'a>>> Extend<T> for Array<'a> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.items.extend(iter.into_iter().map(Into::into));
}
}
impl<'a> IntoIterator for Array<'a> {
type Item = Value<'a>;
type IntoIter = vec::IntoIter<Value<'a>>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.into_vec().into_iter()
}
}
impl<'r, 'a> IntoIterator for &'r Array<'a> {
type Item = &'r Value<'a>;
type IntoIter = slice::Iter<'r, Value<'a>>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.items.iter()
}
}
impl<'r, 'a> IntoIterator for &'r mut Array<'a> {
type Item = &'r mut Value<'a>;
type IntoIter = slice::IterMut<'r, Value<'a>>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.items.iter_mut()
}
}