aboutsummaryrefslogtreecommitdiff
path: root/src/serialization.ts
blob: 4289b3661881edb67f7e3a9df1e3c4a8a9faa24e (plain)
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
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)
}