summaryrefslogtreecommitdiff
path: root/chapter31/src/main/smp/sys
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-08 14:20:21 -0800
committerCliff Click <cliffc@acm.org>2026-11-12 13:48:30 -0800
commit6fb3aac50c642ed73ec78e9ceb6e04b127796abb (patch)
treeb0f3df12b85add20a34cfe839bdfdba272237d9a /chapter31/src/main/smp/sys
parent394f0aba21eb7a73a00014b3ffcf2ad21eeb8e21 (diff)
downloadSimple-6fb3aac50c642ed73ec78e9ceb6e04b127796abb.tar.gz
Simple-6fb3aac50c642ed73ec78e9ceb6e04b127796abb.zip
Start Chapter 31 from the completed Chapter 30 compiler
Diffstat (limited to 'chapter31/src/main/smp/sys')
-rw-r--r--chapter31/src/main/smp/sys/adt.smp3
-rw-r--r--chapter31/src/main/smp/sys/adt/bitset.smp57
-rw-r--r--chapter31/src/main/smp/sys/ary.smp40
-rw-r--r--chapter31/src/main/smp/sys/aryi64.smp85
-rw-r--r--chapter31/src/main/smp/sys/aryu8.smp78
-rw-r--r--chapter31/src/main/smp/sys/char.smp8
-rw-r--r--chapter31/src/main/smp/sys/io.smp95
-rw-r--r--chapter31/src/main/smp/sys/libc.smp61
-rw-r--r--chapter31/src/main/smp/sys/rt.smp3
-rw-r--r--chapter31/src/main/smp/sys/rt/simple_args.smp22
-rw-r--r--chapter31/src/main/smp/sys/scan.smp39
-rw-r--r--chapter31/src/main/smp/sys/text.smp98
12 files changed, 589 insertions, 0 deletions
diff --git a/chapter31/src/main/smp/sys/adt.smp b/chapter31/src/main/smp/sys/adt.smp
new file mode 100644
index 00000000..a4fe40bf
--- /dev/null
+++ b/chapter31/src/main/smp/sys/adt.smp
@@ -0,0 +1,3 @@
+
+// Abstract data types.
+val bitset = bitset;
diff --git a/chapter31/src/main/smp/sys/adt/bitset.smp b/chapter31/src/main/smp/sys/adt/bitset.smp
new file mode 100644
index 00000000..d02cd2fe
--- /dev/null
+++ b/chapter31/src/main/smp/sys/adt/bitset.smp
@@ -0,0 +1,57 @@
+
+// A set of non-negative integers, represented one bit per value.
+struct bitset {
+ i64[] !_bits;
+
+ new bitset = { ->
+ _bits = new i64[1];
+ };
+
+ // Return 0 for missing, non-zero for true
+ val get = { int bit ->
+ if( (bit >> 6) >= _bits# ) return false;
+ i64 mask = 1 << (bit & 63);
+ return (_bits[bit >> 6] & mask);
+ };
+
+ val _grow = { int bit ->
+ int x = bit >> 6;
+ int len = _bits#;
+ if( x < len ) return self;
+ while( x >= len ) len *= 2;
+ var bits = new i64[len];
+ for( int i=0; i<_bits#; i++ )
+ bits[i] = _bits[i];
+ _bits = bits;
+ return self;
+ };
+
+ // Set
+ val set = { int bit ->
+ i64 mask = 1 << (bit & 63);
+ _grow(bit)._bits[bit >> 6] |= mask;
+ return self;
+ };
+
+ // Test and set
+ val tset = { int bit ->
+ int idx = bit >> 6;
+ i64 mask = 1 << (bit & 63);
+ if( _grow(bit)._bits[idx] & mask )
+ return true; // Already set
+ _bits[idx] |= mask;
+ return false; // Was false (and now set)
+ };
+
+ val clr = { int bit ->
+ if( (bit >> 6) >= _bits# ) return self;
+ i64 mask = 1 << (bit & 63);
+ _bits[bit >> 6] &= (mask ^ -1);
+ return self;
+ };
+
+ val clear = { ->
+ for( int i=0; i<_bits#; i++ ) _bits[i] = 0;
+ return self;
+ };
+};
diff --git a/chapter31/src/main/smp/sys/ary.smp b/chapter31/src/main/smp/sys/ary.smp
new file mode 100644
index 00000000..c139cd33
--- /dev/null
+++ b/chapter31/src/main/smp/sys/ary.smp
@@ -0,0 +1,40 @@
+
+// Array utilities
+
+// Geometric growth without wrapping a u32 length. Zero means too large.
+val capacity = { u32 current, i64 needed ->
+ if( needed < 0 || needed > 4294967295 ) return 0;
+ if( needed <= current ) return current;
+ i64 size = current ? current : 1;
+ while( size < needed ) {
+ size *= 2;
+ if( size > 4294967295 ) size = 4294967295;
+ }
+ u32 result = size;
+ return result;
+};
+
+// Copy byte array contents. Copies the shorter of the buffers and len
+val copy = { u8[] dst, u32 doff, u8[~] src, u32 soff, u32 len ->
+ if( doff > dst# || soff > src# ) return dst;
+ if( len > dst# - doff ) len = dst# - doff;
+ if( len > src# - soff ) len = src# - soff;
+ for( u32 i=0; i<len; i++ )
+ dst[i+doff] = src[i+soff];
+ return dst;
+};
+
+// Compare lexigraphically array contents. Compares up to shorter array or
+// len. Returns <0 or >0 for first non-matching byte. Returns <0 or >0 for
+// the larger array after that, or 0 if both arrays are fully equal.
+val cmp = { u8[~] src1, u32 off1, u8[~] src2, u32 off2, u32 len ->
+ u32 left1 = off1 >= src1# ? 0 : src1# - off1;
+ u32 left2 = off2 >= src2# ? 0 : src2# - off2;
+ u32 len1 = len > left1 ? left1 : len;
+ u32 len2 = len > left2 ? left2 : len;
+ u32 max = len1 > len2 ? len2 : len1;
+ for( u32 i=0; i<max; i++ )
+ if( src1[off1+i] != src2[off2+i] )
+ return src1[off1+i] - src2[off2+i]; // Bytes determine compare
+ return len1 - len2; // Length determines compare
+};
diff --git a/chapter31/src/main/smp/sys/aryi64.smp b/chapter31/src/main/smp/sys/aryi64.smp
new file mode 100644
index 00000000..b9f1fbed
--- /dev/null
+++ b/chapter31/src/main/smp/sys/aryi64.smp
@@ -0,0 +1,85 @@
+
+// Ary/Vector of i64s
+struct aryi64 {
+ u32 !len = 0;
+ i64[] !buf;
+
+ new aryi64 = { i64[] b ->
+ buf = b;
+ };
+
+ // Grow as needed
+ val _grow = { u32 len2 ->
+ if( len+len2 <= buf# ) return self;
+ u32 newlen = ary.capacity(buf#,len+len2);
+ if( !newlen ) libc._exit(1); // Length exceeds the array representation.
+ i64[] !buf2 = new i64[newlen];
+ for( u32 i=0; i<len; i++ )
+ buf2[i] = buf[i];
+ buf = buf2;
+ self;
+ };
+
+ // Add an i64 to aryi64
+ val add = { i64 c ->
+ _grow(1).buf[len++] = c;
+ self;
+ };
+
+ val get = { u32 index -> return buf[index]; };
+
+ // Write the bracketed array-list form to aryu8.
+ val str = { ->
+ // TODO: clunky default constructor syntax
+ var str = new aryu8().add('[');
+ for( u32 i=0; i<len; i++ )
+ str.num(buf[i]).add(',').add(' ');
+ if( len ) str.undo(2);
+ return str.add(']');
+ };
+
+ val swap = { u32 i, u32 j ->
+ i64 tmp = buf[i];
+ buf[i] = buf[j];
+ buf[j] = tmp;
+ self;
+ };
+};
+
+
+
+// Parse a comma-separated list of numbers, wrapped with square brackets,
+// with optional whitespace e.g. "[ -17, 0,99,12456789 ] ".
+// parseAryI64 & aryi64.str are bijections modulo whitespace.
+// Returns null if the parse failed, without giving a clue as to why.
+val parseAryI64 = { u8[~] str ->
+ !scan !s = new scan(str);
+ if( !s.match('[') ) return null;
+ // Array of parsed results
+ var nums = new aryi64(new i64[1]);
+
+ // Parse a list of numbers
+ if( s.match(']') ) // Handle the empty list
+ return nums;
+
+ // Parse number commas "123, " until something else
+ while( s.x < s.buf# ) {
+ nums.add(s.number());
+ if( s.bad ) return null;
+ if( !s.match(',') )
+ break;
+ };
+ // Close the list
+ if( !s.match(']') ) return null;
+ s.skip();
+ return s.x == s.buf# ? nums : null;
+};
+
+val copy = { i64[] dst, u32 doff, i64[~] src, u32 soff, u32 len ->
+ if( doff > dst# || soff > src# ) return dst;
+ if( len > dst# - doff ) len = dst# - doff;
+ if( len > src# - soff ) len = src# - soff;
+ for( u32 i=0; i<len; i++ )
+ dst[i+doff] = src[i+soff];
+ return dst;
+};
diff --git a/chapter31/src/main/smp/sys/aryu8.smp b/chapter31/src/main/smp/sys/aryu8.smp
new file mode 100644
index 00000000..18543f13
--- /dev/null
+++ b/chapter31/src/main/smp/sys/aryu8.smp
@@ -0,0 +1,78 @@
+
+// Ary/Vector of u8s - a resizable array of bytes.
+struct aryu8 {
+ u32 !len = 0;
+ u8[] !buf;
+
+ new aryu8 = { -> buf = new u8[1]; };
+
+ // Grow as needed
+ val _grow = { u32 len2 ->
+ if( len+len2 <= buf# ) return self;
+ u32 newlen = ary.capacity(buf#,len+len2);
+ if( !newlen ) libc._exit(1); // Length exceeds the array representation.
+ u8[] !buf2 = new u8[newlen];
+ ary.copy(buf2,0,buf,0,len);
+ buf = buf2;
+ self;
+ };
+
+ val clear = { -> len = 0; self; };
+
+ // Add a character to aryu8
+ val add = { u8 c ->
+ _grow(1).buf[len++] = c;
+ self;
+ };
+
+ // Add all of a plain array to the aryu8
+ val addAry = { u8[~] xs ->
+ u32 n=xs#;
+ _grow(n);
+ ary.copy(buf,len,xs,0,n);
+ len += n;
+ self;
+ };
+
+ // Remove x bytes from the tail.
+ val undo = { u32 x ->
+ len = len >= x ? len-x : 0;
+ self;
+ };
+
+ // Print ASCII number into aryu8
+ val num = { i64 x ->
+ text.integer(self,x,0,0,-1);
+ self;
+ };
+
+ // Write all bytes to fd; return len, or -1 with errno set on failure.
+ val write = { i32 fd ->
+ io.writeOff(fd,buf,0,len);
+ };
+};
+
+
+// Parse one integer, ignore trailing data; returns 0 with an empty string.
+// If you want a more robust parsing, use the `scan` class
+val atoi = { u8[~] str ->
+ u32 x = 0;
+ while( x < str# && str[x] <= ' ' ) x++;
+ if( x == str# ) return 0;
+ bool neg = false;
+ if( str[x]=='-' ) { neg=true; x++; }
+ i64 n = 0;
+ while( x < str# && '0' <= str[x] <= '9' )
+ n = n*10 + str[x++]-'0';
+ return neg ? -n : n;
+};
+
+// Zero-terminate a string for libc, reserving one array element for the zero.
+{ u8[~] -> u8[] } str0 = { u8[~] str ->
+ if( str# == 4294967295 ) libc._exit(1);
+ u8[] !strz = new u8[str#+1];
+ u32 len=str#;
+ ary.copy(strz,0,str,0,len);
+ strz[str#] = '\0';
+ strz;
+};
diff --git a/chapter31/src/main/smp/sys/char.smp b/chapter31/src/main/smp/sys/char.smp
new file mode 100644
index 00000000..22ca4213
--- /dev/null
+++ b/chapter31/src/main/smp/sys/char.smp
@@ -0,0 +1,8 @@
+
+val toupper = { u8 c ->
+ return c >= 'a' && c <= 'z' ? c - ('a' - 'A') : c;
+};
+
+val tolower = { u8 c ->
+ return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c;
+};
diff --git a/chapter31/src/main/smp/sys/io.smp b/chapter31/src/main/smp/sys/io.smp
new file mode 100644
index 00000000..14993429
--- /dev/null
+++ b/chapter31/src/main/smp/sys/io.smp
@@ -0,0 +1,95 @@
+
+// Simple I/O Library
+
+// Write byte array to stdout
+val p = { u8[~] str -> write(1,str); };
+val p_noInline = { u8[~] str -> write(1,str); };
+// Write to stderr
+val err = { u8[~] str -> write(libc.STDERR,str); };
+
+
+// Read until EOF, including after short reads. Return an empty array for an
+// empty stream, or null on error with errno preserved (partial data discarded).
+val read = { i32 fd ->
+ val chunk = new u8[8*1024];
+ i64 ptr = chunk;
+ val buf = new aryu8();
+ while( true ) {
+ i64 rez = libc.read(fd,ptr,chunk#);
+ if( rez < 0 ) {
+ if( libc.errno() == libc.EINTR ) continue;
+ return null;
+ }
+ if( rez == 0 ) break;
+ if( buf.len+rez > 4294967295 ) {
+ libc.set_errno(libc.EOVERFLOW);
+ return null;
+ }
+ u32 count = rez;
+ buf._grow(count);
+ ary.copy(buf.buf,buf.len,chunk,0,count);
+ buf.len += count;
+ }
+ val out = new u8[buf.len];
+ return ary.copy(out,0,buf.buf,0,buf.len);
+};
+
+// Write all bytes, returning the count or -1 with errno set. An error can
+// follow a successfully written prefix; it does not undo that prefix.
+val write = { i32 fd, u8[~] str ->
+ writeOff(fd,str,0,str#);
+};
+
+// Write a slice, capping len at the remaining bytes. An offset past the end
+// is invalid, including for an empty write. A valid empty slice returns zero.
+// Invalid arguments return -1;
+val writeOff = { i32 fd, u8[~] str, u32 off, u32 len ->
+ if( off > str# ) return libc.set_errno(libc.EINVAL);
+ if( len > str# - off ) len = str# - off;
+ i64 ptr = str;
+ ptr += off;
+ i64 done = 0;
+ while( done < len ) {
+ i64 rez = libc.write(fd,ptr+done,len-done);
+ if( rez < 0 ) {
+ if( libc.errno() == libc.EINTR ) continue;
+ return -1;
+ }
+ if( rez == 0 ) {
+ libc.set_errno(libc.EIO);
+ return -1;
+ }
+ done += rez;
+ }
+ return done;
+};
+
+// Return stdin as a u8[].
+val stdin = { -> read(0); };
+
+// One byte, without Enter or echo. Restores the previous terminal mode before
+// returning. Files/pipes also work. Returns 0..255, or -1 with libc.errno() set
+// to libc.EOF or an OS error. Ctrl-C is byte 3; escape/UTF-8 sequences are multiple bytes.
+val getch = { -> libc.simple_getch(); };
+
+// Create file for writing. Return fd, or -1 and errno has the error code
+val create = { u8[~] str ->
+ i64 ptr = sys.aryu8.str0(str);
+ i32 perms = 6*64 + 6*8 + 6; // 0666
+ return libc.creat(ptr, perms);
+};
+
+// Open file for reading. Return fd, or -1 and errno has the error code
+val open = { u8[~] str ->
+ i64 ptr = sys.aryu8.str0(str);
+ return libc.open(ptr, sys.libc.O_RDONLY, 0);
+};
+
+// Close an open fd. Return 0, or -1 and errno has the error code
+val close = { i32 fd -> return libc.close(fd); };
+
+// Remove a file. Return 0, or -1 and errno has the error code
+val remove = { u8[~] str ->
+ i64 ptr = sys.aryu8.str0(str);
+ return libc.unlink(ptr);
+};
diff --git a/chapter31/src/main/smp/sys/libc.smp b/chapter31/src/main/smp/sys/libc.smp
new file mode 100644
index 00000000..7122bbd8
--- /dev/null
+++ b/chapter31/src/main/smp/sys/libc.smp
@@ -0,0 +1,61 @@
+
+// libc bindings:
+// https://www.man7.org/linux/man-pages/man2/<libc call>.2.html
+
+// The buffers are i64 addresses of zero-terminated strings.
+// i64 buf = aryu8.str0("some_file");
+// buf mode perm-> fd
+{ i64 i32 i32 -> i32 } open = "C";
+// buf perm -> fd
+{ i64 i32 -> i32 } creat = "C";
+
+// fd buf len -> len
+{ i32 i64 i64 -> i64 } write = "C";
+// fd buf len -> len
+{ i32 i64 i64 -> i64 } read = "C";
+// fd -> err
+{ i32 -> i32 } close = "C";
+// path -> err
+{ i64 -> i32 } unlink = "C";
+
+i32 O_RDONLY = 0;
+i32 O_WRONLY = 1;
+i32 O_RDWR = 2;
+i32 O_CREAT = 512; // 02000 on x86_64-pc-cygwin
+i32 O_TRUNC = 1024; // 04000 on x86_64-pc-cygwin
+
+i32 STDIN = 0;
+i32 STDOUT = 1;
+i32 STDERR = 2;
+i32 EOF = -1; // simple_getch sets errno to EOF on end-of-input.
+
+// status
+{ i32 -> i32 } _exit = "C";
+
+// errno is not an ordinary C data symbol; read it through the native runtime.
+{ i32 } simple_errno = "C";
+val errno = { -> simple_errno(); };
+{ i32 -> i32 } simple_set_errno = "C";
+// Set errno and return -1, matching the native I/O error convention.
+val set_errno = { i32 error -> simple_set_errno(error); };
+
+i32 EINTR = "C";
+i32 EIO = "C";
+i32 EINVAL = "C";
+i32 EOVERFLOW = "C";
+
+// Read one byte from stdin, without <enter> or echo. Restores the previous
+// terminal mode before returning. Files and pipes also work. Returns 0..255,
+// or -1 with errno set to EOF or an OS error. Ctrl-C is byte 3; escape/UTF-8
+// sequences are multiple bytes.
+{ i32 } simple_getch = "C";
+
+// addr len prot flags fd off -> void*
+{ i64 i64 i32 i32 i32 i32 -> i64 } mmap = "C";
+// mmap flags
+i32 PROT_EXEC = 4;
+i32 PROT_READ = 1;
+i32 PROT_WRITE= 2;
+i32 PROT_NONE = 0;
+i32 MAP_PRIVATE = 2;
+i32 MAP_ANON = 32;
diff --git a/chapter31/src/main/smp/sys/rt.smp b/chapter31/src/main/smp/sys/rt.smp
new file mode 100644
index 00000000..d62b4def
--- /dev/null
+++ b/chapter31/src/main/smp/sys/rt.smp
@@ -0,0 +1,3 @@
+// Run Time support: "rt" has the same meaning as Java's rt.jar or C's crt.o.
+// Native entry helpers are compiled and linked independently of ordinary sys
+// imports, so programs without library imports can use the same startup code.
diff --git a/chapter31/src/main/smp/sys/rt/simple_args.smp b/chapter31/src/main/smp/sys/rt/simple_args.smp
new file mode 100644
index 00000000..3f630e54
--- /dev/null
+++ b/chapter31/src/main/smp/sys/rt/simple_args.smp
@@ -0,0 +1,22 @@
+// Native startup support, compiled independently and linked with the CRT.
+// Raw native addresses stay i64; only the arrays allocated here are Simple objects.
+{ i64 i64 -> i64 } simple_argv = "C";
+{ i64 -> i64 } strlen = "C";
+{ i64 i64 i64 -> i64 } memcpy = "C";
+
+val simple_args = { i64 argc, i64 argv ->
+ if( argc < 0 || argc > 4294967295 ) return null;
+ // Zero-filled reference arrays require nullable elements. Every slot is
+ // filled before returning; the native entry bridge publishes u8[~][].
+ val args = new u8[~]?[argc];
+ for( i64 i=0; i<argc; i++ ) {
+ i64 src = simple_argv(argv,i);
+ i64 len = strlen(src);
+ if( len < 0 || len > 4294967295 ) return null;
+ val bytes = new u8[len];
+ i64 dst = bytes;
+ memcpy(dst,src,len);
+ args[i] = bytes;
+ }
+ return args;
+};
diff --git a/chapter31/src/main/smp/sys/scan.smp b/chapter31/src/main/smp/sys/scan.smp
new file mode 100644
index 00000000..44bedaaa
--- /dev/null
+++ b/chapter31/src/main/smp/sys/scan.smp
@@ -0,0 +1,39 @@
+
+// Scanner; a simple string parser.
+struct scan {
+ int !x; // Cursor
+ bool !bad; // True after a malformed token
+ u8[~] buf; // Buffer to parse
+
+ new scan = { u8[~] b -> buf = b; };
+
+ // Skip whitespace
+ val skip = { ->
+ while( x < buf# && buf[x] <= ' ' )
+ x++;
+ return self;
+ };
+
+ // True if find required character, and skip it; else False.
+ val match = { u8 c ->
+ skip();
+ if( x >= buf# ) return false;
+ if( buf[x] != c ) return false;
+ x++;
+ return true;
+ };
+
+ // Parse a simple number
+ val number = { ->
+ skip();
+ bool neg = match('-');
+ if( x >= buf# || buf[x] < '0' || '9' < buf[x] ) {
+ bad = true;
+ return 0;
+ }
+ i64 n = 0;
+ while( x < buf# && '0' <= buf[x] & buf[x] <= '9' )
+ n = n*10 + (buf[x++] - '0');
+ return neg ? -n : n;
+ };
+};
diff --git a/chapter31/src/main/smp/sys/text.smp b/chapter31/src/main/smp/sys/text.smp
new file mode 100644
index 00000000..a414ff45
--- /dev/null
+++ b/chapter31/src/main/smp/sys/text.smp
@@ -0,0 +1,98 @@
+// Formatting primitives used directly by interpolation and named converters.
+// Keep this module free of interpolation: sys can build itself from source.
+// spec's low byte is the format kind; bits 8..12 are flags: - + space # 0.
+
+val begin = { -> new aryu8(); };
+
+val end = { aryu8 b ->
+ val bytes = new u8[b.len];
+ ary.copy(bytes,0,b.buf,0,b.len);
+ u8[~] result = bytes;
+ result;
+};
+
+val _pad = { !aryu8 b, i64 n, u8 c ->
+ for( i64 i=0; i<n; i++ ) b.add(c);
+ b;
+};
+
+val string = { !aryu8 b, u8[~] s, i64 spec, i64 width, i64 precision ->
+ i64 len=s#;
+ if( precision>=0 && precision<len ) len=precision;
+ i64 pad=width-len;
+ if( !(spec&256) ) _pad(b,pad,' ');
+ for( i64 i=0; i<len; i++ ) b.add(s[i]);
+ if( spec&256 ) _pad(b,pad,' ');
+ b;
+};
+
+val integer = { !aryu8 b, i64 value, i64 spec, i64 width, i64 precision ->
+ i64 kind=spec&255;
+ if( kind=='b' ) return string(b,value ? "true" : "false",spec,width,-1);
+ if( kind=='c' ) {
+ if( !(spec&256) ) _pad(b,width-1,' ');
+ u8 c=value;
+ b.add(c);
+ if( spec&256 ) _pad(b,width-1,' ');
+ return b;
+ }
+ bool signed=kind==0 || kind=='d' || kind=='i';
+ i64 base=kind=='o' ? 8 : (kind=='x' || kind=='X' ? 16 : 10);
+ u8[~] alphabet=kind=='X' ? "0123456789ABCDEF" : "0123456789abcdef";
+ val digits=new u8[22]; // Maximum: 22 octal digits for a 64-bit integer.
+ i64 count=0, n=value;
+ // Signed decimal stays nonpositive, including the minimum i64.
+ if( signed && n>0 ) n=-n;
+ if( n==0 && precision!=0 ) digits[count++]='0';
+ while( n!=0 ) {
+ i64 q=0, r=0;
+ if( signed ) { q=n/base; r=q*base-n; }
+ else {
+ // Unsigned division without a u64 type. Halving first makes
+ // the dividend nonnegative; the remainder needs at most one fix.
+ q=((n>>>1)/base)*2;
+ r=n-q*base;
+ if( r>=base ) { q++; r-=base; }
+ }
+ digits[count++]=alphabet[r];
+ n=q;
+ }
+ u8[~] !prefix="";
+ if( signed ) {
+ if( value<0 ) prefix="-";
+ else if( spec&512 ) prefix="+";
+ else if( spec&1024 ) prefix=" ";
+ } else if( (spec&2048) && value!=0 ) {
+ if( kind=='x' ) prefix="0x";
+ if( kind=='X' ) prefix="0X";
+ }
+ i64 zeros=precision>count ? precision-count : 0;
+ // Alternate octal always begins with a zero, including precision-zero 0.
+ if( kind=='o' && (spec&2048) && zeros==0 && (count==0 || digits[count-1]!='0') ) zeros=1;
+ i64 pad=width-prefix#-zeros-count;
+ bool left=(spec&256)!=0;
+ bool zero=(spec&4096)!=0 && precision<0 && !left;
+ if( !left && !zero ) _pad(b,pad,' ');
+ b.addAry(prefix);
+ if( zero ) _pad(b,pad,'0');
+ _pad(b,zeros,'0');
+ while( count>0 ) b.add(digits[--count]);
+ if( left ) _pad(b,pad,' ');
+ b;
+};
+
+// Only conversion of binary floating-point values is delegated to libc.
+// The fixed signature accepts a validated format and returns a byte string.
+{ f64 i64 i64 i64 -> u8[~] } simple_text_float = "C";
+val floating = { !aryu8 b, f64 value, i64 spec, i64 width, i64 precision ->
+ b.addAry(simple_text_float(value,spec,width,precision));
+};
+
+// Explicitly named, typed conversions share the same formatting routines.
+val int = { i64 x -> end(integer (begin(),x, 0 ,0,-1)); };
+val flt = { f64 x -> end(floating(begin(),x, 0 ,0,-1)); };
+val f32 = { f32 x -> end(floating(begin(),x,'g',0,-1)); };
+val f64 = { f64 x -> end(floating(begin(),x, 0 ,0,-1)); };
+val char = { i64 x -> end(integer (begin(),x,'c',0,-1)); };
+val bool = { bool x -> end(integer (begin(),x,'b',0,-1)); };
+val hex = { i64 x -> end(integer (begin(),x,'x',0,-1)); };