From f28bc869f3812aaaa39d12a26ac835c1d683fab0 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:33:35 +0100 Subject: [PATCH] Str's UTF-8 and toInt, Map's remove and next, Sort, Math, Fmt.real Str: encode and decode, FFFDH for what isn't a char (surrogates, overlong, cut short); toInt counts below zero for the smallest I64. Map: remove by moving later entries back, no tombstones; next walks the slots. Sort: a heapsort. Math after fdlibm, coefficients its own; sqrt by sqrtsd; sin and cos reduce past 1.6E6 by Payne-Hanek with a table of 2/pi. Within 1 ulp of glibc on 30,000 args, edges alike. Fmt.real: whole and fraction apart, an exponent from 1E15. Map and Sort, generic, are tested in test/run; the others in their main. Co-Authored-By: Claude Opus 5.5 (1M context) --- diff --git a/PLAN.md b/PLAN.md index 6b5f667..bcaf459 100644 --- a/PLAN.md +++ b/PLAN.md @@ -39,7 +39,7 @@ breaks here: `spawn` changes. - [x] 4. `Sys`, the rest: `clock`, `now`, `sleep`, `random`; `connectTcp`, `connectUdp`, `listen`, `listenTcp`, `accept`. -- [ ] 5. `Str.encode`, `Str.decode`, `Str.toInt`; `Map.remove` and +- [x] 5. `Str.encode`, `Str.decode`, `Str.toInt`; `Map.remove` and `Map.next`; `Sort`; `Math`; `Fmt.real`. Each module's `main` tests it. - [ ] 5a. Asked for rloc, and every program after it: `Opt`, a diff --git a/README.md b/README.md index a07e3bf..34af872 100644 --- a/README.md +++ b/README.md @@ -127,12 +127,13 @@ `Rt` (ending the program, failed checks, signals), `Sys` (system calls), `Out` (buffered output), `C`, `Lock`, `Thread` (threads without C), `Mem`, -`Heap`, `Arena`, `Str`, `Buf`, `Fmt`, `List(T)` and `Map(K, V; hash, -eq)`. `tools/Doc.raz` prints any of them: +`Heap`, `Arena`, `Str`, `Buf`, `Fmt`, `Math`, `List(T)`, `Map(K, V; +hash, eq)` and `Sort(T; less)`. `tools/Doc.raz` prints any of them: $ ./raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz -Each library module's `main` is its test, which `make check` runs. +Each library module's `main` is its test, which `make check` runs; the +generic ones, which can't run alone, are tested in `test/run`. ## Editors diff --git a/lib/Fmt.raz b/lib/Fmt.raz index bc8e059..5fdf778 100644 --- a/lib/Fmt.raz +++ b/lib/Fmt.raz @@ -1,5 +1,5 @@ (* Formatted output. Each {} in the format takes the next argument: - Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.int(m)]); + Fmt.print("{} of {}\n", [Fmt.int(n), Fmt.real(x, 2)]); {{ and }} stand for { and }. print writes to standard output, write appends to a Buf. *) module Fmt; @@ -13,6 +13,7 @@ str(s: []U8); char(c: U8); bool(b: BOOL); + real(r: F64; places: I64); end; (* The digits of u in base, at the end of the array: it and where they start. *) @@ -35,6 +36,42 @@ if b = nil then Out.str(s); else Buf.str(b, s); end; end; +(* x with places digits after the point, at most 9, rounded to the + nearest; from 1E15 on, with the exponent that makes it less than 10, + as 1.50e17. The whole part and the fraction are taken apart, so that + each fits an I64. *) +proc putReal(b: ^Buf.Buf; x: F64; places: I64); +const zeros = "00000000"; +var d: [24]U8; at, scale, i, whole, frac, e: I64; +begin + if x # x then put(b, "nan"); return; end; + if x < 0.0 then put(b, "-"); x := -x; end; + if x > 1.7976931348623157E308 then put(b, "inf"); return; end; + if places < 0 then places := 0; elsif places > 9 then places := 9; end; + scale := 1; + for i := 1 to places do scale := scale * 10; end; + if x >= 1.0E15 then + while x >= 10.0 do x := x / 10.0; INC(e); end; + end; + whole := I64(x); + frac := I64((x - F64(whole)) * F64(scale) + 0.5); + if frac = scale then INC(whole); frac := 0; end; + if (e > 0) and (whole = 10) then whole := 1; INC(e); end; + d, at := digits(U64(whole), 10); + put(b, d[at..24]); + if places > 0 then + put(b, "."); + d, at := digits(U64(frac), 10); + put(b, zeros[0..places - (24 - at)]); + put(b, d[at..24]); + end; + if e > 0 then + d, at := digits(U64(e), 10); + put(b, "e"); + put(b, d[at..24]); + end; +end; + proc arg(b: ^Buf.Buf; a: Arg); var d: [24]U8; at: I64; one: [1]U8; begin @@ -52,6 +89,7 @@ | str(s): put(b, s); | char(c): one[0] := c; put(b, one); | bool(t): if t then put(b, "true"); else put(b, "false"); end; + | real(r, places): putReal(b, r, places); end; end; @@ -89,7 +127,7 @@ (* The module's test: formats into a buffer over an arena. *) proc main*; -var ar: Arena.Arena; b: Buf.Buf; +var ar: Arena.Arena; b: Buf.Buf; zero: F64; begin if not Arena.init(ADR(ar), 1 shl 16) then Rt.stop("Fmt: no arena"); end; Buf.init(ADR(b), ADR(ar.base)); @@ -99,6 +137,14 @@ Buf.reset(ADR(b)); write(ADR(b), "{} and {}", [int(1)]); if Buf.bytes(ADR(b)) # "1 and " then Rt.stop("Fmt: too few arguments"); end; + Buf.reset(ADR(b)); + write(ADR(b), "{} {} {} {} {} {} {} {}", [real(3.14159, 2), real(-2.5, 0), real(0.999, 2), real(0.05, 1), + real(1.0, 12), real(-0.001, 2), real(123.0, 0), real(999999999999999.9, 0)]); + if Buf.bytes(ADR(b)) # "3.14 -3 1.00 0.1 1.000000000 -0.00 123 1000000000000000" then Rt.stop("Fmt.real"); end; + Buf.reset(ADR(b)); + write(ADR(b), "{} {} {} {} {} {}", [real(1.5E17, 2), real(-9.999E20, 2), real(1.0E15, 0), real(1.7976931348623157E308, 3), + real(1.0 / zero, 2), real(zero / zero, 2)]); + if Buf.bytes(ADR(b)) # "1.50e17 -1.00e21 1e15 1.798e308 inf nan" then Rt.stop("Fmt.real: an exponent"); end; Arena.done(ADR(ar)); end; diff --git a/lib/Map.raz b/lib/Map.raz index 84bf36c..2fef081 100644 --- a/lib/Map.raz +++ b/lib/Map.raz @@ -68,6 +68,30 @@ return true; end; +(* k maps to nothing; false if it didn't map to anything. The entries + after it that were pushed on past its slot move back, so that a + search for each still finds it before an empty slot. *) +proc remove*(m: ^Map; k: K): BOOL; +var i, j, home: I64; +begin + if m^.cap = 0 then return false; end; + i := slot(m, k); + if not m^.slots[i].used then return false; end; + j := (i + 1) & (m^.cap - 1); + while m^.slots[j].used do + (* the entry at j may fill i if i lies between its home and j *) + home := I64(hash(m^.slots[j].key) & U64(m^.cap - 1)); + if (j - home) & (m^.cap - 1) >= (j - i) & (m^.cap - 1) then + m^.slots[i] := m^.slots[j]; + i := j; + end; + j := (j + 1) & (m^.cap - 1); + end; + m^.slots[i].used := false; + DEC(m^.len); + return true; +end; + (* What k maps to, and whether it maps to anything. *) proc get*(m: ^Map; k: K): (V, BOOL); var i: I64; none: V; @@ -76,6 +100,18 @@ i := slot(m, k); if not m^.slots[i].used then return none, false; end; return m^.slots[i].val, true; +end; + +(* The entry after i, walking from 0: the number to pass for the one + after it, or -1 if there are no more, then its key and value. *) +proc next*(m: ^Map; i: I64): (I64, K, V); +var k: K; v: V; +begin + while i < m^.cap do + if m^.slots[i].used then return i + 1, m^.slots[i].key, m^.slots[i].val; end; + INC(i); + end; + return -1, k, v; end; end Map. diff --git a/lib/Math.raz b/lib/Math.raz new file mode 100644 index 0000000..2c97675 --- /dev/null +++ b/lib/Math.raz @@ -0,0 +1,348 @@ +(* Mathematical functions of F64, as C's math.h has them, to within the + last bit or so. They follow fdlibm, Sun's library that most C ones + come from: each brings its argument into a small range, where a + polynomial is accurate, and puts the range back on the result. The + polynomials' coefficients are fdlibm's. + + Left out: tan, the inverse sines and powers, until a program needs + them. *) +module Math; +import Rt; + +const + pi* = 3.141592653589793; + ln2hi = 6.93147180369123816490E-01; (* ln 2 in two parts, whose sum is more exact than one F64 *) + ln2lo = 1.90821492927058770002E-10; + +(* The bits of x, and the F64 with bits u. *) +proc bits(x: F64): U64; +var p: ^U64; +begin + p := ^U64(ADR(x)); + return p^; +end; + +proc fromBits(u: U64): F64; +var p: ^F64; +begin + p := ^F64(ADR(u)); + return p^; +end; + +(* Whether x has its sign bit set, -0.0 included. *) +proc negative(x: F64): BOOL; +begin + return bits(x) shr 63 = 1; +end; + +proc sqrt*(x: F64): F64; +code 0F2H, 0FH, 51H, 0C0H, (* sqrtsd xmm0, xmm0 *) + 0C3H; (* ret *) + +(* The largest whole number not above x. One of 2^52 or more is whole + already, and so are an infinity and NaN. *) +proc floor*(x: F64): F64; +var t: F64; +begin + if not (x > -4503599627370496.0) or not (x < 4503599627370496.0) or (x = 0.0) then return x; end; + t := F64(I64(x)); + if t > x then t := t - 1.0; end; + return t; +end; + +(* x times 2^k, for k from -1075 to 1024: 2^k is made from its bits, + in two steps where k is past what an F64's exponent holds. *) +proc scale(x: F64; k: I64): F64; +begin + if k > 1023 then x := x * fromBits(U64(2046) shl 52); DEC(k, 1023); end; + if k < -1022 then x := x * fromBits(U64(1 + 53) shl 52); INC(k, 1022 - 53); end; + return x * fromBits(U64(k + 1023) shl 52); +end; + +(* e^x = 2^k e^r, with r = x - k ln 2 at most ln 2 / 2 across. *) +proc exp*(x: F64): F64; +var k: I64; hi, lo, r, rr, c: F64; +begin + if x # x then return x; end; + if x > 709.782712893383973096 then return x * fromBits(U64(2046) shl 52); end; (* too big: inf *) + if x < -745.13321910194110842 then return 0.0; end; + if x < 0.0 then k := I64(x * 1.44269504088896338700 - 0.5); + else k := I64(x * 1.44269504088896338700 + 0.5); + end; + hi := x - F64(k) * ln2hi; + lo := F64(k) * ln2lo; + r := hi - lo; + rr := r * r; + c := r - rr * (1.66666666666666019037E-01 + rr * (-2.77777777770155933842E-03 + + rr * (6.61375632143793436117E-05 + rr * (-1.65339022054652515390E-06 + + rr * 4.13813679705723846039E-08)))); + return scale(1.0 + (r * c / (2.0 - c) - lo + hi), k); +end; + +(* ln x = k ln 2 + ln m, with m from sqrt(2)/2 to sqrt(2): ln m is + found through s = f / (2 + f), f = m - 1, whose series converges + fast. *) +proc ln*(x: F64): F64; +var u: U64; k: I64; f, hfsq, s, z, w, r: F64; +begin + if x # x then return x; end; + if x < 0.0 then return (x - x) / 0.0; end; (* NaN *) + if x = 0.0 then return -1.0 / 0.0; end; (* -inf *) + if x > 1.7976931348623157E308 then return x; end; + if x < 2.2250738585072014E-308 then (* subnormal: made normal *) + x := x * 18014398509481984.0; (* 2^54 *) + k := -54; + end; + (* the exponent, counted from m's lower end, and the bits of m *) + u := bits(x) + (3FF0000000000000H - 3FE6A09E00000000H); + INC(k, I64(u shr 52) - 3FFH); + f := fromBits((u & 0FFFFFFFFFFFFFH) + 3FE6A09E00000000H) - 1.0; + hfsq := 0.5 * f * f; + s := f / (2.0 + f); + z := s * s; + w := z * z; + r := w * (3.999999999940941908E-01 + w * (2.222219843214978396E-01 + w * 1.531383769920937332E-01)) + + z * (6.666666666666735130E-01 + w * (2.857142874366239149E-01 + + w * (1.818357216161805012E-01 + w * 1.479819860511658591E-01))); + return s * (hfsq + r) + F64(k) * ln2lo - hfsq + f + F64(k) * ln2hi; +end; + +(* a times b: the low 64 bits of the product, and the high. *) +proc mul(a, b: U64): (U64, U64); +code 48H, 89H, 0F8H, (* mov rax, rdi *) + 48H, 0F7H, 0E6H, (* mul rsi *) + 0C3H; (* ret *) + +(* 64 bits of t from bit s on, the first bit of t[0] being 0. *) +proc window(t: []U64; s: I64): U64; +var q, r: I64; +begin + q := s div 64; + r := s mod 64; + if r = 0 then return t[q]; end; + return t[q] shl r | t[q + 1] shr (64 - r); +end; + +(* reduce's work, for an x too big for it, by Payne and Hanek's way. + x is m 2^e, m a whole number of 53 bits, so x 2/pi is m times the + bits of 2/pi moved by e: those that land at 4 or above add whole + turns, which change no sine, and are left out; the 192 after them + give the two bits of n mod 4 and the fraction past n, exact far + beyond an F64. *) +proc reduceLarge(x: F64): (I64, F64, F64); +var + t: [21]U64; (* 2/pi's bits after its point, behind a word of zeros *) + m, w0, w1, w2, p0, p1, p2, lo: U64; e, s, n, k: I64; y: F64; neg, up: BOOL; +begin + t := [0, 0A2F9836E4E441529H, 0FC2757D1F534DDC0H, 0DB6295993C439041H, 0FE5163ABDEBBC561H, + 0B7246E3A424DD2E0H, 06492EEA09D1921CH, 0FE1DEB1CB129A73EH, 0E88235F52EBB4484H, + 0E99C7026B45F7E41H, 03991D639835339F4H, 09C845F8BBDF9283BH, 01FF897FFDE05980FH, + 0EF2F118B5A0A6D1FH, 06D367ECF27CB09B7H, 04F463F669E5FEA2DH, 07527BAC7EBE5F17BH, + 03D0739F78A5292EAH, 06BFB5FB11F8D5D08H, 056033046FC7B6BABH, 0F0CFBC209AF4361DH]; + neg := x < 0.0; + if neg then x := -x; end; + m := bits(x) & 0FFFFFFFFFFFFFH | 10000000000000H; + e := I64(bits(x) shr 52) - 1075; + (* W, the 192 bits of 2/pi from the one worth 2^(1 - e), so that + x 2/pi is m W 2^-190, of which the bits from 2^192 up are left out *) + s := e + 62; + w0 := window(t, s); + w1 := window(t, s + 64); + w2 := window(t, s + 128); + p0, p1 := mul(m, w2); + lo, p2 := mul(m, w1); + INC(p1, lo); + INC(p2, m * w0); + if p1 < lo then INC(p2); end; + (* n is the two bits from 2^190, the fraction those below; from a + half up, n is the next and the fraction 1 less, taken as 1 less + the fraction, negated: its bits complemented, one in 2^190 short *) + n := I64(p2 shr 62); + p2 := p2 & 3FFFFFFFFFFFFFFFH; + up := p2 shr 61 = 1; + if up then + INC(n); + p0 := ~p0; p1 := ~p1; p2 := ~p2 & 3FFFFFFFFFFFFFFFH; + end; + (* the fraction as an F64, from the 64 bits that start at its first one *) + k := 0; + while (p2 shr 61 = 0) and (k < 128) do + p2 := p2 shl 1 | p1 shr 63; + p1 := p1 shl 1 | p0 shr 63; + p0 := p0 shl 1; + INC(k); + end; + y := scale(F64(p2 shl 2 | p1 shr 62) * (pi / 2.0), -64 - k); + if up then y := -y; end; + if neg then return -n, -y, 0.0; end; + return n, y, 0.0; +end; + +(* x less the whole number n of pi/2 nearest it, as y + yy, more exact + than one F64; and n. pi/2 is taken in three parts of 33 bits, each + with what is left of it after, so that n times each is exact while + n is below 2^20, about x = 1.6E6. *) +proc reduce(x: F64): (I64, F64, F64); +var n: I64; fn, r, t, w, y: F64; +begin + if (x > 1.6E6) or (x < -1.6E6) then return reduceLarge(x); end; + if x < 0.0 then n := I64(x * 6.36619772367581382433E-01 - 0.5); + else n := I64(x * 6.36619772367581382433E-01 + 0.5); + end; + fn := F64(n); + r := x - fn * 1.57079632673412561417E+00; + t := r; + w := fn * 6.07710050630396597660E-11; + r := t - w; + w := fn * 2.02226624879595063154E-21 - ((t - r) - w); + t := r; + w := fn * 2.02226624871116645580E-21; + r := t - w; + w := fn * 8.47842766036889956997E-32 - ((t - r) - w); + y := r - w; + return n, y, (r - y) - w; +end; + +(* sin and cos of x + y, x at most pi/4 and y far below it. *) +proc kernelSin(x, y: F64): F64; +var z, v, r: F64; +begin + z := x * x; + v := z * x; + r := 8.33333333332248946124E-03 + z * (-1.98412698298579493134E-04 + z * 2.75573137070700676789E-06) + + z * z * z * (-2.50507602534068634195E-08 + z * 1.58969099521155010221E-10); + return x - ((z * (0.5 * y - v * r) - y) + v * 1.66666666666666324348E-01); +end; + +proc kernelCos(x, y: F64): F64; +var z, r, hz, w: F64; +begin + z := x * x; + r := z * (4.16666666666666019037E-02 + z * (-1.38888888888741095749E-03 + z * 2.48015872894767294178E-05)) + + z * z * z * z * (-2.75573143513906633035E-07 + z * (2.08757232129817482790E-09 + - z * 1.13596475577881948265E-11)); + hz := 0.5 * z; + w := 1.0 - hz; + return w + (((1.0 - w) - hz) + (z * r - x * y)); +end; + +proc sin*(x: F64): F64; +var n: I64; y, yy: F64; +begin + if (x = 0.0) or (x # x) then return x; end; + if (x - x) # 0.0 then return x - x; end; (* an infinity: NaN *) + n, y, yy := reduce(x); + n := n & 3; + if n = 0 then return kernelSin(y, yy); + elsif n = 1 then return kernelCos(y, yy); + elsif n = 2 then return -kernelSin(y, yy); + end; + return -kernelCos(y, yy); +end; + +proc cos*(x: F64): F64; +var n: I64; y, yy: F64; +begin + if (x - x) # 0.0 then return x - x; end; (* an infinity or NaN: NaN *) + n, y, yy := reduce(x); + n := n & 3; + if n = 0 then return kernelCos(y, yy); + elsif n = 1 then return -kernelSin(y, yy); + elsif n = 2 then return -kernelCos(y, yy); + end; + return kernelSin(y, yy); +end; + +(* The arc tangent of x, at least 0: atan(x) = atan(c) + atan(t), t + small, for c one of 1/2, 1, 3/2 and infinity, as x is nearest; the + atan(c) in two parts as pi is. *) +proc atan(x: F64): F64; +var hi, lo, z, w, s1, s2: F64; +begin + if x < 0.4375 then + hi := 0.0; lo := 0.0; + elsif x < 0.6875 then + hi := 4.63647609000806093515E-01; lo := 2.26987774529616870924E-17; + x := (2.0 * x - 1.0) / (2.0 + x); + elsif x < 1.1875 then + hi := 7.85398163397448278999E-01; lo := 3.06161699786838301793E-17; + x := (x - 1.0) / (x + 1.0); + elsif x < 2.4375 then + hi := 9.82793723247329054082E-01; lo := 1.39033110312309984516E-17; + x := (x - 1.5) / (1.0 + 1.5 * x); + else + hi := 1.57079632679489655800E+00; lo := 6.12323399573676603587E-17; + x := -1.0 / x; + end; + z := x * x; + w := z * z; + s1 := z * (3.33333333333329318027E-01 + w * (1.42857142725034663711E-01 + w * (9.09088713343650656196E-02 + + w * (6.66107313738753120669E-02 + w * (4.97687799461593236017E-02 + w * 1.62858201153657823623E-02))))); + s2 := w * (-1.99999999998764832476E-01 + w * (-1.11111104054623557880E-01 + w * (-7.69187620504482999495E-02 + + w * (-5.83357013379057348645E-02 - w * 3.65315727442169155270E-02)))); + return hi - ((x * (s1 + s2) - lo) - x); +end; + +(* The angle of the point (x, y) from the x axis, from -pi to pi. *) +proc atan2*(y, x: F64): F64; +var a: F64; (* the angle from the x axis on x's side, at least 0 *) +begin + if (x # x) or (y # y) then return x + y; end; + if y = 0.0 then + if not negative(x) then return y; end; + a := pi; + else + if ((x - x) # 0.0) and ((y - y) # 0.0) then a := pi / 4.0; (* both infinite *) + else + a := y / x; + if a < 0.0 then a := -a; end; + a := atan(a); + end; + (* pi less a, with what pi lacks of its true value *) + if negative(x) then a := pi - (a - 1.2246467991473531772E-16); end; + end; + if negative(y) then return -a; end; + return a; +end; + +(* The module's test: values C's library gives, to within two units in + the last place, and the edges. *) +proc near(got, want: F64): BOOL; +var d: F64; +begin + d := got - want; + if d < 0.0 then d := -d; end; + if want < 0.0 then want := -want; end; + return d <= want * 4.5E-16; +end; + +proc main*; +var inf, nan, hard: F64; +begin + inf := 1.0 / 0.0; + nan := inf - inf; + hard := scale(6381956970095103.0, 797); (* of all F64s, the nearest a multiple of pi/2 *) + if (sqrt(2.0) # 1.4142135623730951) or (sqrt(0.0) # 0.0) or (sqrt(-1.0) = sqrt(-1.0)) then Rt.stop("Math.sqrt"); end; + if (floor(2.5) # 2.0) or (floor(-2.5) # -3.0) or (floor(-2.0) # -2.0) or (floor(1.0E300) # 1.0E300) + or not negative(floor(-0.0)) or (floor(nan) = floor(nan)) then Rt.stop("Math.floor"); end; + if not near(exp(1.0), 2.718281828459045) or not near(exp(-3.5), 0.0301973834223185) + or not near(exp(700.0), 1.0142320547350045E304) or not near(exp(-740.0), 4.2E-322) + or (exp(0.0) # 1.0) or (exp(710.0) # inf) or (exp(-746.0) # 0.0) or (exp(-inf) # 0.0) then Rt.stop("Math.exp"); end; + if not near(ln(10.0), 2.302585092994046) or not near(ln(0.3), -1.2039728043259361) + or not near(ln(1.0E-310), -713.8013788281542) or (ln(1.0) # 0.0) or (ln(0.0) # -inf) + or (ln(inf) # inf) or (ln(-1.0) = ln(-1.0)) then Rt.stop("Math.ln"); end; + if not near(sin(1.0), 0.8414709848078965) or not near(sin(-100.0), 0.5063656411097588) + or not near(sin(pi), 1.2246467991473532E-16) or not near(sin(1.0E6), -0.34999350217129294) + or not near(sin(1.0E22), -0.8522008497671888) or not negative(sin(-0.0)) + or (sin(inf) = sin(inf)) then Rt.stop("Math.sin"); end; + if not near(cos(1.0), 0.5403023058681398) or not near(cos(-100.0), 0.8623188722876839) + or not near(cos(pi / 2.0), 6.123233995736766E-17) or not near(cos(1.0E6), 0.9367521275331447) + or not near(cos(1.0E300), -0.5753861119575491) or not near(cos(hard), -4.687165924254628E-19) + or (cos(0.0) # 1.0) or (cos(nan) = cos(nan)) then Rt.stop("Math.cos"); end; + if not near(atan2(1.0, 2.0), 0.4636476090008061) or not near(atan2(-3.0, -4.0), -2.498091544796509) + or not near(atan2(5.0, 0.1), 1.550798992821746) or not near(atan2(1.0, -1.0E-20), 1.5707963267948966) + or (atan2(0.0, -1.0) # pi) or not negative(atan2(-0.0, 1.0)) or (atan2(-inf, inf) # -pi / 4.0) + or not near(atan2(inf, -inf), 2.356194490192345) or (atan2(1.0, 0.0) # pi / 2.0) then Rt.stop("Math.atan2"); end; +end; + +end Math. diff --git a/lib/Sort.raz b/lib/Sort.raz new file mode 100644 index 0000000..7398425 --- /dev/null +++ b/lib/Sort.raz @@ -0,0 +1,35 @@ +(* Sorting a slice in place, in the order less gives: + import ByAge := Sort(Person, younger); + It is a heapsort: no memory of its own, and n log n steps at most, + whatever the order it starts in. Two elements equal by less may + change places. *) +module Sort(T; less: proc(a, b: T): BOOL); + +(* The element at i sinks through s[0..n], a heap with the largest at + its root, to where it is no smaller than its children, 2i+1 and + 2i+2. *) +proc sink(s: []T; i, n: I64); +var c: I64; t: T; +begin + c := 2 * i + 1; + while c < n do + if (c + 1 < n) and less(s[c], s[c + 1]) then INC(c); end; + if not less(s[i], s[c]) then return; end; + t := s[i]; s[i] := s[c]; s[c] := t; + i := c; + c := 2 * i + 1; + end; +end; + +(* s made a heap, then its largest taken, in turn, to the end. *) +proc sort*(s: []T); +var i: I64; t: T; +begin + for i := LEN(s) div 2 - 1 to 0 by -1 do sink(s, i, LEN(s)); end; + for i := LEN(s) - 1 to 1 by -1 do + t := s[0]; s[0] := s[i]; s[i] := t; + sink(s, 0, i); + end; +end; + +end Sort. diff --git a/lib/Str.raz b/lib/Str.raz index 7519b07..324b9d8 100644 --- a/lib/Str.raz +++ b/lib/Str.raz @@ -1,7 +1,10 @@ (* Operations on strings, which are []U8. = and # compare them; this - module orders, searches and hashes them. *) + module orders, searches and hashes them, reads and writes their + UTF-8, and reads a number from one. *) module Str; import Rt; + +const least = -9223372036854775807 - 1; (* the smallest I64 *) (* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *) proc cmp*(a, b: []U8): I64; @@ -51,6 +54,154 @@ return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p); end; +(* c in UTF-8: its bytes, and how many. A number that isn't a + character, a surrogate or one past 10FFFFH, becomes FFFDH, the + character that stands for a wrong one. *) +proc encode*(c: I64): ([4]U8, I64); +var b: [4]U8; +begin + if (c < 0) or (c > 10FFFFH) or (c >= 0D800H) and (c <= 0DFFFH) then c := 0FFFDH; end; + if c < 80H then + b[0] := U8(c); + return b, 1; + elsif c < 800H then + b[0] := U8(0C0H + (c shr 6)); + b[1] := U8(80H + (c & 3FH)); + return b, 2; + elsif c < 10000H then + b[0] := U8(0E0H + (c shr 12)); + b[1] := U8(80H + (c shr 6 & 3FH)); + b[2] := U8(80H + (c & 3FH)); + return b, 3; + end; + b[0] := U8(0F0H + (c shr 18)); + b[1] := U8(80H + (c shr 12 & 3FH)); + b[2] := U8(80H + (c shr 6 & 3FH)); + b[3] := U8(80H + (c & 3FH)); + return b, 4; +end; + +(* The character s starts with, and its length in bytes: FFFDH and 1 + if its first byte doesn't start one rightly, being a continuation, + or followed by too few continuations, or spelling a surrogate or a + character in more bytes than it needs; 0 and 0 if s is empty. *) +proc decode*(s: []U8): (I64, I64); +var c, n, least, i: I64; +begin + if LEN(s) = 0 then return 0, 0; end; + c := I64(s[0]); + if c < 80H then return c, 1; + elsif c < 0C0H then return 0FFFDH, 1; + elsif c < 0E0H then n := 2; c := c & 1FH; least := 80H; + elsif c < 0F0H then n := 3; c := c & 0FH; least := 800H; + elsif c < 0F8H then n := 4; c := c & 7H; least := 10000H; + else return 0FFFDH, 1; + end; + if LEN(s) < n then return 0FFFDH, 1; end; + for i := 1 to n - 1 do + if s[i] & 0C0H # 80H then return 0FFFDH, 1; end; + c := c shl 6 + I64(s[i] & 3FH); + end; + if (c < least) or (c > 10FFFFH) or (c >= 0D800H) and (c <= 0DFFFH) then return 0FFFDH, 1; end; + return c, n; +end; + +(* s as a decimal number, with a - or + before it if any, and nothing + else; false if it isn't one, or an I64 can't hold it. *) +proc toInt*(s: []U8): (I64, BOOL); +var n, i, d: I64; neg: BOOL; +begin + neg := (LEN(s) > 0) and (s[0] = '-'); + if (LEN(s) > 0) and ((s[0] = '-') or (s[0] = '+')) then i := 1; end; + if i = LEN(s) then return 0, false; end; + (* the digits are taken off below zero, since the smallest I64 has no positive *) + while i < LEN(s) do + if (s[i] < '0') or (s[i] > '9') then return 0, false; end; + d := I64(s[i] - '0'); + if n < (least + d) div 10 then return 0, false; end; + n := n * 10 - d; + INC(i); + end; + if not neg then + if n = least then return 0, false; end; + n := -n; + end; + return n, true; +end; + +proc testUtf8; +var b: [4]U8; n, c, i: I64; +begin + b, n := encode('a'); + if (n # 1) or (b[0] # 'a') then Rt.stop("Str.encode: a"); end; + b, n := encode(0E9H); + if b[0..n] # "é" then Rt.stop("Str.encode: é"); end; + b, n := encode(20ACH); + if b[0..n] # "€" then Rt.stop("Str.encode: €"); end; + b, n := encode(1F600H); + if b[0..n] # "😀" then Rt.stop("Str.encode: 😀"); end; + b, n := encode(0D800H); + if b[0..n] # "\u{FFFD}" then Rt.stop("Str.encode: a surrogate"); end; + b, n := encode(110000H); + if n # 3 then Rt.stop("Str.encode: past 10FFFFH"); end; + (* every character back through decode *) + for i := 0 to 10FFFFH do + if (i < 0D800H) or (i > 0DFFFH) then + b, n := encode(i); + c, n := decode(b[0..n]); + if c # i then Rt.stop("Str.decode: not what encode wrote"); end; + end; + end; + c, n := decode(""); + if (c # 0) or (n # 0) then Rt.stop("Str.decode: empty"); end; + c, n := decode("é!"); + if (c # 0E9H) or (n # 2) then Rt.stop("Str.decode: é"); end; + b := [80H, 'a', 0, 0]; + c, n := decode(b[0..2]); + if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: a continuation"); end; + b := [0E2H, 82H, 'a', 0]; + c, n := decode(b[0..3]); + if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: too few continuations"); end; + c, n := decode(b[0..2]); + if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: cut short"); end; + b := [0C0H, 0AFH, 0, 0]; + c, n := decode(b[0..2]); + if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: overlong"); end; + b := [0EDH, 0A0H, 80H, 0]; + c, n := decode(b[0..3]); + if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: a surrogate"); end; + b := [0F4H, 90H, 80H, 80H]; + c, n := decode(b); + if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: past 10FFFFH"); end; +end; + +proc testToInt; +var n: I64; ok: BOOL; +begin + n, ok := toInt("42"); + if not ok or (n # 42) then Rt.stop("Str.toInt: 42"); end; + n, ok := toInt("-17"); + if not ok or (n # -17) then Rt.stop("Str.toInt: -17"); end; + n, ok := toInt("+0"); + if not ok or (n # 0) then Rt.stop("Str.toInt: +0"); end; + n, ok := toInt("9223372036854775807"); + if not ok or (n # 9223372036854775807) then Rt.stop("Str.toInt: the largest"); end; + n, ok := toInt("-9223372036854775808"); + if not ok or (n # least) then Rt.stop("Str.toInt: the smallest"); end; + n, ok := toInt("9223372036854775808"); + if ok then Rt.stop("Str.toInt: past the largest"); end; + n, ok := toInt("-9223372036854775809"); + if ok then Rt.stop("Str.toInt: past the smallest"); end; + n, ok := toInt(""); + if ok then Rt.stop("Str.toInt: empty"); end; + n, ok := toInt("-"); + if ok then Rt.stop("Str.toInt: a sign alone"); end; + n, ok := toInt("12a"); + if ok then Rt.stop("Str.toInt: a letter"); end; + n, ok := toInt(" 1"); + if ok then Rt.stop("Str.toInt: a space"); end; +end; + (* The module's test: stops the program if something is wrong. *) proc main*; begin @@ -61,6 +212,8 @@ if (find("hello", "ll") # 2) or (find("hello", "x") # -1) or (find("", "") # 0) or (find("ab", "abc") # -1) then Rt.stop("Str.find"); end; if not hasPrefix("hello", "he") or hasPrefix("he", "hello") then Rt.stop("Str.hasPrefix"); end; + testUtf8; + testToInt; end; end Str. diff --git a/test/doc/Str.expect b/test/doc/Str.expect index f44b026..9522e08 100644 --- a/test/doc/Str.expect +++ b/test/doc/Str.expect @@ -1,6 +1,7 @@ module Str; Operations on strings, which are []U8. = and # compare them; this - module orders, searches and hashes them. + module orders, searches and hashes them, reads and writes their + UTF-8, and reads a number from one. proc cmp*(a, b: []U8): I64; -1, 0 or 1 as a sorts before, with or after b, byte by byte. @@ -14,6 +15,21 @@ Where sub first starts in s, or -1. proc hasPrefix*(s, p: []U8): BOOL; + +proc encode*(c: I64): ([4]U8, I64); + c in UTF-8: its bytes, and how many. A number that isn't a + character, a surrogate or one past 10FFFFH, becomes FFFDH, the + character that stands for a wrong one. + +proc decode*(s: []U8): (I64, I64); + The character s starts with, and its length in bytes: FFFDH and 1 + if its first byte doesn't start one rightly, being a continuation, + or followed by too few continuations, or spelling a surrogate or a + character in more bytes than it needs; 0 and 0 if s is empty. + +proc toInt*(s: []U8): (I64, BOOL); + s as a decimal number, with a - or + before it if any, and nothing + else; false if it isn't one, or an I64 can't hold it. proc main*; The module's test: stops the program if something is wrong. diff --git a/test/run/MapRemove.expect b/test/run/MapRemove.expect new file mode 100644 index 0000000..2d3431b --- /dev/null +++ b/test/run/MapRemove.expect @@ -0,0 +1,2 @@ +341 entries, 341 of them, summing 6658308 +walked 341, summing 6658308 diff --git a/test/run/MapRemove.raz b/test/run/MapRemove.raz new file mode 100644 index 0000000..75277f8 --- /dev/null +++ b/test/run/MapRemove.raz @@ -0,0 +1,56 @@ +(* Map's remove and next, against an array that holds the same: keys + hashed into runs of eight, so that removing moves entries back, + around the end of the slots too. *) +module MapRemove; +import Fmt, Heap, Rt, Ints := Map(I64, I64, near, same); + +const N = 500; + +proc near(k: I64): U64; +begin + return U64(k div 8 * 977); +end; + +proc same(a, b: I64): BOOL; +begin + return a = b; +end; + +proc main*; +var + m: Ints.Map; want: [N]I64; i, k, v, n, sum, seed: I64; + found, _ok: BOOL; +begin + Ints.init(ADR(m), Heap.heap); + seed := 1; + for i := 1 to 20000 do + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + k := seed mod N; + if seed div N mod 3 = 0 then + if Ints.remove(ADR(m), k) # (want[k] # 0) then Rt.stop("remove: wrong answer"); end; + want[k] := 0; + else + _ok := Ints.put(ADR(m), k, i); + want[k] := i; + end; + end; + for k := 0 to N - 1 do + v, found := Ints.get(ADR(m), k); + if (found # (want[k] # 0)) or (v # want[k]) then Rt.stop("get: not what was put"); end; + if found then INC(n); INC(sum, v); end; + end; + if Ints.remove(ADR(m), N) then Rt.stop("remove: a key never put"); end; + Fmt.print("{} entries, {} of them, summing {}\n", [Fmt.int(m.len), Fmt.int(n), Fmt.int(sum)]); + (* the walk sees each entry once *) + n := 0; sum := 0; + i, k, v := Ints.next(ADR(m), 0); + while i >= 0 do + if want[k] # v then Rt.stop("next: not what was put"); end; + want[k] := 0; + INC(n); INC(sum, v); + i, k, v := Ints.next(ADR(m), i); + end; + Fmt.print("walked {}, summing {}\n", [Fmt.int(n), Fmt.int(sum)]); +end; + +end MapRemove. diff --git a/test/run/Sorted.expect b/test/run/Sorted.expect new file mode 100644 index 0000000..f87c5ce --- /dev/null +++ b/test/run/Sorted.expect @@ -0,0 +1,4 @@ +Bo 7 +Di 23 +Ana 41 +Cy 90 diff --git a/test/run/Sorted.raz b/test/run/Sorted.raz new file mode 100644 index 0000000..9658ae9 --- /dev/null +++ b/test/run/Sorted.raz @@ -0,0 +1,51 @@ +(* Sort: slices in many orders and of every length up to 40 come out + in order, holding what they held; and a sort by a record's field. *) +module Sorted; +import Fmt, Rt, Ints := Sort(I64, below), ByAge := Sort(Person, younger); + +type Person = record name: []U8; age: I64; end; + +proc below(a, b: I64): BOOL; +begin + return a < b; +end; + +proc younger(a, b: Person): BOOL; +begin + return a.age < b.age; +end; + +proc main*; +var + a: [40]I64; count: [10]I64; n, i, kind, seed: I64; + people: [4]Person; +begin + seed := 7; + for n := 0 to 40 do + for kind := 0 to 3 do + for i := 0 to 9 do count[i] := 0; end; + for i := 0 to n - 1 do + seed := (seed * 1103515245 + 12345) & 7FFFFFFFH; + if kind = 0 then a[i] := seed mod 10; (* at random, with repeats *) + elsif kind = 1 then a[i] := i mod 10; (* rising *) + elsif kind = 2 then a[i] := 9 - i mod 10; (* falling *) + else a[i] := 5; (* all equal *) + end; + INC(count[a[i]]); + end; + Ints.sort(a[0..n]); + for i := 0 to n - 1 do + if (i > 0) and (a[i - 1] > a[i]) then Rt.stop("out of order"); end; + DEC(count[a[i]]); + end; + for i := 0 to 9 do + if count[i] # 0 then Rt.stop("not what it held"); end; + end; + end; + end; + people := [{name: "Ana", age: 41}, {name: "Bo", age: 7}, {name: "Cy", age: 90}, {name: "Di", age: 23}]; + ByAge.sort(people); + for i := 0 to 3 do Fmt.print("{} {}\n", [Fmt.str(people[i].name), Fmt.int(people[i].age)]); end; +end; + +end Sorted.