stream/mts/meta: simplified meta checking for Get and GetAll

This commit is contained in:
saxon 2019-02-09 22:25:36 +10:30
parent 50575270b9
commit cc0becf58c
1 changed files with 6 additions and 15 deletions

View File

@ -50,8 +50,7 @@ const (
var ( var (
errKeyAbsent = errors.New("Key does not exist in map") errKeyAbsent = errors.New("Key does not exist in map")
errNoHeader = errors.New("Metadata string does not contain header") errInvalidMeta = errors.New("Invalid metadata given")
errInvalidHeader = errors.New("Metadata string does not contain valid header")
errUnexpectedMetaFormat = errors.New("Unexpected meta format") errUnexpectedMetaFormat = errors.New("Unexpected meta format")
) )
@ -167,7 +166,7 @@ func (m *Data) Encode() []byte {
// Get returns the value for the given key in d. // Get returns the value for the given key in d.
func Get(key string, d []byte) (string, error) { func Get(key string, d []byte) (string, error) {
err := checkHeader(d) err := checkMeta(d)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -184,13 +183,7 @@ func Get(key string, d []byte) (string, error) {
// GetAll returns metadata keys and values from d. // GetAll returns metadata keys and values from d.
func GetAll(d []byte) ([][2]string, error) { func GetAll(d []byte) ([][2]string, error) {
if d == nil { err := checkMeta(d)
return nil, errors.New("nil slice given")
}
if len(d) == 0 {
return nil, errors.New("empty slice given")
}
err := checkHeader(d)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -208,11 +201,9 @@ func GetAll(d []byte) ([][2]string, error) {
} }
// checkHeader checks that a valid metadata header exists in the given data. // checkHeader checks that a valid metadata header exists in the given data.
func checkHeader(d []byte) error { func checkMeta(d []byte) error {
if d[0] != 0 { if len(d) == 0 || d[0] != 0 || binary.BigEndian.Uint16(d[2:headSize]) != uint16(len(d[headSize:])) {
return errNoHeader return errInvalidMeta
} else if d[0] == 0 && binary.BigEndian.Uint16(d[2:headSize]) != uint16(len(d[headSize:])) {
return errInvalidHeader
} }
return nil return nil
} }