Skip to content

ReadBits still drops bits on encountering the last byte #11

@itchyny

Description

@itchyny

This is quite similar to #6 but there is another failure case when Read() returns both data and io.EOF.
Here's a sample code.

  • *myReader returns io.EOF with the last byte.
  • Read with ReadBits(n >= 8) including the last byte.
package main

import (
	"fmt"
	"io"
	"os"

	bitstream "github.com/dgryski/go-bitstream"
)

type myReader struct {
	n int
}

func (e *myReader) Read(p []byte) (int, error) {
	switch e.n {
	case 0:
		p[0] = '\xF0'
		e.n++
		return 1, nil
	case 1:
		p[0] = '\x1F'
		e.n++
		return 1, io.EOF
	default:
		return 0, io.EOF
	}
}

func main() {
	br := bitstream.NewReader(&myReader{})
	b, err := br.ReadBits(4)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
	fmt.Printf("%q\n", b)
	b, err = br.ReadBits(8)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
	fmt.Printf("%q\n", b)
	b, err = br.ReadBits(4)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	}
	fmt.Printf("%q\n", b)
	_, err = br.ReadBits(4)
	if err != io.EOF {
		panic("unreachable")
	}
}

The result is

'\x0f'
EOF
exit status 1

But, I expect the following output, no error.

'\x0f'
'\x01'
'\x0f'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions