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
use Error::{self, ArgumentError};
use Result;
use bson::{self, Bson};
use std::collections::BTreeMap;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ReadMode {
Primary,
PrimaryPreferred,
Secondary,
SecondaryPreferred,
Nearest,
}
impl FromStr for ReadMode {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Ok(match s {
"Primary" => ReadMode::Primary,
"PrimaryPreferred" => ReadMode::PrimaryPreferred,
"Secondary" => ReadMode::Secondary,
"SecondaryPreferred" => ReadMode::SecondaryPreferred,
"Nearest" => ReadMode::Nearest,
_ => {
return Err(ArgumentError(
format!("Could not convert '{}' to ReadMode.", s),
))
}
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReadPreference {
pub mode: ReadMode,
pub tag_sets: Vec<BTreeMap<String, String>>,
}
impl ReadPreference {
pub fn new(mode: ReadMode, tag_sets: Option<Vec<BTreeMap<String, String>>>) -> ReadPreference {
ReadPreference {
mode: mode,
tag_sets: tag_sets.unwrap_or_else(Vec::new),
}
}
pub fn to_document(&self) -> bson::Document {
let mut doc = doc! { "mode": stringify!(self.mode).to_ascii_lowercase() };
let bson_tag_sets: Vec<_> = self.tag_sets
.iter()
.map(|map| {
let mut bson_map = bson::Document::new();
for (key, val) in map.iter() {
bson_map.insert(&key[..], Bson::String(val.to_owned()));
}
Bson::Document(bson_map)
})
.collect();
doc.insert("tag_sets", Bson::Array(bson_tag_sets));
doc
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WriteConcern {
pub w: i32,
pub w_timeout: i32,
pub j: bool,
pub fsync: bool,
}
impl WriteConcern {
pub fn new() -> WriteConcern {
WriteConcern {
w: 1,
w_timeout: 0,
j: false,
fsync: false,
}
}
pub fn to_bson(&self) -> bson::Document {
doc! {
"w": self.w,
"wtimeout": self.w_timeout,
"j": self.j,
}
}
}
impl Default for WriteConcern {
fn default() -> Self {
WriteConcern::new()
}
}
pub fn merge_options<T: Into<bson::Document>>(
document: bson::Document,
options: T,
) -> bson::Document {
let options_doc: bson::Document = options.into();
document
.into_iter()
.chain(options_doc.into_iter())
.collect()
}