1use std::{borrow::Cow, convert::TryFrom};
2
3use serde::{ser::SerializeSeq, Deserialize, Serialize};
4
5use super::{
6 error::{ValueAccessError, ValueAccessErrorKind, ValueAccessResult},
7 serde::OwnedOrBorrowedRawArray,
8 Error,
9 RawBinaryRef,
10 RawBsonRef,
11 RawDocument,
12 RawIter,
13 RawRegexRef,
14 Result,
15};
16use crate::{
17 oid::ObjectId,
18 raw::RAW_ARRAY_NEWTYPE,
19 spec::ElementType,
20 Bson,
21 DateTime,
22 RawArrayBuf,
23 Timestamp,
24};
25
26#[derive(PartialEq)]
76#[repr(transparent)]
77pub struct RawArray {
78 pub(crate) doc: RawDocument,
79}
80
81impl RawArray {
82 pub(crate) fn from_doc(doc: &RawDocument) -> &RawArray {
83 unsafe { &*(doc as *const RawDocument as *const RawArray) }
93 }
94
95 pub(crate) fn as_doc(&self) -> &RawDocument {
96 &self.doc
97 }
98
99 pub fn to_raw_array_buf(&self) -> RawArrayBuf {
103 RawArrayBuf::from_raw_document_buf(self.doc.to_raw_document_buf())
104 }
105
106 pub fn get(&self, index: usize) -> Result<Option<RawBsonRef<'_>>> {
108 self.into_iter().nth(index).transpose()
109 }
110
111 fn get_with<'a, T>(
112 &'a self,
113 index: usize,
114 expected_type: ElementType,
115 f: impl FnOnce(RawBsonRef<'a>) -> Option<T>,
116 ) -> ValueAccessResult<T> {
117 let bson = self
118 .get(index)
119 .map_err(|e| ValueAccessError {
120 key: index.to_string(),
121 kind: ValueAccessErrorKind::InvalidBson(e),
122 })?
123 .ok_or(ValueAccessError {
124 key: index.to_string(),
125 kind: ValueAccessErrorKind::NotPresent,
126 })?;
127 match f(bson) {
128 Some(t) => Ok(t),
129 None => Err(ValueAccessError {
130 key: index.to_string(),
131 kind: ValueAccessErrorKind::UnexpectedType {
132 expected: expected_type,
133 actual: bson.element_type(),
134 },
135 }),
136 }
137 }
138
139 pub fn get_f64(&self, index: usize) -> ValueAccessResult<f64> {
142 self.get_with(index, ElementType::Double, RawBsonRef::as_f64)
143 }
144
145 pub fn get_str(&self, index: usize) -> ValueAccessResult<&str> {
148 self.get_with(index, ElementType::String, RawBsonRef::as_str)
149 }
150
151 pub fn get_document(&self, index: usize) -> ValueAccessResult<&RawDocument> {
154 self.get_with(
155 index,
156 ElementType::EmbeddedDocument,
157 RawBsonRef::as_document,
158 )
159 }
160
161 pub fn get_array(&self, index: usize) -> ValueAccessResult<&RawArray> {
164 self.get_with(index, ElementType::Array, RawBsonRef::as_array)
165 }
166
167 pub fn get_binary(&self, index: usize) -> ValueAccessResult<RawBinaryRef<'_>> {
170 self.get_with(index, ElementType::Binary, RawBsonRef::as_binary)
171 }
172
173 pub fn get_object_id(&self, index: usize) -> ValueAccessResult<ObjectId> {
176 self.get_with(index, ElementType::ObjectId, RawBsonRef::as_object_id)
177 }
178
179 pub fn get_bool(&self, index: usize) -> ValueAccessResult<bool> {
182 self.get_with(index, ElementType::Boolean, RawBsonRef::as_bool)
183 }
184
185 pub fn get_datetime(&self, index: usize) -> ValueAccessResult<DateTime> {
188 self.get_with(index, ElementType::DateTime, RawBsonRef::as_datetime)
189 }
190
191 pub fn get_regex(&self, index: usize) -> ValueAccessResult<RawRegexRef<'_>> {
194 self.get_with(index, ElementType::RegularExpression, RawBsonRef::as_regex)
195 }
196
197 pub fn get_timestamp(&self, index: usize) -> ValueAccessResult<Timestamp> {
200 self.get_with(index, ElementType::Timestamp, RawBsonRef::as_timestamp)
201 }
202
203 pub fn get_i32(&self, index: usize) -> ValueAccessResult<i32> {
206 self.get_with(index, ElementType::Int32, RawBsonRef::as_i32)
207 }
208
209 pub fn get_i64(&self, index: usize) -> ValueAccessResult<i64> {
212 self.get_with(index, ElementType::Int64, RawBsonRef::as_i64)
213 }
214
215 pub fn as_bytes(&self) -> &[u8] {
217 self.doc.as_bytes()
218 }
219
220 pub fn is_empty(&self) -> bool {
222 self.doc.is_empty()
223 }
224}
225
226impl std::fmt::Debug for RawArray {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 f.debug_struct("RawArray")
229 .field("data", &hex::encode(self.doc.as_bytes()))
230 .finish()
231 }
232}
233
234impl TryFrom<&RawArray> for Vec<Bson> {
235 type Error = Error;
236
237 fn try_from(arr: &RawArray) -> Result<Vec<Bson>> {
238 arr.into_iter()
239 .map(|result| {
240 let rawbson = result?;
241 Bson::try_from(rawbson)
242 })
243 .collect()
244 }
245}
246
247impl ToOwned for RawArray {
248 type Owned = RawArrayBuf;
249
250 fn to_owned(&self) -> Self::Owned {
251 self.to_raw_array_buf()
252 }
253}
254
255impl<'a> From<&'a RawArray> for Cow<'a, RawArray> {
256 fn from(rdr: &'a RawArray) -> Self {
257 Cow::Borrowed(rdr)
258 }
259}
260
261impl<'a> IntoIterator for &'a RawArray {
262 type IntoIter = RawArrayIter<'a>;
263 type Item = Result<RawBsonRef<'a>>;
264
265 fn into_iter(self) -> RawArrayIter<'a> {
266 RawArrayIter {
267 inner: RawIter::new(&self.doc),
268 }
269 }
270}
271
272pub struct RawArrayIter<'a> {
274 inner: RawIter<'a>,
275}
276
277impl<'a> Iterator for RawArrayIter<'a> {
278 type Item = Result<RawBsonRef<'a>>;
279
280 fn next(&mut self) -> Option<Result<RawBsonRef<'a>>> {
281 match self.inner.next() {
282 Some(Ok(elem)) => match elem.value() {
283 Ok(value) => Some(Ok(value)),
284 Err(e) => Some(Err(e)),
285 },
286 Some(Err(e)) => Some(Err(e)),
287 None => None,
288 }
289 }
290}
291
292impl<'de: 'a, 'a> Deserialize<'de> for &'a RawArray {
293 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
294 where
295 D: serde::Deserializer<'de>,
296 {
297 match OwnedOrBorrowedRawArray::deserialize(deserializer)? {
298 OwnedOrBorrowedRawArray::Borrowed(b) => Ok(b),
299 o => Err(serde::de::Error::custom(format!(
300 "expected borrowed raw array, instead got owned {:?}",
301 o
302 ))),
303 }
304 }
305}
306
307impl Serialize for &RawArray {
308 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
309 where
310 S: serde::Serializer,
311 {
312 struct SeqSerializer<'a>(&'a RawArray);
313
314 impl Serialize for SeqSerializer<'_> {
315 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
316 where
317 S: serde::Serializer,
318 {
319 if serializer.is_human_readable() {
320 let mut seq = serializer.serialize_seq(None)?;
321 for v in self.0 {
322 let v = v.map_err(serde::ser::Error::custom)?;
323 seq.serialize_element(&v)?;
324 }
325 seq.end()
326 } else {
327 serializer.serialize_bytes(self.0.as_bytes())
328 }
329 }
330 }
331
332 serializer.serialize_newtype_struct(RAW_ARRAY_NEWTYPE, &SeqSerializer(self))
333 }
334}