From 2c6eea0886192a1bc07f564ef26c664b0953b73d Mon Sep 17 00:00:00 2001 From: Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> Date: Mon, 7 Nov 2022 12:11:06 +0300 Subject: add ReadString() function --- bitreader.go | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) (limited to 'bitreader.go') diff --git a/bitreader.go b/bitreader.go index a56aab8..d3cc71f 100644 --- a/bitreader.go +++ b/bitreader.go @@ -118,9 +118,17 @@ func (reader *ReaderType) TryReadFloat64() float64 { return math.Float64frombits(value) } +// TryReadString is a wrapper function that returns the string +// that is read until it is null-terminated. +func (reader *ReaderType) TryReadString() string { + text, _ := reader.ReadString() + return text +} + // SkipBits is a function that increases Reader index -// based on given input bits number. Returns an error -// if there are no remaining bits. +// based on given input bits number. +// +// Returns an error if there are no remaining bits. func (reader *ReaderType) SkipBits(bits int) error { // Read as many raw bytes as we can bytes := bits / 8 @@ -144,8 +152,9 @@ func (reader *ReaderType) SkipBits(bits int) error { } // SkipBytes is a function that increases Reader index -// based on given input bytes number. Returns an error -// if there are no remaining bits. +// based on given input bytes number. +// +// Returns an error if there are no remaining bits. func (reader *ReaderType) SkipBytes(bytes int) error { err := reader.SkipBits(bytes * 8) if err != nil { @@ -154,6 +163,26 @@ func (reader *ReaderType) SkipBytes(bytes int) error { return nil } +// ReadString is a function that reads every byte +// until it is null-terminated (the byte is 0). Returns the +// string that is read until the null-termination. +// +// Returns an error if there are no remaining bits. +func (reader *ReaderType) ReadString() (string, error) { + var out string + for { + value, err := reader.ReadBytes(1) + if err != nil { + return out, err + } + if value == 0 { + break + } + out += string(rune(value)) + } + return out, nil +} + // ReadBits is a function that reads the specified amount of bits // specified in the parameter and returns the value, error // based on the output. It can read up to 64 bits. Returns the read -- cgit v1.2.3