tbase64.nim 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. discard """
  2. output: '''YQ=='''
  3. nimout: '''YQ=='''
  4. """
  5. import base64
  6. import base64
  7. static: echo encode("a")
  8. echo encode("a")
  9. proc main() =
  10. doAssert encode("Hello World") == "SGVsbG8gV29ybGQ="
  11. doAssert encode("leasure.") == "bGVhc3VyZS4="
  12. doAssert encode("easure.") == "ZWFzdXJlLg=="
  13. doAssert encode("asure.") == "YXN1cmUu"
  14. doAssert encode("sure.") == "c3VyZS4="
  15. doAssert encode([1,2,3]) == "AQID"
  16. doAssert encode(['h','e','y']) == "aGV5"
  17. doAssert encode("") == ""
  18. doAssert decode("") == ""
  19. const testInputExpandsTo76 = "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
  20. const testInputExpands = "++++++++++++++++++++++++++++++"
  21. const longText = """Man is distinguished, not only by his reason, but by this
  22. singular passion from other animals, which is a lust of the mind,
  23. that by a perseverance of delight in the continued and indefatigable
  24. generation of knowledge, exceeds the short vehemence of any carnal
  25. pleasure."""
  26. const tests = ["", "abc", "xyz", "man", "leasure.", "sure.", "easure.",
  27. "asure.", longText, testInputExpandsTo76, testInputExpands]
  28. doAssert encodeMIME("foobarbaz", lineLen=4) == "Zm9v\r\nYmFy\r\nYmF6"
  29. doAssert decode("Zm9v\r\nYmFy\r\nYmF6") == "foobarbaz"
  30. for t in items(tests):
  31. doAssert decode(encode(t)) == t
  32. doAssert decode(encodeMIME(t, lineLen=40)) == t
  33. doAssert decode(encodeMIME(t, lineLen=76)) == t
  34. const invalid = "SGVsbG\x008gV29ybGQ="
  35. try:
  36. doAssert decode(invalid) == "will throw error"
  37. except ValueError:
  38. discard
  39. block base64urlSafe:
  40. doAssert encode("c\xf7>", safe = true) == "Y_c-"
  41. doAssert encode("c\xf7>", safe = false) == "Y/c+" # Not a nice URL :(
  42. doAssert decode("Y/c+") == decode("Y_c-")
  43. # Output must not change with safe=true
  44. doAssert encode("Hello World", safe = true) == "SGVsbG8gV29ybGQ="
  45. doAssert encode("leasure.", safe = true) == "bGVhc3VyZS4="
  46. doAssert encode("easure.", safe = true) == "ZWFzdXJlLg=="
  47. doAssert encode("asure.", safe = true) == "YXN1cmUu"
  48. doAssert encode("sure.", safe = true) == "c3VyZS4="
  49. doAssert encode([1,2,3], safe = true) == "AQID"
  50. doAssert encode(['h','e','y'], safe = true) == "aGV5"
  51. doAssert encode("", safe = true) == ""
  52. doAssert encode("the quick brown dog jumps over the lazy fox", safe = true) == "dGhlIHF1aWNrIGJyb3duIGRvZyBqdW1wcyBvdmVyIHRoZSBsYXp5IGZveA=="
  53. main()