1+ const { compileEncoder, compileDecoder } = require ( './Compiler' ) ;
2+
13/**
24 * @class
35 * Base class for any transcodable type definition.
46 */
57class TranscodableType {
68 constructor ( ) {
7- this . last_bytes_encoded = - 1 ;
8- this . last_bytes_decoded = - 1 ;
9+ this . _tmp_encoder_compiled = null ;
10+ this . _tmp_decoder_compiled = null ;
911 }
1012 /**
1113 * Encode an object into a binary representation.
@@ -15,15 +17,41 @@ class TranscodableType {
1517 * @returns {Buffer } The buffer that contains the encoded data. If a new buffer is allocated then the data was written from the begining.
1618 */
1719 encode ( object , buffer , offset ) {
18- throw Error ( 'Called abstract encode' ) ;
20+ if ( ! this . _tmp_encoder_compiled )
21+ this . _tmp_encoder_compiled = compileEncoder ( this ) ;
22+ return this . _tmp_encoder_compiled ( object , buffer , offset ) ;
1923 }
2024 /**
2125 * Decode an object from a binary representation.
2226 * @param {Buffer } buffer The buffer to read from.
2327 * @param {Number } [offset] The offset in buffer to start reading.
2428 */
2529 decode ( buffer , offset ) {
26- throw Error ( 'Called abstract decode' ) ;
30+ if ( ! this . _tmp_decoder_compiled )
31+ this . _tmp_decoder_compiled = compileDecoder ( this ) ;
32+ return this . _tmp_decoder_compiled ( buffer , offset ) ;
33+ }
34+ /**
35+ * Generate code that encodes the value in variable of name _source\_var_.
36+ * The code is pasted with other generated code in a single function.
37+ * Refer to {@link Compiler.js} for usable local variables.
38+ * @param {String } source_var The variable name to read from.
39+ * @param {function } tmp_var_alloc A function that allocates a unique temporary variable. Returns its name.
40+ * @returns {String } JavaScript code
41+ */
42+ compiledEncoder ( source_var , tmp_var_alloc ) {
43+ throw new Error ( 'Abstract compiledEncoder called' ) ;
44+ }
45+ /**
46+ * Generate code that decodes the local _buffer_ variable at _position_.
47+ * Save the decoded value to _target\_var_ variable.
48+ * Refer to {@link Compiler.js} for usable local variables.
49+ * @param {String } target_var The variable name to save to.
50+ * @param {function } tmp_var_alloc A function that allocates a unique temporary variable. Returns its name.
51+ * @returns {String } JavaScript code
52+ */
53+ compiledDecoder ( target_var , tmp_var_alloc ) {
54+ throw new Error ( 'Abstract compiledDecoder called' ) ;
2755 }
2856}
2957
0 commit comments