forked from ccorcos/tuple-database
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcodec.ts
194 lines (178 loc) · 4.97 KB
/
codec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// This codec is should create a component-wise lexicographically sortable array.
import * as elen from "elen"
import { invert, sortBy } from "remeda"
import { isPlainObject } from "./isPlainObject"
import { Tuple, Value } from "../storage/types"
import { compare } from "./compare"
import { UnreachableError } from "./Unreachable"
export type EncodingOptions = {
delimiter?: string
escape?: string
disallow?: string[]
}
// null < object < array < number < string < boolean
export const encodingByte = {
null: "b",
object: "c",
array: "d",
number: "e",
string: "f",
boolean: "g",
} as const
export type EncodingType = keyof typeof encodingByte
export const encodingRank = new Map<EncodingType, number>(
sortBy(Object.entries(encodingByte), ([key, value]) => value).map(
([key], i) => [key as EncodingType, i]
)
)
export function encodeValue(value: Value, options?: EncodingOptions): string {
if (value === null) {
return encodingByte.null
}
if (value === true || value === false) {
return encodingByte.boolean + value
}
if (typeof value === "string") {
for (const disallowed of options?.disallow ?? []) {
if (value.includes(disallowed)) {
throw new Error(`Disallowed character found: ${disallowed}.`)
}
}
return encodingByte.string + value
}
if (typeof value === "number") {
return encodingByte.number + elen.encode(value)
}
if (Array.isArray(value)) {
return encodingByte.array + encodeTuple(value, options)
}
if (typeof value === "object") {
return encodingByte.object + encodeObjectValue(value, options)
}
throw new UnreachableError(value, "Unknown value type")
}
export function encodingTypeOf(value: Value): EncodingType {
if (value === null) {
return "null"
}
if (value === true || value === false) {
return "boolean"
}
if (typeof value === "string") {
return "string"
}
if (typeof value === "number") {
return "number"
}
if (Array.isArray(value)) {
return "array"
}
if (typeof value === "object") {
return "object"
}
throw new UnreachableError(value, "Unknown value type")
}
const decodeType = invert(encodingByte) as {
[key: string]: keyof typeof encodingByte
}
export function decodeValue(str: string, options?: EncodingOptions): Value {
const encoding: EncodingType = decodeType[str[0]]
const rest = str.slice(1)
if (encoding === "null") {
return null
}
if (encoding === "boolean") {
return JSON.parse(rest)
}
if (encoding === "string") {
return rest
}
if (encoding === "number") {
return elen.decode(rest)
}
if (encoding === "array") {
return decodeTuple(rest, options)
}
if (encoding === "object") {
return decodeObjectValue(rest, options)
}
throw new UnreachableError(encoding, "Invalid encoding byte")
}
export function encodeTuple(tuple: Tuple, options?: EncodingOptions) {
const delimiter = options?.delimiter ?? "\x00"
const escape = options?.escape ?? "\x01"
const reEscapeByte = new RegExp(`${escape}`, "g")
const reDelimiterByte = new RegExp(`${delimiter}`, "g")
return tuple
.map((value, i) => {
const encoded = encodeValue(value, options)
return (
encoded
// B -> BB or \ -> \\
.replace(reEscapeByte, escape + escape)
// A -> BA or x -> \x
.replace(reDelimiterByte, escape + delimiter) + delimiter
)
})
.join("")
}
export function decodeTuple(str: string, options?: EncodingOptions) {
if (str === "") {
return []
}
const delimiter = options?.delimiter ?? "\x00"
const escape = options?.escape ?? "\x01"
// Capture all of the escaped BB and BA pairs and wait
// til we find an exposed A.
const matcher = new RegExp(
`(${escape}(${escape}|${delimiter})|${delimiter})`,
"g"
)
const reEncodedEscape = new RegExp(escape + escape, "g")
const reEncodedDelimiter = new RegExp(escape + delimiter, "g")
const tuple: Tuple = []
let start = 0
while (true) {
const match = matcher.exec(str)
if (match === null) {
return tuple
}
if (match[0][0] === escape) {
// If we match a escape+escape or escape+delimiter then keep going.
continue
}
const end = match.index
const escaped = str.slice(start, end)
if (typeof escaped !== "string") {
console.log(escaped)
}
const unescaped = escaped
// BB -> B
.replace(reEncodedEscape, escape)
// BA -> A
.replace(reEncodedDelimiter, delimiter)
const decoded = decodeValue(unescaped, options)
tuple.push(decoded)
// Skip over the \x00.
start = end + 1
}
}
function encodeObjectValue(obj: object, options?: EncodingOptions) {
if (!isPlainObject(obj)) {
throw new Error("Cannot serialize this object.")
}
const entries = Object.entries(obj)
.sort(([k1], [k2]) => compare(k1, k2))
// We allow undefined values in objects, but we want to strip them out before
// serializing.
.filter(([key, value]) => value !== undefined)
return encodeTuple(entries as Tuple, options)
}
function decodeObjectValue(str: string, options?: EncodingOptions) {
const entries = decodeTuple(str, options) as Array<[string, Value]>
const obj = {}
for (const [key, value] of entries) {
obj[key] = value
}
return obj
}