Handy BinaryStream extension methods

| | Comments (1)

While working on a particular project of interest to me, I happened to need a few functions which I was rather surprised don't exist on the BinaryStream class: ReadCString and ReadWString. I'm not certain why they don't exist on the BinaryStream already --- I mean, there's a ReadPString on there! So I wrote some handy little extension methods that you're welcome to use.

Function ReadWString(extends bs as BinaryStream) As String
// Read one word at a time until we come to a 0-word.
dim ret as String
dim word as UInt16

do
word = bs.ReadUInt16
ret = ret + Encodings.UTF16.Chr( word )
loop until word = 0

return ret
End Function

Function ReadCString(extends bs as BinaryStream, enc as TextEncoding = nil ) As String
// Read one bytes at a time until we come to a 0-byte.
dim ret as String
dim bytes as UInt8

do
bytes = bs.ReadUInt8

if enc <> nil then
ret = ret + enc.Chr( bytes )
else
ret = ret + Encodings.ASCII.Chr( bytes )
end if
loop until bytes = 0

return ret
End Function

They're pretty straight-forward functions. The one interesting thing to note is that the CString function allows you to use a particular encoding if you happen to know about it, otherwise it simply falls back on ASCII. This is handy if you know your data is in Mac Roman for instance. But if you don't know the encoding, we try a sensible enough default.

1 Comments

One important note: endianness matters for this ReadWString. You have to have LittleEndian set appropriately.

As for why BinaryStream has PString and not WString/CString, that should be obvious: PString is a legacy of REALbasic's origins as a Macintosh product. UCS-2/UTF-16 was barely out in 1997 when REALbasic was released, and CStrings were non-existent on the Mac platform.

Leave a comment

Disclaimer

I'm currently an employee of REAL Software. My blog is mine. The opinions represented in this blog are mine as well and may not represent my employer's opinions. All original material is copyrighted and property of the author.

REALbasic® is a registered trademark of REAL Software, Inc. REAL SQL Server™ and Lingua™ are pending trademarks of REAL Software, Inc. All rights reserved.