use std::error;
use std::fmt::{self, Debug, Display, Formatter};
use std::iter::{FromIterator, Map};
use std::marker::PhantomData;
use chrono::{DateTime, Utc};
use linked_hash_map::{self, LinkedHashMap};
use serde::de::{self, MapAccess, Visitor};
use bson::{Array, Bson, Document};
use oid::ObjectId;
use spec::BinarySubtype;
#[derive(PartialEq)]
pub enum ValueAccessError {
NotPresent,
UnexpectedType,
}
pub type ValueAccessResult<T> = Result<T, ValueAccessError>;
impl Debug for ValueAccessError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
ValueAccessError::NotPresent => write!(f, "ValueAccessError: field is not present"),
ValueAccessError::UnexpectedType => write!(f, "ValueAccessError: field does not have the expected type"),
}
}
}
impl Display for ValueAccessError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
ValueAccessError::NotPresent => write!(f, "field is not present"),
ValueAccessError::UnexpectedType => write!(f, "field does not have the expected type"),
}
}
}
impl error::Error for ValueAccessError {
fn description(&self) -> &str {
"Error to indicate that either a value was empty or it contained an unexpected type"
}
}
#[derive(Clone, PartialEq)]
pub struct OrderedDocument {
inner: LinkedHashMap<String, Bson>,
}
impl Default for OrderedDocument {
fn default() -> Self {
Document::new()
}
}
impl Display for OrderedDocument {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
fmt.write_str("{")?;
let mut first = true;
for (k, v) in self {
if first {
first = false;
fmt.write_str(" ")?;
} else {
fmt.write_str(", ")?;
}
write!(fmt, "{}: {}", k, v)?;
}
write!(fmt, "{}}}", if !first { " " } else { "" })
}
}
impl Debug for OrderedDocument {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "OrderedDocument({:?})", self.inner)
}
}
pub struct OrderedDocumentIntoIterator {
inner: LinkedHashMap<String, Bson>,
}
pub struct OrderedDocumentIterator<'a> {
inner: linked_hash_map::Iter<'a, String, Bson>,
}
pub struct Keys<'a> {
inner: Map<OrderedDocumentIterator<'a>, fn((&'a String, &'a Bson)) -> &'a String>,
}
pub struct Values<'a> {
inner: Map<OrderedDocumentIterator<'a>, fn((&'a String, &'a Bson)) -> &'a Bson>,
}
impl<'a> Iterator for Keys<'a> {
type Item = &'a String;
fn next(&mut self) -> Option<(&'a String)> {
self.inner.next()
}
}
impl<'a> Iterator for Values<'a> {
type Item = &'a Bson;
fn next(&mut self) -> Option<(&'a Bson)> {
self.inner.next()
}
}
impl IntoIterator for OrderedDocument {
type Item = (String, Bson);
type IntoIter = OrderedDocumentIntoIterator;
fn into_iter(self) -> Self::IntoIter {
OrderedDocumentIntoIterator { inner: self.inner }
}
}
impl<'a> IntoIterator for &'a OrderedDocument {
type Item = (&'a String, &'a Bson);
type IntoIter = OrderedDocumentIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
OrderedDocumentIterator { inner: self.inner.iter(), }
}
}
impl FromIterator<(String, Bson)> for OrderedDocument {
fn from_iter<T: IntoIterator<Item = (String, Bson)>>(iter: T) -> Self {
let mut doc = OrderedDocument::new();
for (k, v) in iter {
doc.insert(k, v);
}
doc
}
}
impl<'a> Iterator for OrderedDocumentIntoIterator {
type Item = (String, Bson);
fn next(&mut self) -> Option<(String, Bson)> {
self.inner.pop_front()
}
}
impl<'a> Iterator for OrderedDocumentIterator<'a> {
type Item = (&'a String, &'a Bson);
fn next(&mut self) -> Option<(&'a String, &'a Bson)> {
self.inner.next()
}
}
impl OrderedDocument {
pub fn new() -> OrderedDocument {
OrderedDocument { inner: LinkedHashMap::new(), }
}
pub fn iter<'a>(&'a self) -> OrderedDocumentIterator<'a> {
self.into_iter()
}
pub fn clear(&mut self) {
self.inner.clear();
}
pub fn get(&self, key: &str) -> Option<&Bson> {
self.inner.get(key)
}
pub fn get_mut(&mut self, key: &str) -> Option<&mut Bson> {
self.inner.get_mut(key)
}
pub fn get_f64(&self, key: &str) -> ValueAccessResult<f64> {
match self.get(key) {
Some(&Bson::FloatingPoint(v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_str(&self, key: &str) -> ValueAccessResult<&str> {
match self.get(key) {
Some(&Bson::String(ref v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_array(&self, key: &str) -> ValueAccessResult<&Array> {
match self.get(key) {
Some(&Bson::Array(ref v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_document(&self, key: &str) -> ValueAccessResult<&Document> {
match self.get(key) {
Some(&Bson::Document(ref v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_bool(&self, key: &str) -> ValueAccessResult<bool> {
match self.get(key) {
Some(&Bson::Boolean(v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn is_null(&self, key: &str) -> bool {
self.get(key) == Some(&Bson::Null)
}
pub fn get_i32(&self, key: &str) -> ValueAccessResult<i32> {
match self.get(key) {
Some(&Bson::I32(v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_i64(&self, key: &str) -> ValueAccessResult<i64> {
match self.get(key) {
Some(&Bson::I64(v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_time_stamp(&self, key: &str) -> ValueAccessResult<i64> {
match self.get(key) {
Some(&Bson::TimeStamp(v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_binary_generic(&self, key: &str) -> ValueAccessResult<&Vec<u8>> {
match self.get(key) {
Some(&Bson::Binary(BinarySubtype::Generic, ref v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_object_id(&self, key: &str) -> ValueAccessResult<&ObjectId> {
match self.get(key) {
Some(&Bson::ObjectId(ref v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn get_utc_datetime(&self, key: &str) -> ValueAccessResult<&DateTime<Utc>> {
match self.get(key) {
Some(&Bson::UtcDatetime(ref v)) => Ok(v),
Some(_) => Err(ValueAccessError::UnexpectedType),
None => Err(ValueAccessError::NotPresent),
}
}
pub fn contains_key(&self, key: &str) -> bool {
self.inner.contains_key(key)
}
pub fn keys<'a>(&'a self) -> Keys<'a> {
fn first<A, B>((a, _): (A, B)) -> A {
a
}
let first: fn((&'a String, &'a Bson)) -> &'a String = first;
Keys { inner: self.iter().map(first), }
}
pub fn values<'a>(&'a self) -> Values<'a> {
fn second<A, B>((_, b): (A, B)) -> B {
b
}
let second: fn((&'a String, &'a Bson)) -> &'a Bson = second;
Values { inner: self.iter().map(second), }
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn insert<KT: Into<String>, BT: Into<Bson>>(&mut self, key: KT, val: BT) -> Option<Bson> {
self.insert_bson(key.into(), val.into())
}
pub fn insert_bson(&mut self, key: String, val: Bson) -> Option<Bson> {
self.inner.insert(key, val)
}
pub fn remove(&mut self, key: &str) -> Option<Bson> {
self.inner.remove(key)
}
pub fn entry(&mut self, k: String) -> Entry {
Entry { inner: self.inner.entry(k), }
}
}
pub struct Entry<'a> {
inner: linked_hash_map::Entry<'a, String, Bson>,
}
impl<'a> Entry<'a> {
pub fn key(&self) -> &str {
self.inner.key()
}
pub fn or_insert(self, default: Bson) -> &'a mut Bson {
self.inner.or_insert(default)
}
pub fn or_insert_with<F: FnOnce() -> Bson>(self, default: F) -> &'a mut Bson {
self.inner.or_insert_with(default)
}
}
impl From<LinkedHashMap<String, Bson>> for OrderedDocument {
fn from(tree: LinkedHashMap<String, Bson>) -> OrderedDocument {
OrderedDocument { inner: tree }
}
}
pub struct OrderedDocumentVisitor {
marker: PhantomData<OrderedDocument>,
}
impl OrderedDocumentVisitor {
pub fn new() -> OrderedDocumentVisitor {
OrderedDocumentVisitor { marker: PhantomData, }
}
}
impl<'de> Visitor<'de> for OrderedDocumentVisitor {
type Value = OrderedDocument;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "expecting ordered document")
}
#[inline]
fn visit_unit<E>(self) -> Result<OrderedDocument, E>
where E: de::Error
{
Ok(OrderedDocument::new())
}
#[inline]
fn visit_map<V>(self, mut visitor: V) -> Result<OrderedDocument, V::Error>
where V: MapAccess<'de>
{
let mut inner = match visitor.size_hint() {
Some(size) => LinkedHashMap::with_capacity(size),
None => LinkedHashMap::new(),
};
while let Some((key, value)) = visitor.next_entry()? {
inner.insert(key, value);
}
Ok(inner.into())
}
}