| 1 |
use std::{borrow::Cow, convert::TryFrom}; |
| 2 |
|
| 3 |
use serde::{ser::SerializeSeq, Deserialize, Serialize}; |
| 4 |
|
| 5 |
use super::{ |
| 6 |
error::{ValueAccessError, ValueAccessErrorKind, ValueAccessResult}, |
| 7 |
serde::OwnedOrBorrowedRawArray, |
| 8 |
Error, |
| 9 |
RawBinaryRef, |
| 10 |
RawBsonRef, |
| 11 |
RawDocument, |
| 12 |
RawIter, |
| 13 |
RawRegexRef, |
| 14 |
Result, |
| 15 |
}; |
| 16 |
use crate::{ |
| 17 |
oid::ObjectId, |
| 18 |
raw::RAW_ARRAY_NEWTYPE, |
| 19 |
spec::ElementType, |
| 20 |
Bson, |
| 21 |
DateTime, |
| 22 |
RawArrayBuf, |
| 23 |
Timestamp, |
| 24 |
}; |
| 25 |
|
| 26 |
/// A slice of a BSON document containing a BSON array value (akin to [`std::str`]). This can be |
| 27 |
/// retrieved from a [`RawDocument`] via [`RawDocument::get`]. |
| 28 |
/// |
| 29 |
/// This is an _unsized_ type, meaning that it must always be used behind a pointer like `&`. |
| 30 |
/// |
| 31 |
/// Accessing elements within a [`RawArray`] is similar to element access in [`crate::Document`], |
| 32 |
/// but because the contents are parsed during iteration instead of at creation time, format errors |
| 33 |
/// can happen at any time during use. |
| 34 |
/// |
| 35 |
/// Iterating over a [`RawArray`] yields either an error or a value that borrows from the |
| 36 |
/// original document without making any additional allocations. |
| 37 |
/// |
| 38 |
/// ``` |
| 39 |
/// use bson::{doc, raw::RawDocument}; |
| 40 |
/// |
| 41 |
/// let doc = doc! { |
| 42 |
/// "x": [1, true, "two", 5.5] |
| 43 |
/// }; |
| 44 |
/// let bytes = bson::to_vec(&doc)?; |
| 45 |
/// |
| 46 |
/// let rawdoc = RawDocument::from_bytes(bytes.as_slice())?; |
| 47 |
/// let rawarray = rawdoc.get_array("x")?; |
| 48 |
/// |
| 49 |
/// for v in rawarray { |
| 50 |
/// println!("{:?}", v?); |
| 51 |
/// } |
| 52 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 53 |
/// ``` |
| 54 |
/// |
| 55 |
/// Individual elements can be accessed using [`RawArray::get`] or any of |
| 56 |
/// the type-specific getters, such as [`RawArray::get_object_id`] or |
| 57 |
/// [`RawArray::get_str`]. Note that accessing elements is an O(N) operation, as it |
| 58 |
/// requires iterating through the array from the beginning to find the requested index. |
| 59 |
/// |
| 60 |
/// ``` |
| 61 |
/// # use bson::raw::{ValueAccessError}; |
| 62 |
/// use bson::{doc, raw::RawDocument}; |
| 63 |
/// |
| 64 |
/// let doc = doc! { |
| 65 |
/// "x": [1, true, "two", 5.5] |
| 66 |
/// }; |
| 67 |
/// let bytes = bson::to_vec(&doc)?; |
| 68 |
/// |
| 69 |
/// let rawdoc = RawDocument::from_bytes(bytes.as_slice())?; |
| 70 |
/// let rawarray = rawdoc.get_array("x")?; |
| 71 |
/// |
| 72 |
/// assert_eq!(rawarray.get_bool(1)?, true); |
| 73 |
/// # Ok::<(), Box<dyn std::error::Error>>(()) |
| 74 |
/// ``` |
| 75 |
#[derive(PartialEq)] |
| 76 |
#[repr(transparent)] |
| 77 |
pub struct RawArray { |
| 78 |
pub(crate) doc: RawDocument, |
| 79 |
} |
| 80 |
|
| 81 |
impl RawArray { |
| 82 |
pub(crate) fn from_doc(doc: &RawDocument) -> &RawArray { |
| 83 |
// SAFETY: |
| 84 |
// |
| 85 |
// Dereferencing a raw pointer requires unsafe due to the potential that the pointer is |
| 86 |
// null, dangling, or misaligned. We know the pointer is not null or dangling due to the |
| 87 |
// fact that it's created by a safe reference. Converting &RawDocument to *const |
| 88 |
// RawDocument will be properly aligned due to them being references to the same type, |
| 89 |
// and converting *const RawDocument to *const RawArray is aligned due to the fact that |
| 90 |
// the only field in a RawArray is a RawDocument, meaning the structs are represented |
| 91 |
// identically at the byte level. |
| 92 |
unsafe { &*(doc as *const RawDocument as *const RawArray) } |
| 93 |
} |
| 94 |
|
| 95 |
/// Convert this borrowed [`RawArray`] into an owned [`RawArrayBuf`]. |
| 96 |
/// |
| 97 |
/// This involves a traversal of the array to count the values. |
| 98 |
pub fn to_raw_array_buf(&self) -> RawArrayBuf { |
| 99 |
RawArrayBuf::from_raw_document_buf(self.doc.to_raw_document_buf()) |
| 100 |
} |
| 101 |
|
| 102 |
/// Gets a reference to the value at the given index. |
| 103 |
pub fn get(&self, index: usize) -> Result<Option<RawBsonRef<'_>>> { |
| 104 |
self.into_iter().nth(index).transpose() |
| 105 |
} |
| 106 |
|
| 107 |
fn get_with<'a, T>( |
| 108 |
&'a self, |
| 109 |
index: usize, |
| 110 |
expected_type: ElementType, |
| 111 |
f: impl FnOnce(RawBsonRef<'a>) -> Option<T>, |
| 112 |
) -> ValueAccessResult<T> { |
| 113 |
let bson = self |
| 114 |
.get(index) |
| 115 |
.map_err(|e| ValueAccessError { |
| 116 |
key: index.to_string(), |
| 117 |
kind: ValueAccessErrorKind::InvalidBson(e), |
| 118 |
})? |
| 119 |
.ok_or(ValueAccessError { |
| 120 |
key: index.to_string(), |
| 121 |
kind: ValueAccessErrorKind::NotPresent, |
| 122 |
})?; |
| 123 |
match f(bson) { |
| 124 |
Some(t) => Ok(t), |
| 125 |
None => Err(ValueAccessError { |
| 126 |
key: index.to_string(), |
| 127 |
kind: ValueAccessErrorKind::UnexpectedType { |
| 128 |
expected: expected_type, |
| 129 |
actual: bson.element_type(), |
| 130 |
}, |
| 131 |
}), |
| 132 |
} |
| 133 |
} |
| 134 |
|
| 135 |
/// Gets the BSON double at the given index or returns an error if the value at that index isn't |
| 136 |
/// a double. |
| 137 |
pub fn get_f64(&self, index: usize) -> ValueAccessResult<f64> { |
| 138 |
self.get_with(index, ElementType::Double, RawBsonRef::as_f64) |
| 139 |
} |
| 140 |
|
| 141 |
/// Gets a reference to the string at the given index or returns an error if the |
| 142 |
/// value at that index isn't a string. |
| 143 |
pub fn get_str(&self, index: usize) -> ValueAccessResult<&str> { |
| 144 |
self.get_with(index, ElementType::String, RawBsonRef::as_str) |
| 145 |
} |
| 146 |
|
| 147 |
/// Gets a reference to the document at the given index or returns an error if the |
| 148 |
/// value at that index isn't a document. |
| 149 |
pub fn get_document(&self, index: usize) -> ValueAccessResult<&RawDocument> { |
| 150 |
self.get_with( |
| 151 |
index, |
| 152 |
ElementType::EmbeddedDocument, |
| 153 |
RawBsonRef::as_document, |
| 154 |
) |
| 155 |
} |
| 156 |
|
| 157 |
/// Gets a reference to the array at the given index or returns an error if the |
| 158 |
/// value at that index isn't a array. |
| 159 |
pub fn get_array(&self, index: usize) -> ValueAccessResult<&RawArray> { |
| 160 |
self.get_with(index, ElementType::Array, RawBsonRef::as_array) |
| 161 |
} |
| 162 |
|
| 163 |
/// Gets a reference to the BSON binary value at the given index or returns an error if the |
| 164 |
/// value at that index isn't a binary. |
| 165 |
pub fn get_binary(&self, index: usize) -> ValueAccessResult<RawBinaryRef<'_>> { |
| 166 |
self.get_with(index, ElementType::Binary, RawBsonRef::as_binary) |
| 167 |
} |
| 168 |
|
| 169 |
/// Gets the ObjectId at the given index or returns an error if the value at that index isn't an |
| 170 |
/// ObjectId. |
| 171 |
pub fn get_object_id(&self, index: usize) -> ValueAccessResult<ObjectId> { |
| 172 |
self.get_with(index, ElementType::ObjectId, RawBsonRef::as_object_id) |
| 173 |
} |
| 174 |
|
| 175 |
/// Gets the boolean at the given index or returns an error if the value at that index isn't a |
| 176 |
/// boolean. |
| 177 |
pub fn get_bool(&self, index: usize) -> ValueAccessResult<bool> { |
| 178 |
self.get_with(index, ElementType::Boolean, RawBsonRef::as_bool) |
| 179 |
} |
| 180 |
|
| 181 |
/// Gets the DateTime at the given index or returns an error if the value at that index isn't a |
| 182 |
/// DateTime. |
| 183 |
pub fn get_datetime(&self, index: usize) -> ValueAccessResult<DateTime> { |
| 184 |
self.get_with(index, ElementType::DateTime, RawBsonRef::as_datetime) |
| 185 |
} |
| 186 |
|
| 187 |
/// Gets a reference to the BSON regex at the given index or returns an error if the |
| 188 |
/// value at that index isn't a regex. |
| 189 |
pub fn get_regex(&self, index: usize) -> ValueAccessResult<RawRegexRef<'_>> { |
| 190 |
self.get_with(index, ElementType::RegularExpression, RawBsonRef::as_regex) |
| 191 |
} |
| 192 |
|
| 193 |
/// Gets a reference to the BSON timestamp at the given index or returns an error if the |
| 194 |
/// value at that index isn't a timestamp. |
| 195 |
pub fn get_timestamp(&self, index: usize) -> ValueAccessResult<Timestamp> { |
| 196 |
self.get_with(index, ElementType::Timestamp, RawBsonRef::as_timestamp) |
| 197 |
} |
| 198 |
|
| 199 |
/// Gets the BSON int32 at the given index or returns an error if the value at that index isn't |
| 200 |
/// a 32-bit integer. |
| 201 |
pub fn get_i32(&self, index: usize) -> ValueAccessResult<i32> { |
| 202 |
self.get_with(index, ElementType::Int32, RawBsonRef::as_i32) |
| 203 |
} |
| 204 |
|
| 205 |
/// Gets BSON int64 at the given index or returns an error if the value at that index isn't a |
| 206 |
/// 64-bit integer. |
| 207 |
pub fn get_i64(&self, index: usize) -> ValueAccessResult<i64> { |
| 208 |
self.get_with(index, ElementType::Int64, RawBsonRef::as_i64) |
| 209 |
} |
| 210 |
|
| 211 |
/// Gets a reference to the raw bytes of the [`RawArray`]. |
| 212 |
pub fn as_bytes(&self) -> &[u8] { |
| 213 |
self.doc.as_bytes() |
| 214 |
} |
| 215 |
|
| 216 |
/// Whether this array contains any elements or not. |
| 217 |
pub fn is_empty(&self) -> bool { |
| 218 |
self.doc.is_empty() |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
impl std::fmt::Debug for RawArray { |
| 223 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 224 |
f.debug_struct("RawArray") |
| 225 |
.field("data", &hex::encode(self.doc.as_bytes())) |
| 226 |
.finish() |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
impl TryFrom<&RawArray> for Vec<Bson> { |
| 231 |
type Error = Error; |
| 232 |
|
| 233 |
fn try_from(arr: &RawArray) -> Result<Vec<Bson>> { |
| 234 |
arr.into_iter() |
| 235 |
.map(|result| { |
| 236 |
let rawbson = result?; |
| 237 |
Bson::try_from(rawbson) |
| 238 |
}) |
| 239 |
.collect() |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
impl ToOwned for RawArray { |
| 244 |
type Owned = RawArrayBuf; |
| 245 |
|
| 246 |
fn to_owned(&self) -> Self::Owned { |
| 247 |
self.to_raw_array_buf() |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
impl<'a> From<&'a RawArray> for Cow<'a, RawArray> { |
| 252 |
fn from(rdr: &'a RawArray) -> Self { |
| 253 |
Cow::Borrowed(rdr) |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
impl<'a> IntoIterator for &'a RawArray { |
| 258 |
type IntoIter = RawArrayIter<'a>; |
| 259 |
type Item = Result<RawBsonRef<'a>>; |
| 260 |
|
| 261 |
fn into_iter(self) -> RawArrayIter<'a> { |
| 262 |
RawArrayIter { |
| 263 |
inner: RawIter::new(&self.doc), |
| 264 |
} |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
/// An iterator over borrowed raw BSON array values. |
| 269 |
pub struct RawArrayIter<'a> { |
| 270 |
inner: RawIter<'a>, |
| 271 |
} |
| 272 |
|
| 273 |
impl<'a> Iterator for RawArrayIter<'a> { |
| 274 |
type Item = Result<RawBsonRef<'a>>; |
| 275 |
|
| 276 |
fn next(&mut self) -> Option<Result<RawBsonRef<'a>>> { |
| 277 |
match self.inner.next() { |
| 278 |
Some(Ok(elem)) => match elem.value() { |
| 279 |
Ok(value) => Some(Ok(value)), |
| 280 |
Err(e) => Some(Err(e)), |
| 281 |
}, |
| 282 |
Some(Err(e)) => Some(Err(e)), |
| 283 |
None => None, |
| 284 |
} |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
impl<'de: 'a, 'a> Deserialize<'de> for &'a RawArray { |
| 289 |
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> |
| 290 |
where |
| 291 |
D: serde::Deserializer<'de>, |
| 292 |
{ |
| 293 |
match OwnedOrBorrowedRawArray::deserialize(deserializer)? { |
| 294 |
OwnedOrBorrowedRawArray::Borrowed(b) => Ok(b), |
| 295 |
o => Err(serde::de::Error::custom(format!( |
| 296 |
"expected borrowed raw array, instead got owned {:?}", |
| 297 |
o |
| 298 |
))), |
| 299 |
} |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
impl<'a> Serialize for &'a RawArray { |
| 304 |
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 305 |
where |
| 306 |
S: serde::Serializer, |
| 307 |
{ |
| 308 |
struct SeqSerializer<'a>(&'a RawArray); |
| 309 |
|
| 310 |
impl<'a> Serialize for SeqSerializer<'a> { |
| 311 |
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 312 |
where |
| 313 |
S: serde::Serializer, |
| 314 |
{ |
| 315 |
if serializer.is_human_readable() { |
| 316 |
let mut seq = serializer.serialize_seq(None)?; |
| 317 |
for v in self.0 { |
| 318 |
let v = v.map_err(serde::ser::Error::custom)?; |
| 319 |
seq.serialize_element(&v)?; |
| 320 |
} |
| 321 |
seq.end() |
| 322 |
} else { |
| 323 |
serializer.serialize_bytes(self.0.as_bytes()) |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
serializer.serialize_newtype_struct(RAW_ARRAY_NEWTYPE, &SeqSerializer(self)) |
| 329 |
} |
| 330 |
} |