Permalink
Browse files

storage: ReadAll(chan *Record, bufio.Reader)

  • Loading branch information...
1 parent 3d054a2 commit 1a0d290ded6d71fbfac7515802b6883a81887644 @temoto committed Dec 9, 2012
Showing with 57 additions and 0 deletions.
  1. +57 −0 oakmole/storage.go
View
@@ -9,6 +9,7 @@ import (
"hash/crc32"
"io"
"io/ioutil"
+ "log"
"net"
)
@@ -246,6 +247,62 @@ func (r *Record) ReadFrom(reader *bufio.Reader) (n int64, err error) {
return n, err
}
+// Returns number of bytes scanned and error, if any.
+func ReadAll(ch chan *Record, reader *bufio.Reader, stop chan bool) (pos int64, err error) {
+ var n int64
+ var b []byte
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+
+ record := &Record{}
+ n, err = record.ReadFrom(reader)
+ if err == nil {
+ pos += n
+ ch <- record
+ } else if err == io.EOF {
+ return pos, nil
+ } else {
+ log.Println("ReadAll: position:", pos, "error:", err)
+
+ // Enter recovery mode.
+ // Try to skip 1 byte until we find magic number.
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+
+ _, err = reader.ReadByte()
+ if err != nil {
+ if err == io.EOF {
+ return pos, nil
+ }
+ return pos, err
+ }
+
+ b, err = reader.Peek(4)
+ if err != nil {
+ if err == io.EOF {
+ return pos, nil
+ }
+ return pos, err
+ }
+ number := binary.BigEndian.Uint32(b)
+ if number == MagicNumber {
+ // Exit recovery mode.
+ break
+ }
+ }
+ }
+ }
+ return pos, nil
+}
+
func initStorage() {
}

0 comments on commit 1a0d290

Please sign in to comment.