a collection of lightweight TypeScript packages for AT Protocol, the protocol powering Bluesky
atproto bluesky typescript npm
101
fork

Configure Feed

Select the types of activity you want to include in your feed.

refactor(tid): inline s32 decode directly

Mary 060c7cea da379ce9

+24 -16
+4
packages/utilities/tid/lib/index.test.ts
··· 49 49 clockid: 281, 50 50 }); 51 51 }); 52 + 53 + it('throws on invalid code points', () => { 54 + expect(() => TID.parse('3kztrqxakokc💩')).toThrow('invalid TID'); 55 + }); 52 56 }); 53 57 54 58 describe('validate', () => {
+19 -4
packages/utilities/tid/lib/index.ts
··· 2 2 3 3 import { random } from '#platform/random'; 4 4 5 - import { S32_2CHAR_TABLE, s32decode, s32encode } from './s32.ts'; 5 + import { S32_2CHAR_TABLE, S32_DECODE_TABLE, s32encode } from './s32.ts'; 6 6 7 7 let lastTimestamp = 0; 8 8 let lastCurrentTime = 0; ··· 55 55 * Parses a TID, throws on invalid strings. 56 56 */ 57 57 export const parse = (tid: string): { timestamp: number; clockid: number } => { 58 - if (!validate(tid)) { 58 + if (tid.length !== 13) { 59 59 throw new Error(`invalid TID`); 60 60 } 61 61 62 - const timestamp = s32decode(tid, 0, 11); 63 - const clockid = s32decode(tid, 11, 2); 62 + let timestamp = 0; 63 + let clockid = 0; 64 + 65 + for (let idx = 0; idx < 13; idx++) { 66 + const code = tid.charCodeAt(idx); 67 + const value = code < S32_DECODE_TABLE.length ? S32_DECODE_TABLE[code]! : -1; 68 + 69 + if (value < 0 || (idx === 0 && value > 15)) { 70 + throw new Error(`invalid TID`); 71 + } 72 + 73 + if (idx < 11) { 74 + timestamp = timestamp * 32 + value; 75 + } else { 76 + clockid = clockid * 32 + value; 77 + } 78 + } 64 79 65 80 return { timestamp, clockid }; 66 81 };
+1 -12
packages/utilities/tid/lib/s32.ts
··· 1 1 const S32_CHAR = '234567abcdefghijklmnopqrstuvwxyz'; 2 2 3 - const S32_DECODE_TABLE = /*#__PURE__*/ (() => { 3 + export const S32_DECODE_TABLE = /*#__PURE__*/ (() => { 4 4 const table = new Int16Array(123); 5 5 table.fill(-1); 6 6 ··· 35 35 36 36 return s; 37 37 }; 38 - 39 - export const s32decode = (s: string, offset: number, length: number): number => { 40 - let i = 0; 41 - const end = offset + length; 42 - 43 - for (let idx = offset; idx < end; idx++) { 44 - i = i * 32 + S32_DECODE_TABLE[s.charCodeAt(idx)]!; 45 - } 46 - 47 - return i; 48 - };