Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

index: ReadFrom/WriteTo returns IndexReadError/IndexWriteError. #9

Merged
merged 1 commit into from
Nov 12, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 31 additions & 9 deletions index.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"path/filepath"
"sort"
"time"
"path/filepath"
)

var (
Expand All @@ -34,21 +35,26 @@ type Index []*IndexEntry
// file
func (i *Index) ReadFrom(r io.ReadSeeker, endBlock uint64) error {
if _, err := r.Seek(int64(endBlock)-indexFooterSize, io.SeekStart); err != nil {
return err
return &IndexReadError{err}
}

f, err := i.readFooter(r)
if err != nil {
return err
return &IndexReadError{err}
}

startingPos := int64(f.IndexSize) + indexFooterSize
if _, err := r.Seek(-startingPos, io.SeekCurrent); err != nil {
return err
return &IndexReadError{err}
}

defer sort.Sort(i)
return i.readIndex(r, f, endBlock)
err = i.readIndex(r, f, endBlock)
if err != nil {
return &IndexReadError{err}
}

return nil
}

func (i *Index) readFooter(r io.Reader) (*IndexFooter, error) {
Expand Down Expand Up @@ -128,18 +134,18 @@ func (i *Index) WriteTo(w io.Writer) error {
}

if _, err := hw.Write(IndexSignature); err != nil {
return err
return &IndexWriteError{err}
}

if err := binary.Write(hw, binary.BigEndian, IndexVersion); err != nil {
return err
return &IndexWriteError{err}
}

var blockSize uint64
for _, e := range *i {
blockSize += e.Size
if err := e.WriteTo(hw); err != nil {
return err
return &IndexWriteError{err}
}
}

Expand All @@ -148,7 +154,7 @@ func (i *Index) WriteTo(w io.Writer) error {
f.CRC32 = hw.Checksum()

if err := f.WriteTo(hw); err != nil {
return err
return &IndexWriteError{err}
}

return nil
Expand Down Expand Up @@ -363,3 +369,19 @@ func readIndexAt(r io.ReadSeeker, offset uint64) (Index, error) {
i = append(i, previ...)
return i, nil
}

type IndexReadError struct {
Err error
}

func (e *IndexReadError) Error() string {
return fmt.Sprintf("index read failed: %s", e.Err.Error())
}

type IndexWriteError struct {
Err error
}

func (e *IndexWriteError) Error() string {
return fmt.Sprintf("index write failed: %s", e.Err.Error())
}