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
use std::{
borrow::{Borrow, Cow},
fmt::Debug,
iter::FromIterator,
};
use serde::{Deserialize, Serialize};
use crate::{RawArray, RawBsonRef, RawDocumentBuf};
use super::{bson::RawBson, serde::OwnedOrBorrowedRawArray, RawArrayIter};
/// An owned BSON array value (akin to [`std::path::PathBuf`]), backed by a buffer of raw BSON
/// bytes. This type can be used to construct owned array values, which can be used to append to
/// [`RawDocumentBuf`] or as a field in a [`Deserialize`] struct.
///
/// Iterating over a [`RawArrayBuf`] yields either an error or a [`RawBson`] value that borrows from
/// the original document without making any additional allocations.
/// ```
/// # use bson::raw::Error;
/// use bson::raw::RawArrayBuf;
///
/// let mut array = RawArrayBuf::new();
/// array.push("a string");
/// array.push(12_i32);
///
/// let mut iter = array.into_iter();
///
/// let value = iter.next().unwrap()?;
/// assert_eq!(value.as_str(), Some("a string"));
///
/// let value = iter.next().unwrap()?;
/// assert_eq!(value.as_i32(), Some(12));
///
/// assert!(iter.next().is_none());
/// # Ok::<(), Error>(())
/// ```
///
/// This type implements [`Deref`](std::ops::Deref) to [`RawArray`], meaning that all methods on
/// [`RawArray`] are available on [`RawArrayBuf`] values as well. This includes [`RawArray::get`] or
/// any of the type-specific getters, such as [`RawArray::get_object_id`] or [`RawArray::get_str`].
/// Note that accessing elements is an O(N) operation, as it requires iterating through the document
/// from the beginning to find the requested key.
#[derive(Clone, PartialEq)]
pub struct RawArrayBuf {
inner: RawDocumentBuf,
len: usize,
}
impl RawArrayBuf {
/// Construct a new, empty [`RawArrayBuf`].
pub fn new() -> RawArrayBuf {
Self {
inner: RawDocumentBuf::new(),
len: 0,
}
}
/// Construct a new [`RawArrayBuf`] from the provided [`Vec`] of bytes.
///
/// This involves a traversal of the array to count the values.
pub(crate) fn from_raw_document_buf(doc: RawDocumentBuf) -> Self {
let len = doc.iter().count();
Self { inner: doc, len }
}
/// Append a value to the end of the array.
///
/// ```
/// # use bson::raw::Error;
/// use bson::raw::{RawArrayBuf, RawDocumentBuf};
///
/// let mut array = RawArrayBuf::new();
/// array.push("a string");
/// array.push(12_i32);
///
/// let mut doc = RawDocumentBuf::new();
/// doc.append("a key", "a value");
/// array.push(doc.clone());
///
/// let mut iter = array.into_iter();
///
/// let value = iter.next().unwrap()?;
/// assert_eq!(value.as_str(), Some("a string"));
///
/// let value = iter.next().unwrap()?;
/// assert_eq!(value.as_i32(), Some(12));
///
/// let value = iter.next().unwrap()?;
/// assert_eq!(value.as_document(), Some(doc.as_ref()));
///
/// assert!(iter.next().is_none());
/// # Ok::<(), Error>(())
/// ```
pub fn push(&mut self, value: impl Into<RawBson>) {
self.inner.append(self.len.to_string(), value);
self.len += 1;
}
pub(crate) fn into_vec(self) -> Vec<u8> {
self.inner.into_bytes()
}
}
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<'a> From<RawArrayBuf> for Cow<'a, 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())
}
}
impl<T: Into<RawBson>> FromIterator<T> for RawArrayBuf {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut array_buf = RawArrayBuf::new();
for item in iter {
array_buf.push(item);
}
array_buf
}
}
impl<'de> Deserialize<'de> for RawArrayBuf {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(OwnedOrBorrowedRawArray::deserialize(deserializer)?.into_owned())
}
}
impl 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()
}
}