discogs 0.3.1

A Library to consume Discogs API
Documentation
// Copyright (C) 2018 The discogs-rs developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt;
use std::str::FromStr;
use hyper::header::*;
use hyper;

#[derive(Clone, PartialEq, Debug)]
pub struct DiscogsKSAuth {
    pub key: String,
    pub secret: String
}

impl Scheme for DiscogsKSAuth {
    fn scheme() -> Option<&'static str> {
        Some("Discogs")
    }

    fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(format!("key={}, secret={}", self.key, self.secret).as_str())
    }
}

//TODO: Make a neater implementation of this
//TODO: This parser currently doesent handle the ", " that happens in the middle of the aut request
impl FromStr for DiscogsKSAuth {
    type Err = hyper::error::Error;
    fn from_str(s: &str) -> hyper::Result<DiscogsKSAuth> {
        match String::from_utf8(s.into()) {
            Ok(text) => {
                let mut parts = &mut text.split(' ');
                let key = match parts.next() {
                    Some(key_part) => {
                        let mut kp = &mut key_part.split('=');
                        kp.next();
                        match kp.next() {
                            Some(t) => t.to_owned(),
                            None => return Err(hyper::error::Error::Header)
                        }
                    }
                    None => return Err(hyper::error::Error::Header)
                };
                let secret = match parts.next() {
                    Some(secret_part) => {
                        let mut sp = &mut secret_part.split('=');
                        sp.next();
                        match sp.next() {
                            Some(t) => t.to_owned(),
                            None => return Err(hyper::error::Error::Header)
                        }
                    }
                    None => return Err(hyper::error::Error::Header)
                };
                Ok(DiscogsKSAuth {
                    key: key,
                    secret: secret
                })
            },
            Err(e) => {
                println!("DiscogsKSAuth::from_utf8 error={:?}", e);
                Err(hyper::error::Error::Header)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use hyper::header::{Authorization, Basic, Bearer};
    use hyper::header::{Headers, Header};
    use query::DiscogsKSAuth;

    #[test]
    fn test_discogsks_auth() {
        let mut headers = Headers::new();
        headers.set(Authorization(DiscogsKSAuth {
            key: "Aladdin".to_owned(),
            secret: "sesame".to_owned()
        }));
        assert_eq!(
            headers.to_string(),
            "Authorization: Discogs key=Aladdin, secret=sesame\r\n".to_owned());
    }

    #[test]
    fn test_discogsks_auth_parse() {
        let auth: Authorization<DiscogsKSAuth> = Header::parse_header(
            &[b"Discogs key=Aladdin secret=sesame".to_vec()])
            .unwrap();
        assert_eq!(auth.0.key, "Aladdin".to_owned());
        assert_eq!(auth.0.secret, "sesame".to_owned());
    }
}

//bench_header!(discogs_ks_bench,
//              Authorization<DiscogsKSAuth>,
//              { vec![b"Discogs key=Aladdin secret=sesame".to_vec()] });

#[cfg(all(test, feature = "nightly"))]
mod discogs_ks_bench {
    use test::Bencher;
    use super::*;

    use hyper::header::*;

    #[bench]
    fn bench_parse(b: &mut Bencher) {
        let val = &[b"Discogs key=Aladdin secret=sesame".to_vec()];
        b.iter(|| {
            let _: Authorization<DiscogsKSAuth> = Header::parse_header(val).unwrap();
        });
    }

    //#[bench]
    //fn bench_format(b: &mut Bencher) {
    //    let raw = &[b"Discogs key=Aladdin secret=sesame".to_vec()];
    //    let val: Authorization<DiscogsKSAuth> = Header::parse_header(raw).unwrap();
    //    b.iter(|| {
    //        format!("{}", val);
    //    });
    //}
}