Created
August 6, 2021 08:05
-
-
Save alovak/2ebd064c088e3496db0cd8d073ebdd4b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package network | |
import ( | |
"bytes" | |
"encoding/binary" | |
"fmt" | |
"io" | |
"math" | |
) | |
type Binary7Bytes struct { | |
Len uint16 | |
} | |
func NewBinary7BytesHeader() *Binary2Bytes { | |
return &Binary2Bytes{} | |
} | |
func (h *Binary7Bytes) SetLength(length int) error { | |
if length > math.MaxUint16 { | |
return fmt.Errorf("length %d exceeds max length for 2 bytes header %d", length, math.MaxUint16) | |
} | |
h.Len = uint16(length) | |
return nil | |
} | |
func (h *Binary7Bytes) Length() int { | |
return int(h.Len) | |
} | |
func (h *Binary7Bytes) WriteTo(w io.Writer) (int, error) { | |
err := binary.Write(w, binary.BigEndian, h.Len) | |
if err != nil { | |
return 0, fmt.Errorf("wrigint uint16 into writer: %v", err) | |
} | |
return binary.Size(h.Len), nil | |
} | |
func (h *Binary7Bytes) ReadFrom(r io.Reader) (int, error) { | |
header := make([]byte, 7) | |
n, err := io.ReadFull(r, header) | |
if err != nil { | |
return n, fmt.Errorf("reading from reader: %v", err) | |
} | |
reader := bytes.NewReader(header) | |
err = binary.Read(reader, binary.BigEndian, &h.Len) | |
if err != nil { | |
return 0, fmt.Errorf("reading uint16 from reader: %v", err) | |
} | |
return binary.Size(h.Len), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment