-
Notifications
You must be signed in to change notification settings - Fork 65
tips
Material in this section is largely derived from questions asked by students taking 6.824 and other associated course material.
The str
class implements constant, garbage-collected (reference counted) variable-length strings. The constructor str("xxxx") creates a new str object initialized from the C string "xxxx". The method cstr()
returns a pointer co char that holds the contents of the str
object. Equality with == is defined on str objects, and returns true iff the two strings contain the same bytes. str
objects have an explicit length, so they can contain nulls.
The cstr()
method will not be "confused" by nulls per se but you
probably don't want to call strlen
on it or pass it to printf
.
cstr
returns a pointer to the memory where the actual data is stored
use the len()
method to figure out how long the data is.
You can not modify a str. Don't modify the result of str.cstr()
, since cstr()
returns a pointer to the str's internal storage. (The compiler should warn you if you try to do this.)
strbuf
is a string buffer and can also hold nulls. You can append to a string buffer, for example
str b, c;
strbuf a;
a << b << c; // Concatenates two strings
a << "goodbye!\n"; // Appends a char *.
However, be careful when using string
vs opaque
in XDR defined structs!
XDR strings translate into rpc_str
in :sfslite which subclass str
but
implicitly assume that it can use null as a string terminator (and that the contents
can be printed, e.g. in ASRV_TRACE
).
You can use xdr2str
and str2xdr
to marshal and unmarshal structures defined
in .x
files (and compiled by rpcc
) into str
ings.
You can reuse strbuf's by clearing them as follows:
strbuf b;
b << "hello!";
str hi = b;
b.tosuio ()->clear ();
b << "goodbye!";
str bye = b;
warn << "hi=" << hi << "; bye=" << b << "\n";
This code will print out:
hi=hello!; bye=goodbye!
Arrays can be indexed directly; variable length items (e.g. int<>) can be treated much like the vec class --- you can use x.push_back() to create a new object and then work with x.back() or you can call x.setsize () to set it to a certain length.