String vs CString

207 views
Skip to first unread message

Kohányi Róbert

unread,
Oct 19, 2011, 12:16:31 PM10/19/11
to BSON
In the specification string is defined as follows:
string ::= int32 (byte*) "\x00"
cstring ::= (byte*) "\x00"

I can understand why cstring is defined this way, however I can't see
the advantages of the trailing "\x00" in string's definition.

What is the use-case for this? Why isn't sufficient to define it as
'string ::= int32 (byte*)'? Or am I overlooking something? :)

Thanks for the answers!

Regards,
Kohányi Róbert

Justin Dearing

unread,
Oct 19, 2011, 9:48:16 PM10/19/11
to bs...@googlegroups.com

I think you should ask this question on a C++ list.

Juan Batiz-Benet

unread,
Oct 19, 2011, 9:50:47 PM10/19/11
to bs...@googlegroups.com
I don't know the designers' reasoning directly. However, I'd say that BSON's main goal isn't compactness, but rather performance. Here, the pascal strings (length prefixed) offer significant performance gains for traversing documents, and keeping the extra nulls allows those strings to be used directly in c functions without copying them to another buffer. 

Also, the nulls protect against buffer-overflow bugs. An inexperienced (or very tired) programmer could end up assigning: 

char *str = &(string's byte*) 

without bothering to copy to a larger buffer, properly null terminated, and then pass str to some c function expecting that null.

Kohányi Róbert

unread,
Oct 20, 2011, 2:15:04 AM10/20/11
to BSON
> keeping the extra nulls allows those strings to be used directly in c functions without copying them to another buffer

Thank you! This is exactly what I was looking for. I'm knowledgeable
only in Java and Python, so this didn't popped to my mind. Also never
heard of "Pascal strings" before (although I've learned about Pascal
in elementary school). Thanks again!

Dwight Merriman

unread,
Oct 20, 2011, 2:20:13 AM10/20/11
to bs...@googlegroups.com
right that was the original thinking
Reply all
Reply to author
Forward
0 new messages