dymokomi/luce-js
Source of release 0.6.1
0.6.1 / src / cutils / module.lucb
#==============================================================================================
#
# cutils - C utilities: the C library binding, small string, integer and byte helpers
#
# DESCRIPTION:
# Port of QuickJS cutils.h (lines 1-251: min/max, clz/ctz, unaligned access, byte
# swaps) and cutils.c (lines 32-80: pstrcpy, pstrcat, strstart). Also binds the C
# library's allocator and memory functions once for the whole port, and holds the
# small helpers every module of the port shares: C strings as `str` views and
# comparisons.
#
# C utilities
#
# Copyright (c) 2017 Fabrice Bellard
# Copyright (c) 2018 Charlie Gordon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions: the above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS
# IS", WITHOUT WARRANTY OF ANY KIND.
#
#==============================================================================================
import memory
from io import Writer
# mark: The C library ===========================================================================
## C `malloc`: `size` uninitialised bytes, or none.
pub extern func malloc(size: usize) -> void*?
## C `realloc`: resize `ptr` (none allocates) to `size` bytes, or none on failure.
pub extern func realloc(ptr: void*?, size: usize) -> void*?
## C `free` (`free` is a reserved word in Luce, so the binding is `c_free`).
pub extern func c_free as "free"(ptr: void*?)
## C `memcpy`: copy `n` bytes from `src` to `dest`; answers `dest`.
pub extern func memcpy(dest: void*?, src: const void*?, n: usize) -> void*?
## C `memmove`: copy `n` bytes, the ranges may overlap; answers `dest`.
pub extern func memmove(dest: void*?, src: const void*?, n: usize) -> void*?
## C `memset`: set `n` bytes at `s` to the byte `c`; answers `s`.
pub extern func memset(s: void*?, c: i32, n: usize) -> void*?
## C `memcmp`: compare `n` bytes; negative, zero or positive.
pub extern func memcmp(s1: const void*?, s2: const void*?, n: usize) -> i32
## C `strlen`: the length of the NUL-terminated bytes at `s`.
pub extern func strlen(s: const u8*) -> usize
# mark: Strings =================================================================================
## Copy the NUL-terminated `text` into `buf` of `buf_size` bytes, truncating, and always
## NUL-terminate (when `buf_size > 0`).
pub func pstrcpy(buf: u8*, buf_size: i32, text: const u8*):
if buf_size <= 0:
return
var q = buf
var p = text
let last = buf + (usize)(buf_size - 1)
while true:
let c = *p
p += 1
if c == 0 or q >= last:
break
*q = c
q += 1
*q = 0
## strcat and truncate.
pub func pstrcat(buf: u8*, buf_size: i32, s: const u8*) -> u8*:
let len = (i32)strlen(buf)
if len < buf_size:
pstrcpy(buf + (usize)len, buf_size - len, s)
return buf
## Whether the NUL-terminated `text` starts with `val`; if so and `ptr` is given, `*ptr` is
## set to the first byte after the prefix.
pub func strstart(text: const u8*, val: str, ptr: const u8**?) -> bool:
var p = text
for q in val.bytes:
if *p != q:
return false
p += 1
if let out = ptr:
*out = p
return true
## The NUL-terminated `p` as a `str` viewing its bytes (no copy, no UTF-8 check). QuickJS's
## C strings are UTF-8 except for lone surrogates, which only ever pass through as bytes.
pub func c_str_view(p: const u8*) -> str:
return (str)u8[]((u8*)p, strlen(p))
## Whether the NUL-terminated `p` is the text `text` (C's `!strcmp`).
pub func c_str_equals(p: const u8*, text: str) -> bool:
for i in 0..<text.length:
if p[i] != text.bytes[i]:
return false
return p[text.length] == 0
## Copy `n` bytes; does nothing when `n == 0`, so `dest` and `src` may then be none.
## (Prevent UB when n == 0 and (src == NULL or dest == NULL).)
pub func memcpy_no_ub(dest: void*?, src: const void*?, n: usize):
if n != 0:
_ = memcpy(dest, src, n)
# mark: Min and max =============================================================================
## The larger of two `i32`s.
pub func max_int(a: i32, b: i32) -> i32:
if a > b:
return a
else:
return b
## The smaller of two `i32`s.
pub func min_int(a: i32, b: i32) -> i32:
if a < b:
return a
else:
return b
## The larger of two `u32`s.
pub func max_uint32(a: u32, b: u32) -> u32:
if a > b:
return a
else:
return b
## The smaller of two `u32`s.
pub func min_uint32(a: u32, b: u32) -> u32:
if a < b:
return a
else:
return b
## The larger of two `i64`s.
pub func max_int64(a: i64, b: i64) -> i64:
if a > b:
return a
else:
return b
## The smaller of two `i64`s.
pub func min_int64(a: i64, b: i64) -> i64:
if a < b:
return a
else:
return b
# mark: Leading and trailing zeros ==============================================================
# C uses __builtin_clz/__builtin_ctz; Luce has no intrinsic, so these are binary searches.
# The C versions are undefined for 0; these answer the bit width.
## Count of leading zero bits of `a` (32 for 0; undefined in C).
pub func clz32(a: u32) -> i32:
if a == 0:
return 32
var x = a
var n: i32 = 0
if (x & 0xffff0000) == 0:
n += 16
x = x << 16
if (x & 0xff000000) == 0:
n += 8
x = x << 8
if (x & 0xf0000000) == 0:
n += 4
x = x << 4
if (x & 0xc0000000) == 0:
n += 2
x = x << 2
if (x & 0x80000000) == 0:
n += 1
return n
## Count of leading zero bits of `a` (64 for 0; undefined in C).
pub func clz64(a: u64) -> i32:
let hi = (u32)(a >> 32)
if hi != 0:
return clz32(hi)
return 32 + clz32((u32)a)
## Count of trailing zero bits of `a` (32 for 0; undefined in C).
pub func ctz32(a: u32) -> i32:
if a == 0:
return 32
var x = a
var n: i32 = 0
if (x & 0x0000ffff) == 0:
n += 16
x = x >> 16
if (x & 0x000000ff) == 0:
n += 8
x = x >> 8
if (x & 0x0000000f) == 0:
n += 4
x = x >> 4
if (x & 0x00000003) == 0:
n += 2
x = x >> 2
if (x & 0x00000001) == 0:
n += 1
return n
## Count of trailing zero bits of `a` (64 for 0; undefined in C).
pub func ctz64(a: u64) -> i32:
let lo = (u32)a
if lo != 0:
return ctz32(lo)
return 32 + ctz32((u32)(a >> 32))
# mark: Unaligned access ========================================================================
# Read and written through packed structs, as the C code does: a packed struct's field has
# alignment one, so the access is defined at any address, and it lowers to one load or
# store (memory.read/memory.write copy through memcpy, a call on the interpreter's every
# operand). Byte order is the host's, as in C.
packed struct PackedU64:
var v: u64
packed struct PackedU32:
var v: u32
packed struct PackedU16:
var v: u16
## Read a host-order `u64` at `tab`, which may be unaligned.
pub func get_u64(tab: const u8*) -> u64:
return ((const PackedU64*)tab).v
## Read a host-order `i64` at `tab`, which may be unaligned.
pub func get_i64(tab: const u8*) -> i64:
return (i64)((const PackedU64*)tab).v
## Write a host-order `u64` at `tab`, which may be unaligned.
pub func put_u64(tab: u8*, val: u64):
((PackedU64*)tab).v = val
## Read a host-order `u32` at `tab`, which may be unaligned.
pub func get_u32(tab: const u8*) -> u32:
return ((const PackedU32*)tab).v
## Read a host-order `i32` at `tab`, which may be unaligned.
pub func get_i32(tab: const u8*) -> i32:
return (i32)((const PackedU32*)tab).v
## Write a host-order `u32` at `tab`, which may be unaligned.
pub func put_u32(tab: u8*, val: u32):
((PackedU32*)tab).v = val
## Read a host-order `u16` at `tab`, which may be unaligned, widened to `u32`.
pub func get_u16(tab: const u8*) -> u32:
return ((const PackedU16*)tab).v
## Read a host-order `i16` at `tab`, which may be unaligned, sign-extended to `i32`.
pub func get_i16(tab: const u8*) -> i32:
return (i16)((const PackedU16*)tab).v
## Write a host-order `u16` at `tab`, which may be unaligned.
pub func put_u16(tab: u8*, val: u16):
((PackedU16*)tab).v = val
## Read the byte at `tab`, widened to `u32`.
pub func get_u8(tab: const u8*) -> u32:
return *tab
## Read the byte at `tab` as signed, sign-extended to `i32`.
pub func get_i8(tab: const u8*) -> i32:
return (i8)*tab
## Write the byte `val` at `tab`.
pub func put_u8(tab: u8*, val: u8):
*tab = val
# mark: Byte swaps ==============================================================================
## `x` with its two bytes swapped.
pub func bswap16(x: u16) -> u16:
return (x >> 8) | (x << 8)
## `v` with its four bytes reversed.
pub func bswap32(v: u32) -> u32:
return (((v & 0xff000000) >> 24) | ((v & 0x00ff0000) >> 8) | ((v & 0x0000ff00) << 8) | ((v & 0x000000ff) << 24))
## `v` with its eight bytes reversed.
pub func bswap64(v: u64) -> u64:
return (((v & ((u64)0xff << (7 * 8))) >> (7 * 8)) | ((v & ((u64)0xff << (6 * 8))) >> (5 * 8)) | ((v & ((u64)0xff << (5 * 8))) >> (3 * 8)) | ((v & ((u64)0xff << (4 * 8))) >> (1 * 8)) | ((v & ((u64)0xff << (3 * 8))) << (1 * 8)) | ((v & ((u64)0xff << (2 * 8))) << (3 * 8)) | ((v & ((u64)0xff << (1 * 8))) << (5 * 8)) | ((v & ((u64)0xff << (0 * 8))) << (7 * 8)))