summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorSam Scott <sam.scott89@gmail.com>2017-03-10 19:11:33 -0500
committerSam Scott <sam.scott89@gmail.com>2017-03-10 19:11:33 -0500
commit217dd144ff31af3673624f8a241f7e52995ed9ec (patch)
tree47107f54b3892d8c1e3384b40c73465cf890dc3a /examples
parentb7cb1b9aef155fc9b7b886fc21e92e3e12be0d86 (diff)
Expand tests and examples.
Need to fix sequences.
Diffstat (limited to 'examples')
-rw-r--r--examples/csv_vectors.rs51
1 files changed, 51 insertions, 0 deletions
diff --git a/examples/csv_vectors.rs b/examples/csv_vectors.rs
new file mode 100644
index 0000000..95e4398
--- /dev/null
+++ b/examples/csv_vectors.rs
@@ -0,0 +1,51 @@
+extern crate csv;
+extern crate serde;
+#[macro_use]
+extern crate serde_derive;
+extern crate serde_qs as qs;
+
+#[derive(Debug, Deserialize, Serialize)]
+struct Query {
+ #[serde(deserialize_with="from_csv")]
+ r: Vec<u8>,
+ s: u8,
+}
+
+fn main() {
+ let q = "s=12&r=1,2,3";
+ let q: Query = qs::from_str(&q).unwrap();
+ println!("{:?}", q);
+}
+
+
+fn from_csv<D>(deserializer: D) -> Result<Vec<u8>, D::Error>
+ where D: serde::Deserializer
+{
+ deserializer.deserialize_str(CSVVecVisitor)
+}
+
+/// Visits a string value of the form "v1,v2,v3" into a vector of bytes Vec<u8>
+struct CSVVecVisitor;
+
+impl serde::de::Visitor for CSVVecVisitor {
+ type Value = Vec<u8>;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(formatter, "a str")
+ }
+
+ fn visit_str<E>(self, s: &str) -> std::result::Result<Self::Value, E>
+ where E: serde::de::Error
+ {
+ let mut output = Vec::new();
+ let mut items = csv::Reader::from_string(s);
+ // let items = items.next_str();
+ while let csv::NextField::Data(item) = items.next_str() {
+ output.push(u8::from_str_radix(item, 10).unwrap());
+ }
+
+ Ok(output)
+ }
+
+
+}