aboutsummaryrefslogtreecommitdiff
path: root/src/serialization.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/serialization.ts')
-rw-r--r--src/serialization.ts44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/serialization.ts b/src/serialization.ts
new file mode 100644
index 0000000..4289b36
--- /dev/null
+++ b/src/serialization.ts
@@ -0,0 +1,44 @@
+import * as Base from 'lib/base'
+import * as State from 'state'
+import * as Utils from 'serialization/utils'
+import * as V0 from 'serialization/v0'
+
+// Encoding
+
+const lastVersion = 0 // max is 62
+
+export function encode(s: State.State): string {
+ if (s.length == 0) {
+ return ''
+ } else {
+ const version = Base.encode(BigInt(lastVersion), Base.b62)
+ const xs = V0.encode(s).map(binaryToBase62).join('-')
+ return `${version}${xs}`
+ }
+}
+
+function binaryToBase62(str: string): string {
+ // Prepend 1 so that we don’t loose leading 0s
+ return Base.encode(Base.decode('1' + str, Base.b2), Base.b62)
+}
+
+// Decoding
+
+export function decode(encoded: string): State.State {
+ if (encoded == '') {
+ return []
+ } else {
+ const version = Number(Base.decode(encoded.slice(0, 1), Base.b62))
+ if (version == 0) return V0.decode(encoded.slice(1).split('-').map(base62ToBinary))
+ else {
+ console.error(`Unknown decoder version ${version} in order to decode state.`)
+ return []
+ }
+ }
+}
+
+function base62ToBinary(str: string): string {
+ // Remove prepended 1
+ return Base.encode(Base.decode(str, Base.b62), Base.b2).slice(1)
+}
+