nwaku/waku/common/base64.nim
Ivan FB fd6a71cdd7
chore: Bump dependencies for v0.31.0 (#2885)
* bump_dependencies.md: add nim-results dependency
* change imports stew/results to results
* switching to Nim 2.0.8
* waku.nimble: reflect the requirement nim 1.6.0 to 2.0.8
  Adding --mm:refc as nim 2.0 enables a new garbage collector that we're
  not yet ready to support
* adapt waku code to Nim 2.0
* gcsafe adaptations because Nim 2.0 is more strict
2024-07-09 13:14:28 +02:00

37 lines
1.0 KiB
Nim

{.push raises: [].}
import stew/[byteutils, base64], results
type Base64String* = distinct string
proc encode*[T: byte | char](value: openArray[T]): Base64String =
Base64String(encode(Base64Pad, value))
proc encode*(value: string): Base64String =
encode(toBytes(value))
proc decode[T: byte | char](
btype: typedesc[Base64Types], instr: openArray[T]
): Result[seq[byte], string] =
## Decode BASE64 string ``instr`` and return sequence of bytes as result.
if len(instr) == 0:
return ok(newSeq[byte]())
var bufferLen = decodedLength(btype, len(instr))
var buffer = newSeq[byte](bufferLen)
if decode(btype, instr, buffer, bufferLen) != Base64Status.Success:
return err("Incorrect base64 string")
buffer.setLen(bufferLen)
ok(buffer)
proc decode*(t: Base64String): Result[seq[byte], string] =
decode(Base64Pad, string(t))
proc `$`*(t: Base64String): string {.inline.} =
string(t)
proc `==`*(lhs: Base64String | string, rhs: Base64String | string): bool {.inline.} =
string(lhs) == string(rhs)