Skip to content

Commit

Permalink
github.com/qiniu/x/bufiox
Browse files Browse the repository at this point in the history
  • Loading branch information
xushiwei committed Mar 30, 2020
1 parent ec64d93 commit 05018c1
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions bufiox/bufio.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package bufiox

import (
"bufio"
"bytes"
"io"
"unsafe"
)

// -----------------------------------------------------------------------------

type nilReaderImpl int

func (p nilReaderImpl) Read(b []byte) (n int, err error) {
return 0, io.EOF
}

var nilReader io.Reader = nilReaderImpl(0)

// -----------------------------------------------------------------------------

type reader struct {
buf []byte
rd io.Reader // reader provided by the client
r, w int // buf read and write positions
err error
lastByte int
lastRuneSize int
}

// NewReaderBuffer returns a new Reader who uses a extern buffer.
func NewReaderBuffer(buf []byte) *bufio.Reader {
r := &reader{
buf: buf,
rd: nilReader,
w: len(buf),
lastByte: -1,
lastRuneSize: -1,
}
b := new(bufio.Reader)
*b = *(*bufio.Reader)(unsafe.Pointer(r))
return b
}

// Buffer is reserved for internal use.
func Buffer(b *bufio.Reader) []byte {
r := (*reader)(unsafe.Pointer(b))
return r.buf
}

// IsReaderBuffer returns if this Reader instance is returned by NewReaderBuffer
func IsReaderBuffer(b *bufio.Reader) bool {
r := (*reader)(unsafe.Pointer(b))
return r.rd == nilReader
}

// ReadAll reads all data
func ReadAll(b *bufio.Reader) (ret []byte, err error) {
r := (*reader)(unsafe.Pointer(b))
if r.rd == nilReader {
ret, r.buf = r.buf, nil
return
}
var w bytes.Buffer
_, err1 := b.WriteTo(&w)
return w.Bytes(), err1
}

// -----------------------------------------------------------------------------

0 comments on commit 05018c1

Please sign in to comment.