Skip to content

Commit

Permalink
New: Sequentially serialize fields ordered by id, as of the spec.
Browse files Browse the repository at this point in the history
  • Loading branch information
dcodeIO committed Mar 9, 2017
1 parent 3ead13e commit c1ca65d
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,16 @@ function encoder(mtype) {
("w=Writer.create()");

var i, ref;
for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
var field = mtype._fieldsArray[i].resolve();

// "when a message is serialized its known fields should be written sequentially by field number"
var sortedFields = /* initializes */ mtype.fieldsArray.slice();
sortedFields.sort(function(a, b) {
return a.id - b.id;
});

for (var i = 0; i < sortedFields.length; ++i) {
var field = sortedFields[i].resolve(),
index = mtype._fieldsArray.indexOf(field);
if (field.partOf) // see below for oneofs
continue;
var type = field.resolvedType instanceof Enum ? "uint32" : field.type,
Expand All @@ -47,7 +55,7 @@ function encoder(mtype) {
("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)
("w.uint32(%d).fork().uint32(%d).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
if (wireType === undefined) gen
("types[%d].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", i, ref); // can't be groups
("types[%d].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups
else gen
(".uint32(%d).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
gen
Expand All @@ -73,7 +81,7 @@ function encoder(mtype) {
("if(%s!==undefined&&m.hasOwnProperty(%j)){", ref, field.name)
("for(var i=0;i<%s.length;++i)", ref);
if (wireType === undefined)
genTypePartial(gen, field, i, ref + "[i]");
genTypePartial(gen, field, index, ref + "[i]");
else gen
("w.uint32(%d).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
gen
Expand All @@ -95,7 +103,7 @@ function encoder(mtype) {
}

if (wireType === undefined)
genTypePartial(gen, field, i, ref);
genTypePartial(gen, field, index, ref);
else gen
("w.uint32(%d).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);

Expand Down

0 comments on commit c1ca65d

Please sign in to comment.