packString method
Pack String or null
.
Depending on whether your distinguish empty String from null
or not:
- Empty and
null
is same: consider pack empty String tonull
, to save 1 byte on a wire.
p.packStringEmptyIsNull(s) //or
p.packString(s.isEmpty ? null : s) //or
s.isEmpty ? p.packNull() : p.packString(s)
- Empty and
null
distinguishable: no action required just savep.packString(s)
. Throws ArgumentError if String.length exceed (2^32)-1.
Implementation
void packString(String? v) {
// max 4 byte str header + 1 control byte
if (_buf.length - _offset < 5) _nextBuf();
if (v == null) {
_d.setUint8(_offset++, 0xc0);
return;
}
final encoded = _strCodec.encode(v);
final length = encoded.length;
if (length <= 31) {
_d.setUint8(_offset++, 0xA0 | length);
} else if (length <= 0xFF) {
_d.setUint8(_offset++, 0xd9);
_d.setUint8(_offset++, length);
} else if (length <= 0xFFFF) {
_d.setUint8(_offset++, 0xda);
_d.setUint16(_offset, length);
_offset += 2;
} else if (length <= 0xFFFFFFFF) {
_d.setUint8(_offset++, 0xdb);
_d.setUint32(_offset, length);
_offset += 4;
} else {
throw ArgumentError('Max String length is 0xFFFFFFFF');
}
_putBytes(encoded);
}