base64-bit
This library provides a base64 decoder and encoder for you to manipulate bits in nanoseconds.
Features
- Decoder allows you to pop bits from the base64 string.
- Encoder allows you to push bits to form base64 string.
- Highly optimized, bits manipulation can be done in nanoseconds.
- No dependencies.
- TypeScript supported.
- Well-tested.
- Browser compatability: IE6+.
Usage
CommonJS
const { Decoder, Encoder } = require('base64-bit');
ES Module
import { Decoder, Encoder } from 'base64-bit';
Browser
<script src="https://cdn.jsdelivr.net/npm/base64-bit/dist/index.min.js"></script> // From CDN
<script src="/path/to/node_modules/base64-bit/dist/index.min.js"></script> // From node_modules
const decoder = Base64.Decoder();
const encoder = Base64.Encoder();
APIs
Decoder
Decodes base64 encoded string to bit stream.
const decoder = Decoder();
decoder.from('VGhncy4=');
decoder.pop(8);
decoder.pop(32);
decoder.pop(2);
decoder.pop(1);
decoder.offset(6);
decoder.pop(6);
decoder.from(base64)
Loads a base64 encoded string to the decoder, and replaces the existing one.
Remark: Since base64 is a 6-bit encoding, if the number of bits encoded is not a multiple of 6, 0s are padded at the end of the bit stream. It is very likely that the total bits you pushed is less than base64.length * 6
. Therefore, you are recommended to push a preserved bits to indicate the end of the stream, otherwise you may pop unnecessary bits.
decoder.pop(k = 8)
Extracts the next k bits and converts it to decimal, k should be at most 32.
decoder.offset(k = 0)
Resets the bit position by skipping the first k bits.
Encoder
Encodes bit stream to base64 format.
const encoder = Encoder();
encoder.push(46, 8);
encoder.push(46, 16);
encoder.push(1, 3);
encoder.push(0, 1);
encoder.push(-1, 8);
encoder.push(255, 4);
const encoded = encoder.flush();
encoder.push(binary, k = 8)
Converts an integer to k-bit unsigned binary, and appends it to the end of the bit stream. k should be at most 32.
encoder.flush()
Encodes the bit stream to base64 format, and resets the encoder.
Performance
npm run benchmark
Operation | Benchmark (ops/sec) | Time (ns/ops) |
---|
Push 1 bit | 105,069,508 | 9.52 |
Pop 1 bit | 62,699,807 | 15.95 |
Push 8 bits | 64,279,504 | 15.56 |
Pop 8 bits | 40,743,087 | 24.54 |
Push 16 bits | 36,436,695 | 27.44 |
Pop 16 bits | 30,037,712 | 33.29 |
Push 32 bits | 17,044,324 | 58.67 |
Pop 32 bits | 15,764,883 | 63.43 |
Build
The following command creates index.cjs
, index.mjs
and index.min.js
in ./dist
directory.
npm run build
Test
The following command runs all tests in ./tests
directory.
npm run test
Release
1.1.0
Optimize the implementation to achieve around 2x performance improvement.
1.3.0
Support ES module.