ol
Version:
OpenLayers mapping library
66 lines (57 loc) • 1.76 kB
JavaScript
/**
* @module ol/webgl/LabelsArray
*/
const textEncoder = new TextEncoder();
// the underlying typed array will be resized in increments of this amount of bytes
const chunkSize = 100_000;
/**
* @classdesc
* This class stores text values using typed arrays internally.
* Labels are stored as separate UTF-8 characters in a single Uint8Array.
* The Uint8Array is resized when the capacity exceeds to avoid costly concatenation.
*/
class LabelsArray {
constructor() {
/**
* @private
*/
this.array_ = new Uint8Array(chunkSize);
this.actualSize_ = 0;
/**
* @type {Map<string, Array<number>>}
* @private
*/
this.labelPositionMap_ = new Map();
}
/**
* @param {string} label Label to append to the end of the array
* @return {Array<number>} An array containing 1/ the position of the label in the typed array and 2/ the size of the label in the array
*/
push(label) {
if (label === '') {
return [0, 0];
}
if (this.labelPositionMap_.has(label)) {
return /** @type {Array<number>} */ (this.labelPositionMap_.get(label));
}
const encoded = textEncoder.encode(label);
if (this.actualSize_ + encoded.length > this.array_.length) {
const newArray = new Uint8Array(this.array_.length + chunkSize);
newArray.set(this.array_);
this.array_ = newArray;
}
const position = this.actualSize_;
this.array_.set(encoded, position);
this.actualSize_ += encoded.length;
const result = [position, encoded.length];
this.labelPositionMap_.set(label, result);
return result;
}
/**
* @return {Uint8Array} Typed array containing the encoded labels.
*/
getArray() {
return this.array_;
}
}
export default LabelsArray;