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
use std::io::{Result, Error, ErrorKind};
use std::net::ToSocketAddrs;

use super::{Value, encode_slice};
use super::connection::Connection;

pub fn create_client(hostname: &str, port: u16, password: &str, db: u16) -> Result<Client> {
    let mut client = try!(Client::new((hostname, port)));
    try!(client.init(password, db));
    Ok(client)
}

pub struct Client {
    conn: Connection,
}

impl Client {
    pub fn new<A: ToSocketAddrs>(addrs: A) -> Result<Self> {
        Ok(Client { conn: try!(Connection::new(addrs)) })
    }

    pub fn cmd(&mut self, slice: &[&str]) -> Result<Value> {
        let buf = encode_slice(slice);
        self.conn.write(&buf).unwrap();
        self.conn.read()
    }

    pub fn read_more(&mut self) -> Result<Value> {
        self.conn.read()
    }

    fn init(&mut self, password: &str, db: u16) -> Result<()> {
        if password.len() > 0 {
            if let Value::Error(err) = try!(self.cmd(&["auth", password])) {
                return Err(Error::new(ErrorKind::PermissionDenied, err));
            }

        }
        if db > 0 {
            if let Value::Error(err) = try!(self.cmd(&["select", &db.to_string()])) {
                return Err(Error::new(ErrorKind::InvalidInput, err));
            }
        }
        Ok(())
    }
}