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

Minor improvements #8

Merged
merged 3 commits into from
May 19, 2024
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
18 changes: 8 additions & 10 deletions cobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,16 @@ func NewEncoder(w io.Writer) *Encoder {
e := new(Encoder)

e.w = w
// Create a buffer with maximum capacity for a block
// Create a buffer with maximum capacity for a group
e.buf = make([]byte, 1, 255)
e.buf[0] = 1

return e
}

func (e *Encoder) finish() (err error) {
for i, n := 0, 0; i < len(e.buf); i += n {
if n, err = e.w.Write(e.buf[i:]); err != nil {
return err
}
func (e *Encoder) finish() error {
if _, err := e.w.Write(e.buf); err != nil {
return err
}

// reset buffer
Expand All @@ -63,7 +61,7 @@ func (e *Encoder) finish() (err error) {
// WriteByte encodes a single byte c. If a group is finished
// it is written to w.
func (e *Encoder) WriteByte(c byte) error {
// Finish if block is full
// Finish if group is full
if e.buf[0] == 0xff {
if err := e.finish(); err != nil {
return err
Expand Down Expand Up @@ -98,16 +96,16 @@ func (e *Encoder) Close() error {
}

// Encode encodes and returns a byte slice.
func Encode(data []byte) (enc []byte, err error) {
func Encode(data []byte) ([]byte, error) {
// Reserve a buffer with overhead room
buf := bytes.NewBuffer(make([]byte, 0, len(data) + (len(data) + 253) / 254))
e := NewEncoder(buf)

if _, err = e.Write(data); err != nil {
if _, err := e.Write(data); err != nil {
return buf.Bytes(), err
}

err = e.Close()
err := e.Close()

return buf.Bytes(), err
}
Expand Down