use std::{
borrow::{Borrow, Cow},
fmt::Debug,
};
use crate::{RawArray, RawBsonRef, RawDocumentBuf};
use super::{document_buf::BindRawBsonRef, RawArrayIter};
#[derive(Clone, PartialEq)]
pub struct RawArrayBuf {
inner: RawDocumentBuf,
len: usize,
}
impl RawArrayBuf {
pub fn new() -> RawArrayBuf {
Self {
inner: RawDocumentBuf::new(),
len: 0,
}
}
pub(crate) fn from_raw_document_buf(doc: RawDocumentBuf) -> Self {
let len = doc.iter().count();
Self { inner: doc, len }
}
pub fn push(&mut self, value: impl BindRawBsonRef) {
self.inner.append(
super::CString::from_string_unchecked(self.len.to_string()),
value,
);
self.len += 1;
}
}
impl<B: BindRawBsonRef> FromIterator<B> for RawArrayBuf {
fn from_iter<T: IntoIterator<Item = B>>(iter: T) -> Self {
let mut array_buf = RawArrayBuf::new();
for item in iter {
array_buf.push(item);
}
array_buf
}
}
impl Debug for RawArrayBuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RawArrayBuf")
.field("data", &hex::encode(self.as_bytes()))
.field("len", &self.len)
.finish()
}
}
impl std::ops::Deref for RawArrayBuf {
type Target = RawArray;
fn deref(&self) -> &Self::Target {
RawArray::from_doc(&self.inner)
}
}
impl AsRef<RawArray> for RawArrayBuf {
fn as_ref(&self) -> &RawArray {
RawArray::from_doc(&self.inner)
}
}
impl Borrow<RawArray> for RawArrayBuf {
fn borrow(&self) -> &RawArray {
self.as_ref()
}
}
impl<'a> IntoIterator for &'a RawArrayBuf {
type IntoIter = RawArrayIter<'a>;
type Item = super::Result<RawBsonRef<'a>>;
fn into_iter(self) -> RawArrayIter<'a> {
self.as_ref().into_iter()
}
}
impl From<RawArrayBuf> for Cow<'_, RawArray> {
fn from(rd: RawArrayBuf) -> Self {
Cow::Owned(rd)
}
}
impl<'a> From<&'a RawArrayBuf> for Cow<'a, RawArray> {
fn from(rd: &'a RawArrayBuf) -> Self {
Cow::Borrowed(rd.as_ref())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for RawArrayBuf {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(super::serde::OwnedOrBorrowedRawArray::deserialize(deserializer)?.into_owned())
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for RawArrayBuf {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.as_ref().serialize(serializer)
}
}
impl Default for RawArrayBuf {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<&crate::Array> for RawArrayBuf {
type Error = crate::error::Error;
fn try_from(value: &crate::Array) -> Result<Self, Self::Error> {
Self::try_from(value.clone())
}
}
impl TryFrom<crate::Array> for RawArrayBuf {
type Error = crate::error::Error;
fn try_from(value: crate::Array) -> Result<Self, Self::Error> {
let mut tmp = RawArrayBuf::new();
for val in value {
let raw: super::RawBson = val.try_into()?;
tmp.push(raw);
}
Ok(tmp)
}
}