Compare commits

..

2 Commits

Author SHA1 Message Date
Charles Iliya Krempeaux e13b13e548 initial commits 2023-11-30 10:04:06 -08:00
Charles Iliya Krempeaux 76c2e8cf86 initial commits 2023-11-30 10:00:33 -08:00
3 changed files with 159 additions and 0 deletions

9
errors.go 100644
View File

@ -0,0 +1,9 @@
package bytereader
import (
"sourcecode.social/reiver/go-erorr"
)
const (
errNilReceiver = erorr.Error("bytereader: nil receiver")
)

43
string.go 100644
View File

@ -0,0 +1,43 @@
package bytereader
import (
"io"
)
var _ io.ByteReader = &internalByteReaderFromString{}
type internalByteReaderFromString struct {
value string
index int
}
// NewByteReaderFromString returns a new io.ByteReader from a string.
//
// Example usage:
//
// var s string = "ONCE 🙂 TWICE 🙂 THRICE 🙂 FOURCE"
//
// var byteReader io.ByteReader = bytereader.NewByteReaderFromString(s)
func NewByteReaderFromString(value string) io.ByteReader {
return &internalByteReaderFromString{
value:value,
}
}
func (receiver *internalByteReaderFromString) ReadByte() (byte, error) {
if nil == receiver {
return 0, errNilReceiver
}
var value string = receiver.value
var index int = receiver.index
if len(value) <= index {
return 0, io.EOF
}
var b byte = receiver.value[index]
receiver.index++
return b, nil
}

107
string_test.go 100644
View File

@ -0,0 +1,107 @@
package bytereader_test
import (
"testing"
"io"
"sourcecode.social/reiver/go-bytereader"
)
func TestNewByteReaderFromString(t *testing.T) {
tests := []struct{
Value string
}{
{
Value: "",
},
{
Value: "apple",
},
{
Value: "banana",
},
{
Value: "cherry",
},
{
Value: "ONCE TWICE THRICE FOURCE",
},
{
Value: "۰۱۲۳۴۵۶۷۸۹",
},
{
Value: "😈 👹 😡",
},
}
testloop: for testNumber, test := range tests {
var byteReader io.ByteReader = bytereader.NewByteReaderFromString(test.Value)
var buffer [64]byte
var p []byte = buffer[0:0]
{
length := len(test.Value)
for i:=0; i<length; i++ {
b, err := byteReader.ReadByte()
if nil != err {
t.Errorf("For test #%d and loop #%d, did not expect an error but actually got one.", testNumber, i)
t.Logf("ERROR: (%T) %s", err, err)
t.Logf("VALUE: %q", test.Value)
continue testloop
}
p = append(p, b)
}
}
{
_, err := byteReader.ReadByte()
if nil == err {
t.Errorf("For test #%d, expected an error but did not actually get one.", testNumber)
t.Logf("VALUE: %q", test.Value)
continue testloop
}
{
expected := io.EOF
actual := err
if expected != actual {
t.Errorf("For test #%d, expected an io.EOF error but actually got a different error.", testNumber)
t.Logf("ERROR: (%T) %s", err, err)
t.Logf("VALUE: %q", test.Value)
continue testloop
}
}
}
{
expected := test.Value
actual := string(p)
if expected != actual {
t.Errorf("For test #%d, the actual read value is not what was expected.", testNumber)
t.Logf("EXPECTED: %q", expected)
t.Logf("ACTUAL: %q", actual)
continue testloop
}
}
}
}