hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

base64.ha (1191B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 // bcrypt uses a crappy variant of base64 with its own special alphabet and no
      5 // padding. This file glues encoding::base64 to the bcrypt semantics.
      6 use encoding::base64;
      7 use errors;
      8 use io;
      9 use memio;
     10 
     11 const alpha: str = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
     12 const b64encoding: base64::encoding = base64::encoding { ... };
     13 
     14 @init fn init() void = {
     15 	base64::encoding_init(&b64encoding, alpha);
     16 };
     17 
     18 // Encodes a slice in the bcrypt base64 style, returning a new slice. The caller
     19 // must free the return value.
     20 fn b64_encode(src: []u8) []u8 = {
     21 	let sink = memio::dynamic();
     22 	base64::encode(&sink, &b64encoding, src)!;
     23 	let buf = memio::buffer(&sink);
     24 	let i = len(buf);
     25 	for (i > 0 && buf[i - 1] == '='; i -= 1) void;
     26 	return buf[..i];
     27 };
     28 
     29 // Decodes a slice in the bcrypt base64 style, returning a new slice. The
     30 // caller must free the return value.
     31 fn b64_decode(src: []u8) ([]u8 | errors::invalid) = {
     32 	let src = alloc(src...);
     33 	defer free(src);
     34 	for (let neq = 4 - len(src) % 4; neq > 0; neq -= 1) {
     35 		append(src, '=');
     36 	};
     37 	return base64::decodeslice(&b64encoding, src);
     38 };