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.
11 // ignore-test needs networking
15 use extra::net::tcp::TcpSocketBuf;
20 use std::io::{ReaderUtil,WriterUtil};
31 priv fn parse_data(len: uint, io: @io::Reader) -> Result {
34 let bytes = io.read_bytes(len as uint);
35 assert_eq!(bytes.len(), len);
40 assert_eq!(io.read_char(), '\r');
41 assert_eq!(io.read_char(), '\n');
45 priv fn parse_list(len: uint, io: @io::Reader) -> Result {
46 let mut list: ~[Result] = ~[];
47 for _ in range(0, len) {
48 let v = match io.read_char() {
49 '$' => parse_bulk(io),
58 priv fn chop(s: ~str) -> ~str {
59 s.slice(0, s.len() - 1).to_owned()
62 priv fn parse_bulk(io: @io::Reader) -> Result {
63 match from_str::<int>(chop(io.read_line())) {
66 Some(len) if len >= 0 => parse_data(len as uint, io),
71 priv fn parse_multi(io: @io::Reader) -> Result {
72 match from_str::<int>(chop(io.read_line())) {
76 Some(len) if len >= 0 => parse_list(len as uint, io),
81 priv fn parse_int(io: @io::Reader) -> Result {
82 match from_str::<int>(chop(io.read_line())) {
88 priv fn parse_response(io: @io::Reader) -> Result {
89 match io.read_char() {
90 '$' => parse_bulk(io),
91 '*' => parse_multi(io),
92 '+' => Status(chop(io.read_line())),
93 '-' => Error(chop(io.read_line())),
99 priv fn cmd_to_str(cmd: ~[~str]) -> ~str {
100 let mut res = "*".to_owned();
101 res.push_str(cmd.len().to_str());
102 res.push_str("\r\n");
103 for s in cmd.iter() {
104 res.push_str(["$".to_owned(), s.len().to_str(), "\r\n".to_owned(),
105 (*s).clone(), "\r\n".to_owned()].concat() );
110 fn query(cmd: ~[~str], sb: TcpSocketBuf) -> Result {
111 let cmd = cmd_to_str(cmd);
112 //println!("{}", cmd);
114 let res = parse_response(@sb as @io::Reader);
118 fn query2(cmd: ~[~str]) -> Result {
119 let _cmd = cmd_to_str(cmd);
120 io::with_str_reader("$3\r\nXXX\r\n".to_owned())(|sb| {
121 let res = parse_response(@sb as @io::Reader);
122 println!("{:?}", res);