Simplify unmarshalling.

This commit is contained in:
Henrik, Sölver
2021-06-09 19:51:48 +02:00
committed by Henrik Sölver
parent 61abe8dbd4
commit 71fcac40f0
17 changed files with 452 additions and 179 deletions

View File

@@ -2,7 +2,10 @@
// SPDX-License-Identifier: BSD-3-Clause
package ipp
import "encoding/binary"
import (
"bufio"
"encoding/binary"
)
// SetOfStrings is the strings attribute
type SetOfStrings struct {
@@ -32,17 +35,37 @@ func (s *SetOfStrings) valueTag() tag {
return s.vTag
}
// func (k *keyWord) unmarshal(byteStream io.Reader) {
// if len(k.values) == 0 {
// var v string
// k.name, v = unmarshalSingleValue(byteStream)
// k.values = append(k.values, v)
// } else {
// var v string
// _, v = unmarshalSingleValue(byteStream)
// k.values = append(k.values, v)
// }
// }
func (s *SetOfStrings) unmarshal(byteStream *bufio.Reader, valueTag tag) error {
var length uint16
s.vTag = valueTag
s.values = make([]string, 0, 1)
binary.Read(byteStream, binary.BigEndian, &length)
name := make([]byte, length)
if length > 0 {
binary.Read(byteStream, binary.BigEndian, name)
}
s.name = string(name)
binary.Read(byteStream, binary.BigEndian, &length)
for length > 0 {
valueBytes := make([]byte, length)
err := binary.Read(byteStream, binary.BigEndian, valueBytes)
if err != nil {
return err
}
s.values = append(s.values, string(valueBytes))
next, err := byteStream.Peek(3)
if err != nil {
break
}
if next[0] != byte(valueTag) || next[1] != 0x00 || next[2] != 0x00 {
break
}
// Remove the value tag with the zero length from the stream
byteStream.Discard(3)
binary.Read(byteStream, binary.BigEndian, &length)
}
return nil
}
func (s *SetOfStrings) marshal() []byte {
l := 5 + len(s.name) + len(s.values[0])
@@ -79,16 +102,3 @@ func (s *SetOfStrings) marshal() []byte {
func (s *SetOfStrings) AddValue(v string) {
s.values = append(s.values, v)
}
func (s *SetOfStrings) size() int {
l := 1 + 2 // The value tag (0x44) + name-length field (2 bytes)
l += len(s.name)
l += 2 // value-length field (2 bytes)
l += len(s.values[0])
// Add all additional values
for _, v := range s.values[1:] {
l += 1 + 4 // The value tag (0x44) + 2 length fields (2 bytes)
l += len(v)
}
return l
}