Skip to content

Instantly share code, notes, and snippets.

@treeform
Last active January 7, 2020 17:10
Show Gist options
  • Select an option

  • Save treeform/b2a8cf963d98a579272cff1150d731a3 to your computer and use it in GitHub Desktop.

Select an option

Save treeform/b2a8cf963d98a579272cff1150d731a3 to your computer and use it in GitHub Desktop.
const
cbWebSafe64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
proc encodeWebSafeNoPadding*(s: string): string =
## encodes `s` into web safe base64 representation.
proc encodeSize(size: int): int =
return (size * 4 div 3) + 6
result.setLen(encodeSize(s.len))
var
inputIndex = 0
outputIndex = 0
inputEnds = s.len - s.len mod 3
n: uint32
b: uint32
template inputByte(exp: untyped) =
b = uint32(s[inputIndex])
n = exp
inc inputIndex
template outputChar(x: untyped) =
result[outputIndex] = cbWebSafe64[x and 63]
inc outputIndex
while inputIndex != inputEnds:
inputByte(b shl 16)
inputByte(n or b shl 8)
inputByte(n or b shl 0)
outputChar(n shr 18)
outputChar(n shr 12)
outputChar(n shr 6)
outputChar(n shr 0)
var padding = s.len mod 3
if padding == 1:
inputByte(b shl 16)
outputChar(n shr 18)
outputChar(n shr 12)
elif padding == 2:
inputByte(b shl 16)
inputByte(n or b shl 8)
outputChar(n shr 18)
outputChar(n shr 12)
outputChar(n shr 6)
result.setLen(outputIndex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment