Lindenii Project Forge
Login

hare-git

Git library for Hare

Warning: Due to various recent migrations, viewing non-HEAD refs may be broken.

/git/obj_blob.ha (raw)

use strconv;
use strings;

// A simple Git blob with its object ID and raw data.
export type blob = struct {
	data: []u8,
};

// Frees resources associated with a [[blob]].
export fn blob_finish(b: blob) void = {
	free(b.data);
};

// Parses a blob from its raw data.
// The data is copied and the resulting blob
// must be finished with [[blob_finish]].
export fn blob_parse(body: []u8) (blob | nomem) = {
	let data = alloc(body...)?;
	return blob { data = data };
};


// Serializes a blob into the uncompressed on-disk format.
export fn blob_serialize(b: blob) ([]u8 | nomem) = {
	const sizes = strconv::ztos(len(b.data));
	const ty = strings::toutf8("blob ");
	const sizesb = strings::toutf8(sizes);

	let hlen = len(ty) + len(sizesb) + 1z;
	let out = alloc([0u8...], hlen + len(b.data))?;
	let pos = 0z;

	out[pos .. pos + len(ty)] = ty;
	pos += len(ty);

	out[pos .. pos + len(sizesb)] = sizesb;
	pos += len(sizesb);

	out[pos] = 0u8;
	pos += 1z;

	out[pos .. pos + len(b.data)] = b.data;
	return out;
};