1use std::io::{Result, Error, ErrorKind};
2use std::net::ToSocketAddrs;
3
4use super::{Value, encode_slice};
5use super::connection::Connection;
6
7pub fn create_client(hostname: &str, port: u16, password: &str, db: u16) -> Result<Client> {
8 let mut client = try!(Client::new((hostname, port)));
9 try!(client.init(password, db));
10 Ok(client)
11}
12
13pub struct Client {
14 conn: Connection,
15}
16
17impl Client {
18 pub fn new<A: ToSocketAddrs>(addrs: A) -> Result<Self> {
19 Ok(Client { conn: try!(Connection::new(addrs)) })
20 }
21
22 pub fn cmd(&mut self, slice: &[&str]) -> Result<Value> {
23 let buf = encode_slice(slice);
24 self.conn.write(&buf).unwrap();
25 self.conn.read()
26 }
27
28 pub fn read_more(&mut self) -> Result<Value> {
29 self.conn.read()
30 }
31
32 fn init(&mut self, password: &str, db: u16) -> Result<()> {
33 if password.len() > 0 {
34 if let Value::Error(err) = try!(self.cmd(&["auth", password])) {
35 return Err(Error::new(ErrorKind::PermissionDenied, err));
36 }
37
38 }
39 if db > 0 {
40 if let Value::Error(err) = try!(self.cmd(&["select", &db.to_string()])) {
41 return Err(Error::new(ErrorKind::InvalidInput, err));
42 }
43 }
44 Ok(())
45 }
46}