1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 // ignore-test needs networking
16 use extra::net::tcp::TcpSocketBuf;
21 use std::io::{ReaderUtil,WriterUtil};
32 priv fn parse_data(len: uint, io: @io::Reader) -> Result {
35 let bytes = io.read_bytes(len as uint);
36 assert_eq!(bytes.len(), len);
41 assert_eq!(io.read_char(), '\r');
42 assert_eq!(io.read_char(), '\n');
46 priv fn parse_list(len: uint, io: @io::Reader) -> Result {
47 let mut list: ~[Result] = ~[];
48 for _ in range(0, len) {
49 let v = match io.read_char() {
50 '$' => parse_bulk(io),
59 priv fn chop(s: ~str) -> ~str {
60 s.slice(0, s.len() - 1).to_owned()
63 priv fn parse_bulk(io: @io::Reader) -> Result {
64 match from_str::<int>(chop(io.read_line())) {
67 Some(len) if len >= 0 => parse_data(len as uint, io),
72 priv fn parse_multi(io: @io::Reader) -> Result {
73 match from_str::<int>(chop(io.read_line())) {
77 Some(len) if len >= 0 => parse_list(len as uint, io),
82 priv fn parse_int(io: @io::Reader) -> Result {
83 match from_str::<int>(chop(io.read_line())) {
89 priv fn parse_response(io: @io::Reader) -> Result {
90 match io.read_char() {
91 '$' => parse_bulk(io),
92 '*' => parse_multi(io),
93 '+' => Status(chop(io.read_line())),
94 '-' => Error(chop(io.read_line())),
100 priv fn cmd_to_str(cmd: ~[~str]) -> ~str {
102 res.push_str(cmd.len().to_str());
103 res.push_str("\r\n");
104 for s in cmd.iter() {
105 res.push_str([~"$", s.len().to_str(), ~"\r\n",
106 (*s).clone(), ~"\r\n"].concat() );
111 fn query(cmd: ~[~str], sb: TcpSocketBuf) -> Result {
112 let cmd = cmd_to_str(cmd);
113 //println!("{}", cmd);
115 let res = parse_response(@sb as @io::Reader);
119 fn query2(cmd: ~[~str]) -> Result {
120 let _cmd = cmd_to_str(cmd);
121 io::with_str_reader(~"$3\r\nXXX\r\n")(|sb| {
122 let res = parse_response(@sb as @io::Reader);
123 println!("{:?}", res);