From: Mark Wooding Date: Tue, 15 May 2018 10:44:56 +0000 (+0100) Subject: test/: Add a simple rational-number class. X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~mdw/git/sod/commitdiff_plain/e9be9d868bddf4638c3d055e9f86022f3982ce25 test/: Add a simple rational-number class. This found a surprising number of bugs. I wasn't even intending for it to be a test, but it seems to work well as one. --- diff --git a/test/Makefile.am b/test/Makefile.am index 5c4d59d..de5b634 100644 --- a/test/Makefile.am +++ b/test/Makefile.am @@ -58,4 +58,13 @@ check-local:: kwtest kwtest.ref ./kwtest >kwtest.out diff -u $(srcdir)/kwtest.ref kwtest.out +check_PROGRAMS += rat + +EXTRA_DIST += rat.sod rat.ref +nodist_rat_SOURCES = rat.c rat.h +BUILT_SOURCES += $(nodist_rat_SOURCES) +check-local:: rat rat.ref + ./rat >rat.out + diff -u $(srcdir)/rat.ref rat.out + ###----- That's all, folks -------------------------------------------------- diff --git a/test/rat.ref b/test/rat.ref new file mode 100644 index 0000000..2f3b0f6 --- /dev/null +++ b/test/rat.ref @@ -0,0 +1,3 @@ +0/1 +6/1 +2/3 diff --git a/test/rat.sod b/test/rat.sod new file mode 100644 index 0000000..178e896 --- /dev/null +++ b/test/rat.sod @@ -0,0 +1,53 @@ +/* -*-sod-*- */ + +code c: includes { +#include +#include + +#include "rat.h" +} + +code h: includes { +#include "sod.h" +} + +typename FILE; + +code c: early_user { + static int gcd(int x, int y) + { + int t; + if (x < 0) x = -x; + if (y < 0) y = -y; + while (y) { t = x%y; x = y; y = t; } + return (x); + } +} + +[nick = rat, link = SodObject] +class Rational: SodObject { + int num, den; + initarg int num = 0, den = 1; + init { + int g; + assert(den); + g = gcd(num, den); + me->rat.num = num/g; + me->rat.den = den/g; + } + + void print(FILE *fp) { fprintf(fp, "%d/%d\n", me->rat.num, me->rat.den); } +} + +code c: user { + int main(void) + { + SOD_DECL(Rational, r0, KWARGS(K(den, 9))); + SOD_DECL(Rational, r1, KWARGS(K(num, 6))); + SOD_DECL(Rational, r2, KWARGS(K(num, 6) K(den, 9))); + Rational_print(r0, stdout); + Rational_print(r1, stdout); + Rational_print(r2, stdout); + return (0); + } +}