Hare by Example: Encoding

Hare has support for various encoding formats, but probably the most common would be Base64 and hexadecimal.

use encoding::base64;
use encoding::hex;
use fmt;
use io;
use os;
use strings;

export fn main() void = {
	// Convert a string into a slice of u8
	const data = strings::toutf8("Go to https://harebyexample.org");

	// Quick way to encode data to a string with standard encoding
	const stdstr = base64::encodestr(&base64::std_encoding, data)!;
	fmt::println("Standard encoding", stdstr)!;

	// Quick way to encode data to a string with URL encoding
	const urlstr = base64::encodestr(&base64::url_encoding, data)!;
	fmt::println("URL encoding", urlstr)!;

	// We can also set up an encoder and us normal write functions
	// to encode as we write.
	const enc = base64::newencoder(&base64::url_encoding,
		os::stdout);

	// We can write data to the encoder as much as we want.
	io::write(&enc, data)!;
	fmt::println()!;

	io::write(&enc, ['h', 'a', 'r', 'e']: []u8)!;
	fmt::println()!;

	// All of this is also possible in the other direction to decode
	// data as well.

	// When working with non-readable binary data it is often
	// helpful to encode it to hex to view it. Hare offers hex
	// encoding as well with a few helpers.
	const hexstr = hex::encodestr(data)!;
	fmt::println(hexstr)!;

	// We can even set up an encoder like before.
	const hexenc = hex::newencoder(os::stdout);
	io::write(&hexenc, data)!;
	fmt::println()!;

	// Probably the more useful method is to just dump the hex
	// encoded data to get a nice formatted block of the hex values
	// byte numbers, and actual values of the data itself.
	hex::dump(os::stdout, data)!;
};
$ hare run encoding.ha
4/4 tasks completed (100%)
Standard encoding R28gdG8gaHR0cHM6Ly9oYXJlYnlleGFtcGxlLm9yZw==
URL encoding R28gdG8gaHR0cHM6Ly9oYXJlYnlleGFtcGxlLm9yZw==
R28gdG8gaHR0cHM6Ly9oYXJlYnlleGFtcGxlLm9y
Z2hh
476f20746f2068747470733a2f2f6861726562796578616d706c652e6f7267
476f20746f2068747470733a2f2f6861726562796578616d706c652e6f7267
00000000  47 6f 20 74 6f 20 68 74  74 70 73 3a 2f 2f 68 61  |Go to https://ha|
00000010  72 65 62 79 65 78 61 6d  70 6c 65 2e 6f 72 67     |rebyexample.org|