jpack v0.0.1
Jpack is on its very early stage, it's not ready for production. Don't make PR for it, only issue will be resolved.
Overview
Jpack should be language neutral, extendable and fast. And it should support event IE6. It is based on the subset of json-schema.
Terms
JsonType
Same as the json.org spec.
It represents one of these types: String, Number, Boolean, Object, Array or null.
SimpleValue
It represents one of these types: String, Number, Boolean or null.
SimpleArray
It's an array that contains only SimpleValue or SimpleArray.
Such as [1, 'str', [true, null]] is a SimpleArray, but [1, {a: true}] isn't.
SimpleType
It is an SimpleValue or SimpleArray.
Pack Process
SerializabletoSimpleTypeSuch as
10to10or{ a: 1, b: { d: 3, e: 'test' }, c: 2 }to[1, [3, 'test'], 2].SimpleTypetoSpackSuch as
[1, [3, 'test'], 2]to[1|[3|{test}]].
Spack Encoding
Convert SimpleType into a plain string. Spack is simpler and faster than JSON.
The result string will be more compact and smaller than JSON. Thus it's not human
readable.
Null
\0
Boolean
trueto\1falseto\2
String:
- string sign:
\3
Array
[to\4]to\5,to\6
Such as: [1, 2, 3] to \41\62\63\5.
Number:
Number will be convert to base 119.
- minus sign:
\7 - decimal point:
\8 - digit:
\9~\127
Spack won't support something like 10E+10.
Hash Sum
Hash sum of the schema will be placed before the pack:
| 1 | 2 | ... | | hash | pack |
The hash is 16bit
It will make sure the decoding schema is on the right version.
API
genSchema(val)
Generate simple schema from a sample object. Use it if you feel boring to craft a schema by hand.
param:
val{ JsonType }return: { JsonType }
pack(val, schema)
Serialize anything to a data pack.
param:
val{ JsonType }param:
schema{ JsonType }return: { ArrayBuffer }
unpack(data, schema)
Deserialize the data pack to the origin value.
param:
data{ ArrayBuffer }param:
schema{ JsonType }return: { JsonType }
types
Use it to extend the data type that jpack supports. By default it implements the
Datetype.type: { Object }
Each type should implement two functions. One is
serialize:(val) -> SimpleType. Another one isparse:(val) -> any.example:
This will let jpack support custom type
Size.var Size = function Size (w, h) { this.w = w this.h = h } Size.prototype.area = function () { return this.w * this.h } jpack.types['Size'] = { serialize: function (s) { return [s.w, s.h] }, parse: function (s) { return new Size(s[0], s[1]) } } console.log(Size.name) // => "Size" var obj = { 'a': new Size(1, 2) } var schema = jpack.genSchema(obj) jpack.pack(obj, schema)
11 years ago