Object serialization: Difference between revisions

m
Fixed lang tags.
m (Fixed lang tags.)
Line 165:
Serialization in '''ALGOL 68''' is achieved through a technique called
''straightening''.
<lang algol68>MODE ENTITY = STRUCT([6]CHAR name, INT creation);
<pre>
MODE ENTITY = STRUCT([6]CHAR name, INT creation);
FORMAT entity repr = $"Name: "g", Created:"g$;
MODE PERSON = STRUCT(ENTITY entity, STRING email);
Line 194 ⟶ 193:
printf((person repr, i1, $l$));
printf((entity repr, i2, $l$))</prelang>
FLEXible length arrays (including STRINGs), and tagged-UNION
types are problematic as the lengths of the arrays, and the ''tag'' of the
Line 201 ⟶ 200:
the type (''mode'') of the objectis note stored, but compiled into the
code itself.
Output:<prelang algol68>Cletus
Cletus
Entity
Serialized...
Unserialized...
Name: Cletus, Created: +20080808, Email: test+1@localhost.localdomain
Name: Entity, Created: +20111111</prelang>
{{omit from|AutoHotkey}}
 
Line 281 ⟶ 279:
Run "pbcompiler test.proto" to generate the serializable code. It should generate a D code file named test.d.
In your main file, use the following code:
<lang d>import test1;
import test1;
import std.stdio;
import std.file;
Line 316 ⟶ 313:
writefln("Output data:");
base.print;
}</lang>
}
</lang>
 
=={{header|E}}==
Line 323 ⟶ 319:
(Inheritance, while supported by various features and patterns, is not a preferred design component in [[E]]; nor are simple record data structures.)
 
<lang e>def makeEvent(time :int) {
return def event {
to __printOn(out) { out.print(`@@$time`) }
to __optUncall() { return [makeEvent, "run", [time]] }
to getTime() { return time }
}
}
 
def makeArrival(time :int, what :any, position :int) {
return def arrival extends makeEvent(time) {
to __printOn(out) {
out.print(`$what to $position $super`)
}
to __optUncall() {
return [makeArrival, "run", [time, what, position]]
}
to getWhat() { return what }
to getPosition() { return position }
}
}</lang>
}
 
After defining our data types, we can prepare to serialize them.
 
<lang e>def surgeon := <import:org.erights.e.elib.serial.makeSurgeon>().diverge()
surgeon.addExit(makeEvent, "makeEvent")
surgeon.addExit(makeArrival, "makeArrival")</lang>
 
The 'exits' of the surgeon (so called because it cuts and joins object subgraphs) specify the points at which serialization should stop, instead replacing references to the objects with the specified names. On unserialization, the names are looked up and replaced with the corresponding objects. (The surgeon provides default exits for such things as <tt>false</tt>, <tt>true</tt>, <tt>null</tt>, and the list constructor.)
<lang e>def objs := [makeEvent(timer.now()),
makeArrival(timer.now(), "Smith", 7)]
 
stdout.println(objs)
<file:objects.dat>.setBytes(surgeon.serialize(objs))
stdout.println(surgeon.unserialize(<file:objects.dat>.getBytes()))</lang>
 
=={{header|Java}}==
Anonymous user