ledisdb/server/util.go

63 lines
1.1 KiB
Go
Raw Normal View History

2014-06-09 13:23:32 +04:00
package server
import (
"bufio"
"errors"
2014-09-24 08:34:21 +04:00
"github.com/siddontang/go/hack"
2014-06-09 13:23:32 +04:00
"io"
"strconv"
)
var (
errArrayFormat = errors.New("bad array format")
errBulkFormat = errors.New("bad bulk string format")
errLineFormat = errors.New("bad response line format")
)
2014-07-11 06:43:39 +04:00
func ReadLine(rb *bufio.Reader) ([]byte, error) {
2014-06-09 13:23:32 +04:00
p, err := rb.ReadSlice('\n')
if err != nil {
return nil, err
}
i := len(p) - 2
if i < 0 || p[i] != '\r' {
return nil, errLineFormat
}
return p[:i], nil
}
2014-07-11 06:43:39 +04:00
func ReadBulkTo(rb *bufio.Reader, w io.Writer) error {
l, err := ReadLine(rb)
2014-09-05 06:01:50 +04:00
if err != nil {
return err
} else if len(l) == 0 {
2014-06-10 06:41:50 +04:00
return errBulkFormat
2014-06-09 13:23:32 +04:00
} else if l[0] == '$' {
var n int
//handle resp string
2014-09-24 08:34:21 +04:00
if n, err = strconv.Atoi(hack.String(l[1:])); err != nil {
2014-06-09 13:23:32 +04:00
return err
} else if n == -1 {
return nil
} else {
2014-09-05 06:01:50 +04:00
var nn int64
if nn, err = io.CopyN(w, rb, int64(n)); err != nil {
2014-06-09 13:23:32 +04:00
return err
2014-09-05 06:01:50 +04:00
} else if nn != int64(n) {
return io.ErrShortWrite
2014-06-09 13:23:32 +04:00
}
2014-07-11 06:43:39 +04:00
if l, err = ReadLine(rb); err != nil {
2014-06-09 13:23:32 +04:00
return err
} else if len(l) != 0 {
return errBulkFormat
}
}
} else {
2014-06-10 06:41:50 +04:00
return errBulkFormat
2014-06-09 13:23:32 +04:00
}
return nil
}