Skip to content

Commit

Permalink
ERASEME: showcasing derive for Deserialize
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielSimonetto committed Jul 19, 2022
1 parent c900009 commit afb9130
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 31 deletions.
2 changes: 1 addition & 1 deletion noodles-bed/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ documentation = "https://docs.rs/noodles-bed"

[dependencies]
noodles-core = { path = "../noodles-core", version = "0.7.0" }
serde = { version = "1" }
serde = { version = "1", features = ["derive"] }
65 changes: 35 additions & 30 deletions noodles-bed/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,40 +13,43 @@ use serde::de::{
use crate::{Record, reader::Reader, error::{Error, Result}};

const FIELDS: &'static [&'static str] = &["chrom", "start", "end"];
// const FIELDS: &'static [&'static str] = &["Chrom", "Start", "End"];

#[derive(Deserialize, Debug)]
enum Field { Chrom, Start, End }
struct Record3Visitor;


impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> std::result::Result<Field, D::Error>
where
D: serde::Deserializer<'de>,
{
struct FieldVisitor;

impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`chrom`, `start` or `end`")
}

fn visit_str<E>(self, value: &str) -> std::result::Result<Field, E>
where
E: de::Error,
{
match value {
"chrom" => Ok(Field::Chrom),
"start" => Ok(Field::Start),
"end" => Ok(Field::End),
_ => Err(de::Error::unknown_field(value, FIELDS)),
}
}
}

deserializer.deserialize_identifier(FieldVisitor)
}
}
// impl<'de> Deserialize<'de> for Field {
// fn deserialize<D>(deserializer: D) -> std::result::Result<Field, D::Error>
// where
// D: serde::Deserializer<'de>,
// {
// struct FieldVisitor;

// impl<'de> Visitor<'de> for FieldVisitor {
// type Value = Field;

// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
// formatter.write_str("`chrom`, `start` or `end`")
// }

// fn visit_str<E>(self, value: &str) -> std::result::Result<Field, E>
// where
// E: de::Error,
// {
// match value {
// "chrom" => Ok(Field::Chrom),
// "start" => Ok(Field::Start),
// "end" => Ok(Field::End),
// _ => Err(de::Error::unknown_field(value, FIELDS)),
// }
// }
// }

// deserializer.deserialize_identifier(FieldVisitor)
// }
// }

impl<'de> Visitor<'de> for Record3Visitor {
type Value = Record<3>;
Expand Down Expand Up @@ -863,6 +866,8 @@ mod serde_tests {

#[test]
fn test_bed_single_deserialization() {
// wow this works
// let input = r#"{"Chrom":"sq0","Start":8,"End":13}"#;
let input = r#"{"chrom":"sq0","start":8,"end":13}"#;
let result: Record::<3> = from_str(input).unwrap();

Expand Down

0 comments on commit afb9130

Please sign in to comment.