Skip to content

Instantly share code, notes, and snippets.

@btoews
Created December 7, 2017 22:32
Show Gist options
  • Save btoews/9777da28228d3a1ffb162ac43bdccf25 to your computer and use it in GitHub Desktop.
Save btoews/9777da28228d3a1ffb162ac43bdccf25 to your computer and use it in GitHub Desktop.
Blob Reader
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"time"
)
type packfileReader struct {
r *bufio.Reader
last *bufio.Reader
lastLen int
err error
}
func newPackfileReader(r io.Reader) *packfileReader {
return &packfileReader{
r: bufio.NewReader(r),
last: bufio.NewReader(nil),
}
}
func (pfr *packfileReader) nextHeader() (sha string, typ string, rlen int64) {
if pfr.err != nil {
return
}
if sha, pfr.err = pfr.r.ReadString(' '); pfr.err != nil {
return
}
sha = sha[:len(sha)-1]
if typ, pfr.err = pfr.r.ReadString(' '); pfr.err != nil {
return
}
typ = typ[:len(typ)-1]
var rlenStr string
if rlenStr, pfr.err = pfr.r.ReadString('\n'); pfr.err != nil {
return
}
rlenStr = rlenStr[:len(rlenStr)-1]
if rlen, pfr.err = strconv.ParseInt(rlenStr, 10, 64); pfr.err != nil {
return
}
// thanks @ptoomey3 ;-)
rlen++
return
}
func (pfr *packfileReader) nextBlob() io.Reader {
if pfr.err != nil {
return nil
}
pfr.clearLast()
var (
typ string
len int64
)
for _, typ, len = pfr.nextHeader(); pfr.err == nil; _, typ, len = pfr.nextHeader() {
if typ != "blob" {
_, pfr.err = pfr.r.Discard(int(len))
continue
}
lr := io.LimitReader(pfr.r, len)
pfr.last.Reset(lr)
pfr.lastLen = int(len)
return lr
}
return nil
}
func (pfr *packfileReader) clearLast() {
if pfr.lastLen > 0 {
pfr.last.Discard(pfr.lastLen)
pfr.lastLen = 0
}
}
func (pfr *packfileReader) Error() error {
err := pfr.err
if err == io.EOF {
return nil
}
pfr.err = nil
return err
}
func main() {
pfr := newPackfileReader(os.Stdin)
for blobReader := pfr.nextBlob(); blobReader != nil; blobReader = pfr.nextBlob() {
io.Copy(os.Stdout, blobReader)
}
if err := pfr.Error(); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment