@loaders.gl/wkt
Version:
Loader and Writer for the WKT (Well Known Text) Format
56 lines (55 loc) • 1.75 kB
JavaScript
// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { WKBLoader } from "./wkb-loader.js";
import { VERSION } from "./lib/utils/version.js";
import { decodeHex } from "./lib/utils/hex-transcoder.js";
/**
* Worker loader for Hex-encoded WKB (Well-Known Binary)
*/
export const HexWKBLoader = {
dataType: null,
batchType: null,
name: 'Hexadecimal WKB',
id: 'wkb',
module: 'wkt',
version: VERSION,
worker: true,
category: 'geometry',
extensions: ['wkb'],
mimeTypes: [],
options: WKBLoader.options,
text: true,
testText: isHexWKB,
// TODO - encoding here seems wasteful - extend hex transcoder?
parse: async (arrayBuffer) => parseHexWKB(new TextDecoder().decode(arrayBuffer)),
parseTextSync: parseHexWKB
};
function parseHexWKB(text, options) {
const uint8Array = decodeHex(text);
const binaryGeometry = WKBLoader.parseSync?.(uint8Array.buffer, options);
// @ts-expect-error
return binaryGeometry;
}
/**
* Check if string is a valid Well-known binary (WKB) in HEX format
* https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry
*
* @param str input string
* @returns true if string is a valid WKB in HEX format
*/
export function isHexWKB(string) {
if (!string) {
return false;
}
// check if the length of the string is even and is at least 10 characters long
if (string.length < 10 || string.length % 2 !== 0) {
return false;
}
// check if first two characters are 00 or 01
if (!string.startsWith('00') && !string.startsWith('01')) {
return false;
}
// check if the rest of the string is a valid hex
return /^[0-9a-fA-F]+$/.test(string.slice(2));
}