shithub: mc

ref: 74d91a0021de012908cfdb35fb61a1473a376130
dir: /lib/bio/puti.myr/

View raw version
use std

use "bio"
use "types"

pkg bio =
	/* unsigned big endian */
	generic putbe8	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
	generic putbe16	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
	generic putbe32	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
	generic putbe64	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a

	/* unsigned little endian */
	generic putle8	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
	generic putle16	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
	generic putle32	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
	generic putle64	: (f : file#, v : @a -> std.result(std.size, err)) :: numeric,integral @a
;;

generic putbe8  = {f, v; -> putbe(f, (v : uint64), 1)}
generic putbe16 = {f, v; -> putbe(f, (v : uint64), 2)}
generic putbe32 = {f, v; -> putbe(f, (v : uint64), 4)}
generic putbe64 = {f, v; -> putbe(f, (v : uint64), 8)}

generic putle8  = {f, v; -> putle(f, (v : uint64), 1)}
generic putle16 = {f, v; -> putle(f, (v : uint64), 2)}
generic putle32 = {f, v; -> putle(f, (v : uint64), 4)}
generic putle64 = {f, v; -> putle(f, (v : uint64), 8)}

const putle = {f, v, n
	var buf : byte[8]

	match ensurewrite(f, n)
	| `std.Err e:
		-> `std.Err e
	| `std.Ok _:
		buf[0] = ((v >> 0) & 0xff : byte)
		buf[1] = ((v >> 8) & 0xff : byte)
		buf[2] = ((v >> 16) & 0xff : byte)
		buf[3] = ((v >> 24) & 0xff : byte)
		buf[4] = ((v >> 32) & 0xff : byte)
		buf[5] = ((v >> 40) & 0xff : byte)
		buf[6] = ((v >> 48) & 0xff : byte)
		buf[7] = ((v >> 56) & 0xff : byte)
		-> write(f, buf[:n])
	;;
}

const putbe = {f, v, n
	var buf : byte[8]

	match ensurewrite(f, n)
	| `std.Err e:
		-> `std.Err e
	| `std.Ok _:
		buf[0] = ((v >> 56) & 0xff : byte)
		buf[1] = ((v >> 48) & 0xff : byte)
		buf[2] = ((v >> 40) & 0xff : byte)
		buf[3] = ((v >> 32) & 0xff : byte)
		buf[4] = ((v >> 24) & 0xff : byte)
		buf[5] = ((v >> 16) & 0xff : byte)
		buf[6] = ((v >> 8) & 0xff : byte)
		buf[7] = ((v >> 0) & 0xff : byte)
		-> write(f, buf[8-n:])
	;;
}