Skip to content

Commit

Permalink
Refactor pool reader to use Reader
Browse files Browse the repository at this point in the history
  • Loading branch information
elct9620 committed Sep 7, 2023
1 parent 3506777 commit 0f5189d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 20 deletions.
31 changes: 11 additions & 20 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,38 @@ package mruby

import (
"errors"
"io"
)

var ErrUnsupportPoolValueType = errors.New("unsupport pool value type")

type PoolType uint8
type poolType uint8

const (
poolTypeString PoolType = iota
poolTypeString poolType = iota
poolTypeInt32
poolTypeStaticString
poolTypeInt64
poolTypeFloat = 5
poolTypeBigInt = 7
)

type PoolReader = func(io.Reader) (Value, error)
type PoolReader = func(*Reader) (Value, error)

var poolReaders = map[PoolType]PoolReader{
var poolReaders = map[poolType]PoolReader{
poolTypeString: poolReadString,
}

func readPoolValues(ir *irep, r io.Reader) error {
var pLen uint16
err := binaryRead(r, &pLen)
func readPoolValues(ir *irep, r *Reader) error {
pLen, err := r.ReadUint16()
if err != nil {
return err
}

ir.poolValue = make([]Value, pLen)

var pType PoolType
var pType poolType
for i := 0; i < int(pLen); i++ {
err = binaryRead(r, &pType)
err = r.ReadAs(&pType)
if err != nil {
return err
}
Expand All @@ -56,18 +54,11 @@ func readPoolValues(ir *irep, r io.Reader) error {
return nil
}

func poolReadString(r io.Reader) (Value, error) {
var sLen uint16
err := binaryRead(r, &sLen)
func poolReadString(r *Reader) (Value, error) {
sLen, err := r.ReadUint16()
if err != nil {
return "", err
}

s := make([]byte, sLen+1)
err = binaryRead(r, s)
if err != nil {
return "", err
}

return string(s[0:sLen]), nil
return r.ReadString(int(sLen + 1))
}
16 changes: 16 additions & 0 deletions reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,19 @@ func NewBytesReader(b []byte) *Reader {
func (r *Reader) ReadAs(data any) error {
return binary.Read(r, r.ByteOrder, data)
}

func (r *Reader) ReadUint16() (uint16, error) {
var data uint16
err := r.ReadAs(&data)
return data, err
}

func (r *Reader) ReadString(length int) (string, error) {
buffer := make([]byte, length)
err := r.ReadAs(buffer)
if err != nil {
return "", err
}

return string(buffer[0 : length-1]), nil
}

0 comments on commit 0f5189d

Please sign in to comment.