Skip to content

Commit

Permalink
stdlib: add Base64 encoder
Browse files Browse the repository at this point in the history
  • Loading branch information
soc committed Jan 20, 2024
1 parent 92ae689 commit 9634903
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 1 deletion.
18 changes: 18 additions & 0 deletions dora/stdlib/base64.dora
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use std.string.StringBuffer;

let CHARS: String = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";

@pub
fun encode(src: Array[UInt8]): String {
let buffer = StringBuffer::new();
var i = 0;
while (i < src.size()) {
let bits = src(i).toInt32().shiftLeft(16i32) | src(i+1).toInt32().shiftLeft(8i32) | src(i+2).toInt32();
i = i + 3;
buffer.appendChar(CHARS.getByte(bits.shiftRight(18i32).asInt64() & 0b111111).toChar());
buffer.appendChar(CHARS.getByte(bits.shiftRight(12i32).asInt64() & 0b111111).toChar());
buffer.appendChar(CHARS.getByte(bits.shiftRight( 6i32).asInt64() & 0b111111).toChar());
buffer.appendChar(CHARS.getByte(bits .asInt64() & 0b111111).toChar());
}
return buffer.toString();
}
1 change: 1 addition & 0 deletions dora/stdlib/stdlib.dora
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
@pub use thread.{AtomicInt32, AtomicInt64, Condition, Mutex, Thread};

@pub mod annotations;
@pub mod base64;
@pub mod collections;
@pub mod primitives;
@pub mod rand;
Expand Down
16 changes: 16 additions & 0 deletions tests/base64/base64.dora
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
fun main(): Unit {
bytes3();
bytes15();
}

fun bytes3(): Unit {
let bytes = Array[UInt8]::new(0u8, 12u8, 23u8);
let string = std::base64::encode(bytes);
println(string);
}

fun bytes15(): Unit {
let bytes = Array[UInt8]::new(0u8, 12u8, 23u8, 45u8, 67u8, 78u8, 89u8, 91u8, 12u8, 23u8, 45u8, 67u8, 78u8, 89u8, 91u8);
let string = std::base64::encode(bytes);
println(string);
}
2 changes: 1 addition & 1 deletion tests/fatal1.dora
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//= error code 1
//= stderr "fatal error: bla\n std::fatalError (stdlib/stdlib.dora:16)\n main (tests/fatal1.dora:5)\n"
//= stderr "fatal error: bla\n std::fatalError (stdlib/stdlib.dora:17)\n main (tests/fatal1.dora:5)\n"

fun main(): Unit {
std::fatalError("bla");
Expand Down

0 comments on commit 9634903

Please sign in to comment.