MCPcopy Create free account
hub / github.com/Moddable-OpenSource/moddable / encode

Method encode

modules/crypt/etc/ber.js:202–344  ·  view source on GitHub ↗
(arr)

Source from the content-addressed store, hash-verified

200 return n;
201 }
202 static encode(arr) {
203 const b = new BER;
204 const tag = arr[0];
205 const val = arr[1];
206 b.putTag(tag);
207 switch (tag) {
208 case 0x01: // boolean
209 b.putLength(1);
210 b.putc(val ? 1 : 0);
211 break;
212 case 0x02: { // integer
213 let c = new Uint8Array(ArrayBuffer.fromBigInt(val));
214 if (val >= 0) {
215 if (c[0] & 0x80) {
216 b.putLength(c.byteLength + 1);
217 b.putc(0);
218 }
219 else
220 b.putLength(c.byteLength);
221 c = c.buffer;
222 }
223 else {
224 for (let i = 0; i < c.length; i++) // could use Logical.not
225 c[i] = ~c[i];
226 c = BigInt.fromArrayBuffer(c.buffer);
227 c = ArrayBuffer.fromBigInt(c + 1n);
228 if ((new Uint8Array(c)[0]) & 0x80)
229 b.putLength(c.byteLength);
230 else {
231 b.putLength(c.byteLength + 1);
232 b.putc(0xff);
233 }
234 }
235 b.putChunk(c);
236 } break;
237 case 0x03: { // bit string
238 b.putLength(val.byteLength + 1);
239 let pad = val.byteLength * 8 - arr[2];
240 b.putc(pad);
241 if (pad != 0) {
242 for (let i = 0; i < val.byteLength; i++)
243 b.putc(val[i] << pad);
244 }
245 else
246 b.putChunk(val);
247 } break;
248 case 0x04: // octet string
249 b.putLength(val.byteLength);
250 b.putChunk(val);
251 break;
252 case 0x05: // null
253 b.putLength(0);
254 break;
255 case 0x06: { // object identifier
256 let t = new BER();
257 t.putc(val[0] * 40 + (val.length < 2 ? 0 : val[1]));
258 for (let i = 2; i < val.length; i++) {
259 let x = val[i];

Callers

nothing calls this directly

Calls 10

putTagMethod · 0.95
putLengthMethod · 0.95
putcMethod · 0.95
putChunkMethod · 0.95
getBufferMethod · 0.95
itoaMethod · 0.95
fromBigIntMethod · 0.80
fromStringMethod · 0.80
fromArrayBufferMethod · 0.65
pushMethod · 0.45

Tested by

no test coverage detected