Stream Helper Methods in JavaScript
The stream classes provide all of the low-level methods necessary for encoding and decoding Ice types. However, it would be tedious and error-prone to manually encode complex Ice types such as classes, structs, and dictionaries using these low-level functions. For this reason, the Slice compiler generates helper methods for streaming user-defined types.
Sequence
For a Slice sequence named StringSeq
, the Slice compiler generates StringSeqHelper
that provides read
and write
methods:
var v = StringSeqHelper.read(istr); StringSeqHelper.write(ostr, v);
Dictionary
For a Slice dictionary named EmployeeMap
, the Slice compiler generates EmployeeMapHelper
that provides read
and write
methods:
var v = EmployeeMapHelper.read(istr); EmployeeMapHelper.write(ostr, v);
Enumeration
For a Slice enumeration named Color
, the Slice compiler generates the JavaScript class Color
. No additional helper methods are necessary because the stream classes make insertion and extraction of enumerators straightforward:
var e = istr.readEnum(Color); ostr.writeEnum(e);
Structure
For a Slice structure named Point
, the Slice compiler generates the JavaScript class Point
. This class defines "static" read
and write
methods:
var p = Point.read(istr); Point.write(ostr, p);
Class
For a Slice class named Shape
, the Slice compiler generates the JavaScript class Shape
. This class defines "static" read
and write
methods:
var obj = Shape.read(istr); // obj.value holds instance istr.readPendingValues(); Shape.write(ostr, obj.value);
Note that read
returns a wrapper object with a value
member. This member may not be initialized until after readPendingValues
has been called on the stream and all instances have been unmarshaled, at which point obj.value
will either be null
or a reference to an instance.
The generated class also provides methods for handling optional instances:
var optional = Shape.readOptional(istr, tag); istr.readPendingValues(); if(optional.value !== undefined) { Shape.writeOptional(ostr, tag, optional.value); }
Again, the return value of readOptional
is a wrapper whose value
member will eventually be set to undefined
(if the optional instance was not present), null
, or a reference to an instance.