@@ -177,8 +177,8 @@ export class Parser {
177177 smartBufferSize : number ;
178178
179179 constructor ( opts ?: any ) {
180- this . smartBufferSize =
181- opts && typeof opts === 'object' && opts . smartBufferSize
180+ this . smartBufferSize =
181+ opts && typeof opts === 'object' && opts . smartBufferSize
182182 ? opts . smartBufferSize
183183 : 256 ;
184184 }
@@ -885,6 +885,15 @@ export class Parser {
885885 }
886886
887887 generateEncode ( ctx : Context ) {
888+ var savVarName = ctx . generateTmpVariable ( ) ;
889+ const varName = ctx . generateVariable ( this . varName ) ;
890+
891+ // Transform with the possibly provided encoder before encoding
892+ if ( this . options . encoder ) {
893+ ctx . pushCode ( `var ${ savVarName } = ${ varName } ` ) ;
894+ this . generateEncoder ( ctx , varName , this . options . encoder ) ;
895+ }
896+
888897 if ( this . type ) {
889898 switch ( this . type ) {
890899 case 'uint8' :
@@ -938,9 +947,10 @@ export class Parser {
938947 this . generateAssert ( ctx ) ;
939948 }
940949
941- const varName = ctx . generateVariable ( this . varName ) ;
942950 if ( this . options . encoder ) {
943- this . generateEncoder ( ctx , varName , this . options . encoder ) ;
951+ // Restore varName after encoder transformation so that next parsers will
952+ // have access to original field value (but not nested ones)
953+ ctx . pushCode ( `${ varName } = ${ savVarName } ;` ) ;
944954 }
945955
946956 return this . generateEncodeNext ( ctx ) ;
@@ -988,7 +998,7 @@ export class Parser {
988998 if ( this . next ) {
989999 ctx = this . next . generateEncode ( ctx ) ;
9901000 }
991-
1001+
9921002 return ctx ;
9931003 }
9941004
@@ -1332,7 +1342,7 @@ export class Parser {
13321342 // and length option)
13331343 if ( length !== undefined ) {
13341344 ctx . pushCode ( `${ maxItems } = ${ maxItems } > ${ length } ? ${ length } : ${ maxItems } ` ) ;
1335- }
1345+ }
13361346
13371347 // Save current encoding smartBuffer and allocate a new one
13381348 const savSmartBuffer = ctx . generateTmpVariable ( ) ;
@@ -1343,7 +1353,7 @@ export class Parser {
13431353 ) ;
13441354
13451355 ctx . pushCode ( `if(${ maxItems } > 0) {` ) ;
1346-
1356+
13471357 ctx . pushCode ( `var ${ itemCounter } = 0;` ) ;
13481358 if (
13491359 typeof this . options . encodeUntil === 'function' ||
0 commit comments