@nuintun/qrcode
Version:
A pure JavaScript QRCode encode and decode library.
107 lines (103 loc) • 2.56 kB
JavaScript
/**
* @module QRCode
* @package @nuintun/qrcode
* @license MIT
* @version 5.0.2
* @author nuintun <nuintun@qq.com>
* @description A pure JavaScript QRCode encode and decode library.
* @see https://github.com/nuintun/qrcode#readme
*/
import { toInt32, getBitMask, toBit, getBitOffset } from './utils.js';
/**
* @module BitMatrix
*/
class BitMatrix {
#width;
#height;
#rowSize;
#bits;
constructor(width, height = width) {
const rowSize = Math.ceil(width / 32);
const bitsCapacity = rowSize * height;
this.#width = width;
this.#height = height;
this.#rowSize = rowSize;
this.#bits = new Int32Array(bitsCapacity);
}
#offset(x, y) {
return y * this.#rowSize + toInt32(x / 32);
}
/**
* @property width
* @description The width of the matrix.
*/
get width() {
return this.#width;
}
/**
* @property height
* @description The height of the matrix.
*/
get height() {
return this.#height;
}
/**
* @method set
* @description Set the bit value to 1 of the specified coordinate.
* @param x The x coordinate.
* @param y The y coordinate.
*/
set(x, y) {
this.#bits[this.#offset(x, y)] |= getBitMask(x);
}
/**
* @method get
* @description Get the bit value of the specified coordinate.
* @param x The x coordinate.
* @param y The y coordinate.
*/
get(x, y) {
return toBit(this.#bits[this.#offset(x, y)] >>> getBitOffset(x));
}
flip(x, y) {
if (x != null && y != null) {
this.#bits[this.#offset(x, y)] ^= getBitMask(x);
} else {
const bits = this.#bits;
const { length } = bits;
for (let i = 0; i < length; i++) {
bits[i] = ~bits[i];
}
}
}
/**
* @method clone
* @description Clone the bit matrix.
*/
clone() {
const matrix = new BitMatrix(this.#width, this.#height);
matrix.#bits.set(this.#bits);
return matrix;
}
/**
* @method setRegion
* @description Set the bit value to 1 of the specified region.
* @param left The left coordinate.
* @param top The top coordinate.
* @param width The width to set.
* @param height The height to set.
*/
setRegion(left, top, width, height) {
const bits = this.#bits;
const right = left + width;
const bottom = top + height;
const rowSize = this.#rowSize;
for (let y = top; y < bottom; y++) {
const offset = y * rowSize;
for (let x = left; x < right; x++) {
bits[offset + toInt32(x / 32)] |= getBitMask(x);
}
}
}
}
export { BitMatrix };