@pkmn/engine 0.1.0-dev.1220fbc5 → 0.1.0-dev.130de754

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +46 -30
  3. package/build/pkg/addon/browser.d.ts +3 -0
  4. package/build/pkg/addon/browser.js +47 -0
  5. package/build/pkg/addon/browser.js.map +1 -0
  6. package/build/pkg/addon/node.d.ts +3 -0
  7. package/build/pkg/addon/node.js +110 -0
  8. package/build/pkg/addon/node.js.map +1 -0
  9. package/build/pkg/addon/wasm.d.ts +2 -0
  10. package/build/pkg/addon/wasm.js +53 -0
  11. package/build/pkg/addon/wasm.js.map +1 -0
  12. package/build/pkg/addon.d.ts +26 -4
  13. package/build/pkg/addon.js +39 -71
  14. package/build/pkg/addon.js.map +1 -1
  15. package/build/pkg/data/layout.json +15 -2
  16. package/build/pkg/data/protocol.json +23 -9
  17. package/build/pkg/data.d.ts +27 -5
  18. package/build/pkg/data.js.map +1 -1
  19. package/build/pkg/gen1.d.ts +15 -18
  20. package/build/pkg/gen1.js +28 -19
  21. package/build/pkg/gen1.js.map +1 -1
  22. package/build/pkg/index.d.ts +42 -91
  23. package/build/pkg/index.js +23 -70
  24. package/build/pkg/index.js.map +1 -1
  25. package/build/pkg/protocol.d.ts +29 -1
  26. package/build/pkg/protocol.js +109 -107
  27. package/build/pkg/protocol.js.map +1 -1
  28. package/build/tools/debug.js +84 -73
  29. package/build/tools/debug.js.map +1 -1
  30. package/build/tools/display/debug.jsx +66 -0
  31. package/build/tools/display/debug.jsx.map +1 -0
  32. package/build/tools/display/index.js +152 -0
  33. package/build/tools/display/index.js.map +1 -0
  34. package/build/tools/display/ui.jsx +360 -0
  35. package/build/tools/display/ui.jsx.map +1 -0
  36. package/build/tools/display/util.js +157 -0
  37. package/build/tools/display/util.js.map +1 -0
  38. package/build.zig +310 -203
  39. package/package.json +59 -132
  40. package/src/bin/install-pkmn-engine +70 -53
  41. package/src/bin/pkmn-debug +1 -1
  42. package/src/lib/bindings/c.zig +201 -0
  43. package/src/lib/{binding → bindings}/node.zig +15 -32
  44. package/src/lib/bindings/wasm.zig +51 -0
  45. package/src/lib/common/array.zig +70 -0
  46. package/src/lib/common/data.zig +4 -4
  47. package/src/lib/common/debug.zig +46 -30
  48. package/src/lib/common/js.zig +5 -9
  49. package/src/lib/common/optional.zig +21 -22
  50. package/src/lib/common/options.zig +6 -0
  51. package/src/lib/common/protocol.zig +573 -541
  52. package/src/lib/common/rational.zig +340 -254
  53. package/src/lib/common/rng.zig +11 -13
  54. package/src/lib/common/util.zig +53 -1
  55. package/src/lib/gen1/calc.zig +724 -175
  56. package/src/lib/gen1/chance.zig +494 -308
  57. package/src/lib/gen1/data/moves.zig +2 -4
  58. package/src/lib/gen1/data/species.zig +2 -4
  59. package/src/lib/gen1/data/types.zig +3 -4
  60. package/src/lib/gen1/data.zig +49 -49
  61. package/src/lib/gen1/helpers.zig +115 -562
  62. package/src/lib/gen1/mechanics.zig +603 -489
  63. package/src/lib/gen2/calc.zig +35 -28
  64. package/src/lib/gen2/chance.zig +122 -518
  65. package/src/lib/gen2/data/items.zig +1 -3
  66. package/src/lib/gen2/data/moves.zig +2 -4
  67. package/src/lib/gen2/data/species.zig +1 -3
  68. package/src/lib/gen2/data/types.zig +7 -5
  69. package/src/lib/gen2/data.zig +40 -39
  70. package/src/lib/gen2/generated.zig +30 -47
  71. package/src/lib/gen2/helpers.zig +68 -39
  72. package/src/lib/gen2/mechanics.zig +853 -533
  73. package/src/lib/napi.h +2 -0
  74. package/src/lib/node.zig +14 -0
  75. package/src/lib/pkmn.zig +123 -29
  76. package/src/lib/wasm.zig +12 -0
  77. package/src/tools/display/dom.ts +108 -0
  78. package/src/tools/display/ui.css +354 -0
  79. package/build/test/display.js +0 -400
  80. package/build/test/display.js.map +0 -1
  81. package/src/lib/binding/wasm.zig +0 -12
  82. package/src/lib/gen1/README.md +0 -894
  83. package/src/lib/gen2/README.md +0 -330
  84. package/src/test/display/pkmn.html.tmpl +0 -368
@@ -1,4 +1,3 @@
1
- const builtin = @import("builtin");
2
1
  const std = @import("std");
3
2
 
4
3
  const assert = std.debug.assert;
@@ -8,9 +7,27 @@ const expectError = std.testing.expectError;
8
7
 
9
8
  /// Specialization of a rational number used by the engine to compute probabilties.
10
9
  /// For performance reasons the rational is only reduced lazily and thus `reduce` must be
11
- /// invoked explicitly before reading.
10
+ /// invoked explicitly before reading. Note that this laziness means that this implementation
11
+ /// sometimes overflows in places where an eager reduced implementation would not - to achieve
12
+ /// the same behavior as an eager implementation simply call `reduce` after each operation.
12
13
  pub fn Rational(comptime T: type) type {
13
- return extern struct {
14
+ // With floats we can't rely on an overflow bit to let us know when to reduce, so we
15
+ // instead start reducing when we get sufficiently close to the limit of the mantissa
16
+ // (in our domain we expect updates to involve numbers < 2**10, so we should be safe
17
+ // not reducing before we are 2**10 away from "overflowing" the mantissa)
18
+ const o = if (@typeInfo(T) == .float)
19
+ std.math.pow(T, 2, std.math.floatMantissaBits(T) - 10)
20
+ else
21
+ 0;
22
+
23
+ const Err = switch (@typeInfo(T)) {
24
+ .int => error{Overflow},
25
+ .float => error{},
26
+ else => unreachable,
27
+ };
28
+
29
+ // Zig doesn't allow integers > u128 in an extern struct...
30
+ return if (@sizeOf(T) <= 16) extern struct {
14
31
  const Self = @This();
15
32
 
16
33
  /// Numerator. Must always be >= 1. Not guaranteed to be reduced in all cases.
@@ -18,21 +35,8 @@ pub fn Rational(comptime T: type) type {
18
35
  /// Denominator. Must always be >= 1. Not guaranteed to be reduced in all cases.
19
36
  q: T = 1,
20
37
 
21
- // With floats we can't rely on an overflow bit to let us know when to reduce, so we instead
22
- // start reducing when we get sufficiently close to the limit of the mantissa (in our domain
23
- // we expect updates to involve numbers < 2**10, so we should be safe not reducing before we
24
- // are 2**10 away from "overflowing" the mantissa)
25
- const REDUCE = if (@typeInfo(T) == .Float)
26
- std.math.pow(T, 2, std.math.floatMantissaBits(T) - 10)
27
- else
28
- 0;
29
-
30
38
  /// Possible error returned by operations on the Rational.
31
- pub const Error = switch (@typeInfo(T)) {
32
- .Int => error{Overflow},
33
- .Float => error{},
34
- else => unreachable,
35
- };
39
+ pub const Error = Err;
36
40
 
37
41
  /// Resets the rational back to 1.
38
42
  pub fn reset(r: *Self) void {
@@ -43,182 +47,327 @@ pub fn Rational(comptime T: type) type {
43
47
  /// Update the rational by multiplying its numerator by p and its denominator by q.
44
48
  /// Both p and q must be >= 1, and if computable at comptime must have no common factors.
45
49
  pub fn update(r: *Self, p: anytype, q: anytype) Error!void {
46
- // FIXME
47
- // std.debug.print("({d}/{d}) * ", .{p, q});
48
- assert(p >= 1);
49
- assert(q >= 1);
50
-
51
- // If our parameters are not fully reduced they may prematurely
52
- // cause overflow/loss of precision after the multiplication below
53
- assert(switch (@typeInfo(@TypeOf(p, q))) {
54
- .ComptimeInt, .ComptimeFloat => comptime gcd(p, q),
55
- else => 1,
56
- } == 1);
57
-
58
- switch (@typeInfo(T)) {
59
- .Int => {
60
- // Greedily attempt to multiply and if it fails, reduce and try again
61
- r.multiplication(p, q) catch |err| switch (err) {
62
- error.Overflow => {
63
- r.reduce();
64
- try r.multiplication(p, q);
65
- },
66
- else => unreachable,
67
- };
68
- },
69
- .Float => {
70
- // Reduce in situations where we're likely to start losing precision
71
- if (r.q > REDUCE or r.p > REDUCE) r.reduce();
72
-
73
- r.p *= switch (@typeInfo(@TypeOf(p))) {
74
- .Float, .ComptimeFloat => p,
75
- else => @floatFromInt(p),
76
- };
77
- r.q *= switch (@typeInfo(@TypeOf(q))) {
78
- .Float, .ComptimeFloat => q,
79
- else => @floatFromInt(q),
80
- };
81
-
82
- // We should always be dealing with whole numbers
83
- assert(std.math.modf(r.p).fpart == 0);
84
- assert(std.math.modf(r.q).fpart == 0);
85
- },
86
- else => unreachable,
87
- }
50
+ return update_(T, o, r, p, q);
88
51
  }
89
52
 
90
53
  /// Add two rationals using the identity (a/b) + (c/d) = (ad+bc)/(bd).
91
- pub fn add(r: *Self, s: *Self) Error!void {
92
- switch (@typeInfo(T)) {
93
- .Int => {
94
- if (r.q == s.q) {
95
- r.p = std.math.add(T, r.p, s.p) catch |err| switch (err) {
96
- error.Overflow => val: {
97
- r.reduce();
98
- s.reduce();
99
- break :val try std.math.add(T, r.p, s.p);
100
- },
101
- else => unreachable,
102
- };
103
- } else {
104
- r.addition(s.p, s.q) catch |err| switch (err) {
105
- error.Overflow => {
106
- r.reduce();
107
- s.reduce();
108
- try r.addition(s.p, s.q);
109
- },
110
- else => unreachable,
111
- };
112
- }
113
- },
114
- .Float => {
115
- if (r.q == s.q) {
116
- if (r.p > REDUCE) r.reduce();
117
- if (s.p > REDUCE) s.reduce();
118
-
119
- r.p += s.p;
120
- } else {
121
- // Always reduce to minimize loss of precision from the multiplications
122
- r.reduce();
123
- s.reduce();
124
-
125
- r.p = (r.p * s.q) + (r.q * s.p);
126
- r.q *= s.q;
127
- }
128
-
129
- assert(std.math.modf(r.p).fpart == 0);
130
- assert(std.math.modf(r.q).fpart == 0);
131
- },
132
- else => unreachable,
133
- }
54
+ pub fn add(r: *Self, s: anytype) Error!void {
55
+ return add_(T, o, r, s);
134
56
  }
135
57
 
136
58
  /// Multiplies two rationals.
137
- pub fn mul(r: *Self, s: *Self) Error!void {
138
- switch (@typeInfo(T)) {
139
- .Int => {
140
- r.multiplication(s.p, s.q) catch |err| switch (err) {
141
- error.Overflow => {
142
- r.reduce();
143
- s.reduce();
144
- try r.multiplication(s.p, s.q);
145
- },
146
- else => unreachable,
147
- };
148
- },
149
- .Float => {
150
- if (r.q > REDUCE or r.p > REDUCE) r.reduce();
151
- if (s.q > REDUCE or s.p > REDUCE) s.reduce();
152
-
153
- r.p *= s.p;
154
- r.q *= s.q;
59
+ pub fn mul(r: *Self, s: anytype) Error!void {
60
+ return mul_(T, o, r, s);
61
+ }
155
62
 
156
- assert(std.math.modf(r.p).fpart == 0);
157
- assert(std.math.modf(r.q).fpart == 0);
158
- },
159
- else => unreachable,
160
- }
63
+ /// Compares two rationals using the identity (a/b) > (c/d) => ad > bc
64
+ pub fn cmp(r: *Self, s: anytype) Error!std.math.Order {
65
+ return cmp_(T, o, r, s);
161
66
  }
162
67
 
163
68
  /// Normalize the rational by reducing by the greatest common divisor.
164
69
  pub fn reduce(r: *Self) void {
165
- const d = gcd(r.p, r.q);
166
- if (d == 1) return;
70
+ reduce_(r);
71
+ }
72
+
73
+ pub fn format(self: Self, writer: *std.Io.Writer) !void {
74
+ try writer.print("{d}/{d}", .{ self.p, self.q });
75
+ }
76
+ } else struct {
77
+ const Self = @This();
167
78
 
168
- assert(@mod(r.p, d) == 0);
169
- assert(@mod(r.q, d) == 0);
79
+ /// Numerator. Must always be >= 1. Not guaranteed to be reduced in all cases.
80
+ p: T = 1,
81
+ /// Denominator. Must always be >= 1. Not guaranteed to be reduced in all cases.
82
+ q: T = 1,
170
83
 
171
- r.p /= d;
172
- r.q /= d;
84
+ /// Possible error returned by operations on the Rational.
85
+ pub const Error = Err;
173
86
 
174
- assert(r.p >= 1);
175
- assert(r.q >= 1);
87
+ /// Resets the rational back to 1.
88
+ pub fn reset(r: *Self) void {
89
+ r.p = 1;
90
+ r.q = 1;
176
91
  }
177
92
 
178
- pub fn format(
179
- self: Self,
180
- comptime fmt: []const u8,
181
- opts: std.fmt.FormatOptions,
182
- writer: anytype,
183
- ) !void {
184
- _ = .{ fmt, opts };
185
- try writer.print("{d}/{d}", .{ self.p, self.q });
93
+ /// Update the rational by multiplying its numerator by p and its denominator by q.
94
+ /// Both p and q must be >= 1, and if computable at comptime must have no common factors.
95
+ pub fn update(r: *Self, p: anytype, q: anytype) Error!void {
96
+ return update_(T, o, r, p, q);
97
+ }
98
+
99
+ /// Add two rationals using the identity (a/b) + (c/d) = (ad+bc)/(bd).
100
+ pub fn add(r: *Self, s: anytype) Error!void {
101
+ return add_(T, o, r, s);
102
+ }
103
+
104
+ /// Multiplies two rationals.
105
+ pub fn mul(r: *Self, s: anytype) Error!void {
106
+ return mul_(T, o, r, s);
186
107
  }
187
108
 
188
- fn multiplication(r: *Self, p: anytype, q: anytype) !void {
189
- r.p = try std.math.mul(T, r.p, p);
190
- r.q = try std.math.mul(T, r.q, q);
109
+ /// Compares two rationals using the identity (a/b) > (c/d) => ad > bc
110
+ pub fn cmp(r: *Self, s: anytype) Error!std.math.Order {
111
+ return cmp_(T, o, r, s);
191
112
  }
192
113
 
193
- fn addition(r: *Self, p: anytype, q: anytype) !void {
194
- // (a/b) + (c/d) = (ad+bc)/(bd)
195
- var d = try std.math.mul(T, r.q, q);
196
- var n1 = try std.math.mul(T, r.p, q);
197
- var n2 = try std.math.mul(T, r.q, p);
114
+ /// Normalize the rational by reducing by the greatest common divisor.
115
+ pub fn reduce(r: *Self) void {
116
+ reduce_(r);
117
+ }
198
118
 
199
- r.p = try std.math.add(T, n1, n2);
200
- r.q = d;
119
+ pub fn format(self: Self, writer: *std.Io.Writer) !void {
120
+ try writer.print("{d}/{d}", .{ self.p, self.q });
201
121
  }
202
122
  };
203
123
  }
204
124
 
205
- // https://en.wikipedia.org/wiki/Euclidean_algorithm
125
+ fn update_(comptime T: type, comptime o: comptime_int, r: anytype, p: anytype, q: anytype) !void {
126
+ // std.debug.print("({d}/{d}) * ", .{ p, q }); // DEBUG
127
+ assert(p >= 1);
128
+ assert(q >= 1);
129
+
130
+ // If our parameters are not fully reduced they may prematurely
131
+ // cause overflow/loss of precision after the multiplication below
132
+ assert(switch (@typeInfo(@TypeOf(p, q))) {
133
+ .comptime_int, .comptime_float => comptime gcd(p, q),
134
+ else => 1,
135
+ } == 1);
136
+
137
+ switch (@typeInfo(T)) {
138
+ .int => {
139
+ // Greedily attempt to multiply and if it fails, reduce and try again
140
+ multiplication(T, r, p, q) catch |err| switch (err) {
141
+ error.Overflow => {
142
+ r.reduce();
143
+ try multiplication(T, r, p, q);
144
+ },
145
+ else => unreachable,
146
+ };
147
+ },
148
+ .float => {
149
+ // Reduce in situations where we're likely to start losing precision
150
+ if (r.q > o or r.p > o) r.reduce();
151
+
152
+ r.p *= switch (@typeInfo(@TypeOf(p))) {
153
+ .float, .comptime_float => p,
154
+ else => @floatFromInt(p),
155
+ };
156
+ r.q *= switch (@typeInfo(@TypeOf(q))) {
157
+ .float, .comptime_float => q,
158
+ else => @floatFromInt(q),
159
+ };
160
+
161
+ // We should always be dealing with whole numbers
162
+ assert(std.math.modf(r.p).fpart == 0);
163
+ assert(std.math.modf(r.q).fpart == 0);
164
+ },
165
+ else => unreachable,
166
+ }
167
+ }
168
+
169
+ fn add_(comptime T: type, comptime o: comptime_int, r: anytype, s: anytype) !void {
170
+ switch (@typeInfo(T)) {
171
+ .int => {
172
+ if (r.q == s.q) {
173
+ r.p = std.math.add(T, r.p, s.p) catch |err| switch (err) {
174
+ error.Overflow => val: {
175
+ r.reduce();
176
+ s.reduce();
177
+ break :val try std.math.add(T, r.p, s.p);
178
+ },
179
+ else => unreachable,
180
+ };
181
+ } else {
182
+ addition(T, r, s.p, s.q) catch |err| switch (err) {
183
+ error.Overflow => {
184
+ r.reduce();
185
+ s.reduce();
186
+ try addition(T, r, s.p, s.q);
187
+ },
188
+ else => unreachable,
189
+ };
190
+ }
191
+ },
192
+ .float => {
193
+ if (r.q == s.q) {
194
+ if (r.p > o) r.reduce();
195
+ if (s.p > o) s.reduce();
196
+
197
+ r.p += s.p;
198
+ } else {
199
+ // Always reduce to minimize loss of precision from the multiplications
200
+ r.reduce();
201
+ s.reduce();
202
+
203
+ r.p = (r.p * s.q) + (r.q * s.p);
204
+ r.q *= s.q;
205
+ }
206
+
207
+ assert(std.math.modf(r.p).fpart == 0);
208
+ assert(std.math.modf(r.q).fpart == 0);
209
+ },
210
+ else => unreachable,
211
+ }
212
+ }
213
+
214
+ fn mul_(comptime T: type, comptime o: comptime_int, r: anytype, s: anytype) !void {
215
+ switch (@typeInfo(T)) {
216
+ .int => {
217
+ multiplication(T, r, s.p, s.q) catch |err| switch (err) {
218
+ error.Overflow => {
219
+ r.reduce();
220
+ s.reduce();
221
+ try multiplication(T, r, s.p, s.q);
222
+ },
223
+ else => unreachable,
224
+ };
225
+ },
226
+ .float => {
227
+ if (r.q > o or r.p > o) r.reduce();
228
+ if (s.q > o or s.p > o) s.reduce();
229
+
230
+ r.p *= s.p;
231
+ r.q *= s.q;
232
+
233
+ assert(std.math.modf(r.p).fpart == 0);
234
+ assert(std.math.modf(r.q).fpart == 0);
235
+ },
236
+ else => unreachable,
237
+ }
238
+ }
239
+
240
+ fn cmp_(comptime T: type, comptime o: comptime_int, r: anytype, s: anytype) !std.math.Order {
241
+ switch (@typeInfo(T)) {
242
+ .int => {
243
+ const ad = std.math.mul(T, r.p, s.q) catch |err| switch (err) {
244
+ error.Overflow => ad: {
245
+ r.reduce();
246
+ s.reduce();
247
+ break :ad try std.math.mul(T, r.p, s.q);
248
+ },
249
+ else => unreachable,
250
+ };
251
+ const bc = std.math.mul(T, r.q, s.p) catch |err| switch (err) {
252
+ error.Overflow => bc: {
253
+ r.reduce();
254
+ s.reduce();
255
+ break :bc try std.math.mul(T, r.q, s.p);
256
+ },
257
+ else => unreachable,
258
+ };
259
+
260
+ return std.math.order(ad, bc);
261
+ },
262
+ .float => {
263
+ if (r.q > o or r.p > o) r.reduce();
264
+ if (s.q > o or s.p > o) s.reduce();
265
+
266
+ const ad: T = r.p * s.q;
267
+ const bc: T = r.q * s.p;
268
+
269
+ return std.math.order(ad, bc);
270
+ },
271
+ else => unreachable,
272
+ }
273
+ }
274
+
275
+ fn reduce_(r: anytype) void {
276
+ const d = gcd(r.p, r.q);
277
+ if (d == 1) return;
278
+
279
+ assert(@mod(r.p, d) == 0);
280
+ assert(@mod(r.q, d) == 0);
281
+
282
+ r.p /= d;
283
+ r.q /= d;
284
+
285
+ assert(r.p >= 1);
286
+ assert(r.q >= 1);
287
+ }
288
+
289
+ fn multiplication(comptime T: type, r: anytype, p: anytype, q: anytype) !void {
290
+ r.p = try std.math.mul(T, r.p, p);
291
+ r.q = try std.math.mul(T, r.q, q);
292
+ }
293
+
294
+ fn addition(comptime T: type, r: anytype, p: anytype, q: anytype) !void {
295
+ // (a/b) + (c/d) = (ad+bc)/(bd)
296
+ const bd = try std.math.mul(T, r.q, q);
297
+ const ad = try std.math.mul(T, r.p, q);
298
+ const bc = try std.math.mul(T, r.q, p);
299
+
300
+ r.p = try std.math.add(T, ad, bc);
301
+ r.q = bd;
302
+ }
303
+
206
304
  fn gcd(p: anytype, q: anytype) @TypeOf(p, q) {
207
305
  assert(p >= 1);
208
306
  assert(q >= 1);
209
307
 
210
- var a = p;
211
- var b = q;
212
- var c: @TypeOf(p, q) = undefined;
308
+ // convert comptime_int to a sized integer within this function so that @ctz will work
309
+ const T = switch (@TypeOf(p, q)) {
310
+ comptime_int => std.math.IntFittingRange(@min(p, q), @max(p, q)),
311
+ else => |U| U,
312
+ };
313
+
314
+ switch (@typeInfo(T)) {
315
+ .int => {
316
+ // std.math.gcd but without some checks because we have a stricter range
317
+ var x: T = @intCast(p);
318
+ var y: T = @intCast(q);
319
+
320
+ const xz = @ctz(x);
321
+ const yz = @ctz(y);
322
+ const shift = @min(xz, yz);
323
+ x >>= @intCast(xz);
324
+ y >>= @intCast(yz);
325
+
326
+ var diff = y -% x;
327
+ while (diff != 0) : (diff = y -% x) {
328
+ const zeros = @ctz(diff);
329
+ if (x > y) diff = -%diff;
330
+ y = @min(x, y);
331
+ x = diff >> @intCast(zeros);
332
+ }
333
+
334
+ const result = y << @intCast(shift);
335
+ assert(result > 0);
336
+ return result;
337
+ },
338
+ else => {
339
+ var a = p;
340
+ var b = q;
341
+ var c: T = undefined;
342
+
343
+ while (b != 0) {
344
+ c = b;
345
+ b = @mod(a, b);
346
+ a = c;
347
+ }
213
348
 
214
- while (b != 0) {
215
- c = b;
216
- b = @mod(a, b);
217
- a = c;
349
+ assert(a > 0);
350
+ return a;
351
+ },
218
352
  }
353
+ }
219
354
 
220
- assert(a > 0);
221
- return a;
355
+ test gcd {
356
+ var prng = std.Random.DefaultPrng.init(std.testing.random_seed);
357
+ var random = prng.random();
358
+
359
+ for (0..1000) |_| {
360
+ const a = random.int(u32);
361
+ const b = random.int(u32);
362
+ if (a == 0 or b == 0) continue;
363
+
364
+ try expectEqual(
365
+ gcd(a, b),
366
+ @as(u32, @intFromFloat(gcd(@as(f64, @floatFromInt(a)), @as(f64, @floatFromInt(b))))),
367
+ );
368
+ }
369
+
370
+ try expectEqual(gcd(300_000, @as(u32, 2_300_000)), 100_000); // NB: @ctz requires an @intCast
222
371
  }
223
372
 
224
373
  fn doTurn(r: anytype) !void {
@@ -230,15 +379,18 @@ fn doTurn(r: anytype) !void {
230
379
  }
231
380
 
232
381
  test Rational {
233
- inline for (.{ u64, u128, f64 }) |t| {
234
- var r: Rational(t) = .{};
382
+ inline for (.{ u64, u128, u256, f64 }) |t| {
383
+ const R = Rational(t);
384
+ var r: R = .{};
235
385
 
236
386
  var c: t = 128;
387
+ _ = &c;
388
+
237
389
  try r.update(c, 256);
238
390
  try doTurn(&r);
239
391
 
240
392
  r.reduce();
241
- try expectEqual(Rational(t){ .p = 75383, .q = 35550920704 }, r);
393
+ try expectEqual(R{ .p = 75383, .q = 35550920704 }, r);
242
394
 
243
395
  try r.update(1, 4);
244
396
  if (t == u64) {
@@ -246,108 +398,42 @@ test Rational {
246
398
  } else {
247
399
  try doTurn(&r);
248
400
  r.reduce();
249
- try expectEqual(Rational(t){ .p = 5682596689, .q = 2527735925804191711232 }, r);
401
+ try expectEqual(R{ .p = 5682596689, .q = 2527735925804191711232 }, r);
250
402
  }
251
403
 
252
404
  r.reset();
253
405
 
254
- var s = Rational(t){ .p = 10, .q = 13 };
406
+ var s = R{ .p = 10, .q = 13 };
255
407
  try r.mul(&s);
256
- s = Rational(t){ .p = 3, .q = 4 };
408
+ s = R{ .p = 3, .q = 4 };
257
409
  try r.mul(&s);
258
- try expectEqual(Rational(t){ .p = 30, .q = 52 }, r);
410
+ try expectEqual(R{ .p = 30, .q = 52 }, r);
259
411
 
260
- s = Rational(t){ .p = 1, .q = 3 };
412
+ s = R{ .p = 1, .q = 3 };
261
413
  try r.add(&s);
262
414
  r.reduce();
263
- try expectEqual(Rational(t){ .p = 71, .q = 78 }, r);
264
- }
265
- }
266
-
267
- /// Adapter of std.math.big.Rational to the engines Rational interface.
268
- pub const BigRational = struct {
269
- /// The underlying rational number.
270
- val: std.math.big.Rational,
415
+ try expectEqual(R{ .p = 71, .q = 78 }, r);
271
416
 
272
- /// Possible error returned by operations on the rational.
273
- pub const Error = error{OutOfMemory};
417
+ var u = R{ .p = 3, .q = 5 };
418
+ var v = R{ .p = 2, .q = 5 };
419
+ try expectEqual(u.cmp(&v), .gt);
420
+ v = R{ .p = 4, .q = 5 };
421
+ try expectEqual(u.cmp(&v), .lt);
274
422
 
275
- /// Create a new BigRational wrapper. A small amount of memory will be allocated on
276
- /// initialization. Not default initialized to 1 - you must explicitly `reset` first.
277
- pub fn init(alloc: std.mem.Allocator) !BigRational {
278
- return .{ .val = try std.math.big.Rational.init(alloc) };
279
- }
280
-
281
- /// Frees all memory associated with a rational.
282
- pub fn deinit(r: *BigRational) void {
283
- r.val.deinit();
284
- }
285
-
286
- /// Resets the rational back to 1.
287
- pub fn reset(r: *BigRational) !void {
288
- try r.val.setInt(1);
289
- }
290
-
291
- /// Update the rational by multiplying its numerator by p and its denominator by q.
292
- /// Both p and q must be >= 1.
293
- pub fn update(r: *BigRational, p: anytype, q: anytype) !void {
294
- assert(p >= 1);
295
- assert(q >= 1);
296
-
297
- var s = try std.math.big.Rational.init(r.val.p.allocator);
298
- defer s.deinit();
299
- try s.setRatio(p, q);
300
- try r.val.mul(r.val, s);
301
- }
423
+ v = R{ .p = 3, .q = 6 };
424
+ try expectEqual(u.cmp(&v), .gt);
425
+ v = R{ .p = 3, .q = 4 };
426
+ try expectEqual(u.cmp(&v), .lt);
302
427
 
303
- /// Adds two rationals.
304
- pub fn add(r: *BigRational, s: *const BigRational) !void {
305
- try r.val.add(r.val, s.val);
306
- }
428
+ v = R{ .p = 3, .q = 5 };
429
+ try expectEqual(u.cmp(&v), .eq);
307
430
 
308
- /// Multiplies two rationals.
309
- pub fn mul(r: *BigRational, s: *const BigRational) !void {
310
- try r.val.mul(r.val, s.val);
431
+ try doTurn(&u);
432
+ v = R{ .p = 4567216874, .q = 89124781931235 };
433
+ if (t == u64) {
434
+ try expectEqual(u.cmp(&v), error.Overflow);
435
+ } else {
436
+ try expectEqual(u.cmp(&v), .lt);
437
+ }
311
438
  }
312
- };
313
-
314
- test BigRational {
315
- var r = try BigRational.init(std.testing.allocator);
316
- defer r.deinit();
317
- var s = try std.math.big.Rational.init(std.testing.allocator);
318
- defer s.deinit();
319
-
320
- try r.reset();
321
-
322
- var c: u8 = 128;
323
- try r.update(c, 256);
324
- try doTurn(&r);
325
-
326
- try s.setRatio(75383, 35550920704);
327
- try expect((try s.order(r.val)) == .eq);
328
-
329
- try r.update(1, 4);
330
- try doTurn(&r);
331
-
332
- try s.setRatio(5682596689, 2527735925804191711232);
333
- try expect((try s.order(r.val)) == .eq);
334
-
335
- try r.reset();
336
-
337
- var t = try BigRational.init(std.testing.allocator);
338
- defer t.deinit();
339
-
340
- try t.val.setRatio(10, 13);
341
- try r.mul(&t);
342
- try t.val.setRatio(3, 4);
343
- try r.mul(&t);
344
-
345
- try s.setRatio(15, 26);
346
- try expect((try s.order(r.val)) == .eq);
347
-
348
- try t.val.setRatio(1, 3);
349
- try r.add(&t);
350
-
351
- try s.setRatio(71, 78);
352
- try expect((try s.order(r.val)) == .eq);
353
439
  }