From 7986c19178a4d217ecff436ccaf79a0ff11adf88 Mon Sep 17 00:00:00 2001 From: Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com> Date: Mon, 7 Nov 2022 15:24:20 +0300 Subject: add ReadStringLen(length int) func --- bitreader.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/bitreader.go b/bitreader.go index d3cc71f..d42b8e6 100644 --- a/bitreader.go +++ b/bitreader.go @@ -125,6 +125,13 @@ func (reader *ReaderType) TryReadString() string { return text } +// TryReadStringLen is a wrapper function that returns the string +// that is read until the given length is reached or it is null-terminated. +func (reader *ReaderType) TryReadStringLen(length int) string { + text, _ := reader.ReadStringLen(length) + return text +} + // SkipBits is a function that increases Reader index // based on given input bits number. // @@ -183,6 +190,28 @@ func (reader *ReaderType) ReadString() (string, error) { return out, nil } +// ReadStringLen is a function that reads every byte +// until the given length, or it is null-terminated (the byte is 0). +// Returns the string that is read until the lenth or null-termination. +// It will skip the remaining bytes if it is null-terminated. +// +// Returns an error if there are no remaining bits. +func (reader *ReaderType) ReadStringLen(length int) (string, error) { + var out string + for i := 0; i < length; i++ { + value, err := reader.ReadBytes(1) + if err != nil { + return out, err + } + if value == 0 { + reader.SkipBytes(length - 1 - i) + 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