43 Commits
Author SHA1 Message Date
adrien 49b56bda91 Added int nanometer example in README 2026-04-22 01:20:09 +02:00
adrien 76c69448de Fixed benchmark with removed scale 2026-04-22 01:14:38 +02:00
adrien cb3c41cf4c Better README 2026-04-22 01:07:06 +02:00
adrien 5f42a8c107 Added Dimless to Base 2026-04-22 01:06:52 +02:00
adrien 1719b0de8b Removed scale (just use mulBy + dimless) + added inline to vector fn 2026-04-22 01:05:33 +02:00
adrien 84d0698878 Removed ztracy dep 2026-04-22 00:31:37 +02:00
adrien 11a741f72c Removed useless code 2026-04-22 00:19:07 +02:00
adrien cc39c1a6f4 Same for all bench, nbo more sink 2026-04-22 00:17:58 +02:00
adrien d96a1ac4bc Replaced a sing with std.mem.doNotOptimizeAway 2026-04-22 00:12:38 +02:00
adrien fb922e3d5c Added tracy as dependencie 2026-04-22 00:00:18 +02:00
adrien 1fd86a5807 Moved benchmarks into a seperate file and exe 2026-04-21 23:52:13 +02:00
adrien a518a86fb2 Changed from using format to formatNumber in Scalar and Vector to use precision, fill, width, ect 2026-04-21 22:21:19 +02:00
adrien 8a22788a2e Renamed a test 2026-04-21 19:41:02 +02:00
adrien b9647e0426 Updated build.zig to expose a module 2026-04-21 19:32:59 +02:00
adrien cb51afe79c Update zig name 2026-04-21 19:28:32 +02:00
adrien 732bf11005 Update zig.zon 2026-04-21 19:27:10 +02:00
adrien 46380a95da Renamed Quantity to Scalar and QuantityVec to Vector 2026-04-21 19:18:45 +02:00
adrien aa46cef978 Deleted tmp file 2026-04-21 18:36:31 +02:00
adrien 01c5b50b95 Added cross type overhead benchmark 2026-04-21 18:36:23 +02:00
adrien bbab41008f Passed some Scales stuff to comptime 2026-04-21 18:18:12 +02:00
adrien aa09054c4d Added fast path to mulBy too 2026-04-21 18:16:37 +02:00
adrien b02665fe89 Prevent convertion if unecessary at comptime for Quantity operations 2026-04-21 17:55:33 +02:00
adrien a16bbedbd8 Changed Quantity fn to be inline 2026-04-21 17:49:53 +02:00
adrien 7b038dd2a5 Added some explicit comptime to Quantity 2026-04-21 17:41:37 +02:00
adrien 998404d82a Switched EVERYTHING in Scales and Dimensions to comptime 2026-04-21 17:31:22 +02:00
AdrienBouvais 1f6b794ab6 Better benchmark print 2026-04-21 15:55:13 +02:00
AdrienBouvais a5cda3da62 Added a Quantity vs Native benchmark 2026-04-21 15:52:35 +02:00
AdrienBouvais 664e3aac8a Better README 2026-04-21 15:44:31 +02:00
AdrienBouvais db9d07ddd6 . 2026-04-21 15:42:26 +02:00
AdrienBouvais 574863b98b Added an int section in README 2026-04-21 15:32:23 +02:00
AdrienBouvais fd269e7407 Update README 2026-04-21 15:24:50 +02:00
AdrienBouvais 79bf70d503 Better README.zig 2026-04-21 15:14:50 +02:00
AdrienBouvais 8234591f6e . 2026-04-21 15:14:44 +02:00
AdrienBouvais 7e2652c4ba Renamed Base to Of in BaseQuantities 2026-04-21 15:05:22 +02:00
AdrienBouvais 52e58829eb Added test to BaseQuantity and a benchmark for Vectors 2026-04-21 14:19:22 +02:00
AdrienBouvais f2e18da797 Forgot to save this from previous commit 2026-04-21 13:33:27 +02:00
AdrienBouvais 8f589d3818 Created a BaseQuantity and movec Quantity and QuantityVec to seperat files 2026-04-21 13:18:53 +02:00
AdrienBouvais fd423f2bf6 Changed QuantityVec3 to QuantityVecX for vectors of any size 2026-04-21 13:08:37 +02:00
AdrienBouvais de210588ee Moved some fn 2026-04-21 11:44:48 +02:00
AdrienBouvais a484e2e7da Optimized length to be optimized for int 2026-04-21 11:43:29 +02:00
AdrienBouvais 38bf79e741 Removed old function usless after optimization 2026-04-21 11:26:39 +02:00
AdrienBouvais d9ab2f304a Optimized divBy to prevent type conversion 2026-04-21 11:23:55 +02:00
AdrienBouvais 19de4e1dd2 Optimized Quantity.to 2026-04-21 11:02:10 +02:00
10 changed files with 1541 additions and 1196 deletions
+172 -245
View File
@@ -1,306 +1,233 @@
# zig_units # dimal — Dimensional Analysis for Zig
**Compile-time dimensional analysis for Zig.** A comptime-first dimensional analysis module for Zig. If you try to add meters to seconds, **it won't compile**. That's the point.
`zig_units` lets you attach physical units to numeric values so that Born from a space simulation where `i128` positions were needed to avoid float imprecision far from the origin, this module grew into a full physical-unit type system with zero runtime overhead.
dimension mismatches become *compile errors* rather than silent bugs.
At runtime a `Quantity` is nothing but a single number — zero overhead.
``` > **Source:** [git.bouvais.lu/adrien/zig-dimal](https://git.bouvais.lu/adrien/zig-dimal)
velocity = distance / time → L¹T⁻¹ ✓ > **Minimum Zig version:** `0.16.0`
force = mass + velocity → compile error: M¹ ≠ L¹T⁻¹
```
Requires **Zig 0.16** or later.
--- ---
## Features ## Features
- Seven SI base dimensions (`L M T I Tp N J`) - **100% comptime** — all dimension and unit tracking happens at compile time. No added memory, *almost* native performance.
- Full SI prefix support (`P T G M k h da d c m u n p f`) - **Compile-time dimension errors** — adding `Meter` to `Second` is a compile error, not a runtime panic.
- Custom time aliases (`.min`, `.hour`, `.year`) - **Automatic unit conversion** — use `.to()` to convert between compatible units (e.g. `km/h` → `m/s`). Scale factors are resolved at comptime.
- Automatic scale conversion on add/sub (finer unit wins) - **Full SI prefix support** — `pico`, `nano`, `micro`, `milli`, `centi`, `deci`, `kilo`, `mega`, `giga`, `tera`, `peta`, and more.
- `Quantity(T, dims, scales)` — scalar, any numeric backing type - **Time scale support** — `min`, `hour`, `year` built in.
- `QuantityVec3` — three-component vector with the same guarantees - **Scalar and Vector types** — operate on individual values or fixed-size arrays with the same dimensional safety.
- Unicode superscript formatting (`9.81m.s⁻²`) - **Built-in physical quantities** — `dma.Base` provides ready-made types for `Velocity`, `Acceleration`, `Force`, `Energy`, `Pressure`, `ElectricCharge`, `ThermalConductivity`, and many more.
- Integer-safe square root for `Vec3.length()` - **Rich formatting** — values print with their unit automatically: `9.81m.s⁻²`, `42m.kg.s⁻¹`, `0.172km`.
- All dimension tracking happens at `comptime` — no runtime cost - **`i128` support** — the whole reason this exists. Use large integers for high-precision fixed-point positions without manual conversion.
- **Tests and benchmarks included** — run them and see how it performs on your machine (results welcome!).
---
## The 7 SI Base Dimensions
| Symbol | Dimension | SI Unit |
|--------|----------------------|----------|
| `L` | Length | `m` |
| `M` | Mass | `g` |
| `T` | Time | `s` |
| `I` | Electric Current | `A` |
| `Tp` | Temperature | `K` |
| `N` | Amount of Substance | `mol` |
| `J` | Luminous Intensity | `cd` |
--- ---
## Installation ## Installation
### Add as a Zig dependency ### 1. Fetch the dependency
```bash ```sh
zig fetch --save https://github.com/YOUR_USERNAME/zig_units/archive/refs/heads/main.tar.gz zig fetch --save git+https://git.bouvais.lu/adrien/zig-dimal#b9647e04266e3f395cfd26b41622b0c119a1e5be
``` ```
This adds an entry to your `build.zig.zon`. Then wire it up in your This will add the following to your `build.zig.zon` automatically:
`build.zig`:
```zig ```zig
const zig_units = b.dependency("zig_units", .{
.target = target,
.optimize = optimize,
});
my_module.addImport("zig_units", zig_units.module("zig_units"));
```
### Local path (monorepo / development)
```zig
// build.zig.zon
.dependencies = .{ .dependencies = .{
.zig_units = .{ .path = "../zig_units" }, .dimal = .{
.url = "git+https://git.bouvais.lu/adrien/zig-dimal#b9647e04266e3f395cfd26b41622b0c119a1e5be",
.hash = "dimal-0.1.0-WNhSHvomAQAX1ISvq9ZBal-Gam6078y8hE67aC82l63V",
},
}, },
``` ```
--- ### 2. Wire it up in `build.zig`
## Quick start
```zig ```zig
const units = @import("zig_units"); const std = @import("std");
const Quantity = units.Quantity;
const Dims = units.Dimensions;
const Scales = units.Scales;
// Define named unit types pub fn build(b: *std.Build) void {
const Meter = Quantity(f32, Dims.init(.{ .L = 1 }), Scales.init(.{})); const target = b.standardTargetOptions(.{});
const KiloMeter= Quantity(f32, Dims.init(.{ .L = 1 }), Scales.init(.{ .L = .k })); const dimal = b.dependency("dimal", .{}).module("dimal");
const Second = Quantity(f32, Dims.init(.{ .T = 1 }), Scales.init(.{}));
const MPerSec = Quantity(f32, Dims.init(.{ .L = 1, .T = -1 }), Scales.init(.{}));
const dist = Meter{ .value = 100.0 }; const exe = b.addExecutable(.{
const t = Second{ .value = 5.0 }; .name = "my_project",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.imports = &.{.{
.name = "dimal",
.module = dimal,
}},
}),
});
b.installArtifact(exe);
}
```
// Dimension is tracked automatically — vel has type L¹T⁻¹ ### 3. Import in your code
const vel = dist.divBy(t);
// Convert to an explicit type (same dims required, compile error otherwise) ```zig
const vel2 = vel.to(MPerSec); const dma = @import("dimal");
const Scalar = dma.Scalar;
// Cross-scale addition: km + m → result in metres (finer scale) const Dimensions = dma.Dimensions;
const km = KiloMeter{ .value = 1.0 }; const Scales = dma.Scales;
const sum = km.add(dist); // 1100 m
``` ```
--- ---
## API reference ## Quick Start
### `Quantity(T, dims, scales)` ### Defining unit types
| Member | Kind | Description | A `Scalar` type is parameterized by three things: the numeric type (`f64`, `i128`, …), the dimensions (which physical quantities, and their exponents), and the scales (SI prefixes or custom time units).
|---|---|---|
| `value` | field | The raw numeric value |
| `ValueType` | comptime | Alias for `T` |
| `dims` | comptime | The `Dimensions` of this type |
| `scales` | comptime | The `Scales` of this type |
| `Vec3` | comptime | The matching `QuantityVec3` type |
| `add(rhs)` | fn | Same-dimension addition, finer scale |
| `sub(rhs)` | fn | Same-dimension subtraction, finer scale |
| `mulBy(rhs)` | fn | Multiplication, dims are added |
| `divBy(rhs)` | fn | Division, dims are subtracted |
| `scale(s: T)` | fn | Dimensionless scalar multiply |
| `to(Dest)` | fn | Convert to another `Quantity` type (same dims) |
| `vec3()` | fn | Broadcast scalar to a `Vec3` |
| `format(writer)` | fn | Print `value + unit string` |
### `QuantityVec3`
Obtained via `SomeQuantity.Vec3`.
| Member | Kind | Description |
|---|---|---|
| `x, y, z` | fields | The three components |
| `zero` | comptime | `(0, 0, 0)` |
| `one` | comptime | `(1, 1, 1)` |
| `initDefault(v)` | fn | Broadcast scalar to all components |
| `add(rhs)` | fn | Component-wise addition |
| `sub(rhs)` | fn | Component-wise subtraction |
| `mulBy(rhs)` | fn | Component-wise element-wise multiply |
| `divBy(rhs)` | fn | Component-wise element-wise divide |
| `mulByScalar(q)` | fn | Multiply by a scalar `Quantity` |
| `divByScalar(q)` | fn | Divide by a scalar `Quantity` |
| `scale(s: T)` | fn | Dimensionless scalar multiply |
| `negate()` | fn | Negate all components |
| `to(DestQ)` | fn | Convert to another vector quantity type |
| `lengthSqr()` | fn | Squared Euclidean length (no sqrt) |
| `length()` | fn | Euclidean length (integer-safe) |
| `format(writer)` | fn | Print `(x, y, z) + unit string` |
### `Dimensions`
A comptime struct storing a signed exponent per SI base dimension.
```zig ```zig
const Dims = @import("zig_units").Dimensions; const Meter = Scalar(f64, .init(.{ .L = 1 }), .init(.{}));
const NanoMeter = Scalar(i64, .init(.{ .L = 1 }), .init(.{ .L = .n }));
// Acceleration: L¹ T⁻² const KiloMeter = Scalar(f64, .init(.{ .L = 1 }), .init(.{ .L = .k }));
const accel_dims = Dims.init(.{ .L = 1, .T = -2 }); const Second = Scalar(f64, .init(.{ .T = 1 }), .init(.{}));
const Velocity = Scalar(f64, .init(.{ .L = 1, .T = -1 }), .init(.{}));
const Kmh = Scalar(f64, .init(.{ .L = 1, .T = -1 }), .init(.{ .L = .k, .T = .hour }));
``` ```
| Function | Description | Or use the pre-built helpers from `dma.Base`:
```zig
const Acceleration = dma.Base.Acceleration.Of(f64);
const KmhSpeed = dma.Base.Speed.Scaled(f64, Scales.init(.{ .L = .k, .T = .hour }));
```
### Kinematics example
```zig
const v0 = Velocity{ .value = 10.0 }; // 10 m/s
const accel = Acceleration{ .value = 9.81 }; // 9.81 m/s²
const time = Second{ .value = 5.0 }; // 5 s
// d = v₀t + ½at²
const d1 = v0.mulBy(time); // → Meter
const d2 = accel.mulBy(time.mulBy(time)).scale(0.5); // → Meter
const dist = d1.add(d2);
const v_final = v0.add(accel.mulBy(time));
std.debug.print("Distance: {d} | {d}\n", .{ dist, dist.to(KiloMeter) });
// Distance: 172.625m | 0.172625km
std.debug.print("Final speed: {d:.2}\n", .{v_final});
// Final speed: 59.05m.s⁻¹
```
### Unit conversion
`.to()` converts between compatible units at comptime. Mixing incompatible dimensions is a **compile error**.
```zig
const speed_kmh = Kmh{ .value = 120.0 };
const speed_ms = speed_kmh.to(Velocity); // 33.333... m/s — comptime ratio
// This would NOT compile:
// const bad = speed_kmh.to(Second); // "Dimension mismatch in to: L1T-1 vs T1"
```
### Working with Vectors
Every `Scalar` type exposes a `.Vec3` and a generic `.Vec(n)`:
```zig
const Vec3Meter = Meter.Vec3; // or: Vector(3, Meter)
const pos = Vec3Meter{ .data = .{ 100, 200, 300 } };
const t = Second{ .value = 10 };
const vel = pos.divByScalar(t); // → Vec3 of Velocity (m/s)
std.debug.print("{d}\n", .{vel}); // (10, 20, 30)m.s⁻¹
```
Vectors support: `add`, `sub`, `mulBy`, `divBy`, `mulByScalar`, `divByScalar`, `negate`, `to`, `length`, `lengthSqr`.
---
## API Reference
### `Scalar(T, dims, scales)`
| Method | Description |
|---|---| |---|---|
| `init(struct_literal)` | Create from named exponents; unset dims default to 0 | | `.add(rhs)` | Add two quantities of the same dimension. Auto-converts scales. |
| `initFill(val: i8)` | Set all exponents to `val` | | `.sub(rhs)` | Subtract. Auto-converts scales. |
| `get(dim)` | Read a single exponent | | `.mulBy(rhs)` | Multiply — dimensions are **summed**. `m * s⁻¹` → `m·s⁻¹`. |
| `set(dim, val)` | Write a single exponent | | `.divBy(rhs)` | Divide — dimensions are **subtracted**. `m / s` → `m·s⁻¹`. |
| `add(a, b)` | Component-wise sum (for `mulBy`) | | `.to(DestType)` | Convert to another unit of the same dimension. Compile error on mismatch. |
| `sub(a, b)` | Component-wise difference (for `divBy`) | | `.vec3()` | Wrap the value in a `Vec3` of the same type. |
| `eql(a, b)` | Equality check | | `.Vec(n)` | Get the `Vector(n, Self)` type. |
| `str()` | Comptime human-readable string, e.g. `"L1T-2"` |
### `Scales` ### `dma.Base` — Pre-built quantities
A comptime struct storing a `UnitScale` per SI base dimension. A selection of what's available (call `.Of(T)` for base units, `.Scaled(T, scales)` for custom scales):
```zig `Meter`, `Second`, `Gramm`, `Kelvin`, `ElectricCurrent`, `Speed`, `Acceleration`, `Inertia`, `Force`, `Pressure`, `Energy`, `Power`, `Area`, `Volume`, `Density`, `Frequency`, `Viscosity`, `ElectricCharge`, `ElectricPotential`, `ElectricResistance`, `MagneticFlux`, `ThermalCapacity`, `ThermalConductivity`, and more.
const Scales = @import("zig_units").Scales;
// Kilometres per nanosecond ### `Scales` — SI prefixes
const spd_scales = Scales.init(.{ .L = .k, .T = .n });
```
| `UnitScale` variant | Factor | | Tag | Factor |
|---|---| |---|---|
| `.P` | ×10¹⁵ | | `.P` | 10¹⁵ |
| `.T` | ×10¹² | | `.T` | 10¹² |
| `.G` | ×10⁹ | | `.G` | 10⁹ |
| `.M` | ×10⁶ | | `.M` | 10⁶ |
| `.k` | ×10³ | | `.k` | 10³ |
| `.h` | ×10² | | `.none` | 1 |
| `.da` | ×10¹ | | `.c` | 10⁻² |
| `.none` | ×1 | | `.m` | 10⁻³ |
| `.d` | ×10⁻¹ | | `.u` | 10⁻⁶ |
| `.c` | ×10⁻² | | `.n` | 10⁻⁹ |
| `.m` | ×10⁻³ | | `.p` | 10⁻¹² |
| `.u` | ×10⁻⁶ | | `.f` | 10⁻¹⁵ |
| `.n` | ×10⁻⁹ | | `.min` | 60 |
| `.p` | ×10⁻¹² | | `.hour` | 3600 |
| `.f` | ×10⁻¹⁵ | | `.year` | 31 536 000 |
| `.min` | ×60 (seconds) |
| `.hour` | ×3 600 |
| `.year` | ×31 536 000 |
--- ---
## Examples ## Running Tests and Benchmarks
### Kinematics ```sh
```zig
const Meter = Quantity(f64, Dims.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f64, Dims.init(.{ .T = 1 }), Scales.init(.{}));
const pos = Meter{ .value = 200.0 };
const time = Second{ .value = 8.0 };
const vel = pos.divBy(time); // L¹T⁻¹ — 25 m/s
const accel = vel.divBy(time); // L¹T⁻² — 3.125 m/s²
```
### Cross-scale addition
```zig
const KM = Quantity(i64, Dims.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const M = Quantity(i64, Dims.init(.{ .L = 1 }), Scales.init(.{}));
const a = KM{ .value = 2 }; // 2 km
const b = M{ .value = 500 }; // 500 m
const sum = a.add(b); // result scale = metres (finer) → 2500 m
```
### Time conversion
```zig
const Hour = Quantity(i64, Dims.init(.{ .T = 1 }), Scales.init(.{ .T = .hour }));
const Minute = Quantity(i64, Dims.init(.{ .T = 1 }), Scales.init(.{ .T = .min }));
const Second = Quantity(i64, Dims.init(.{ .T = 1 }), Scales.init(.{}));
const h = Hour{ .value = 2 };
const min = h.to(Minute); // 120
const sec = min.to(Second); // 7200
```
### Vec3 velocity
```zig
const Meter = Quantity(f32, Dims.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f32, Dims.init(.{ .T = 1 }), Scales.init(.{}));
const pos = Meter.Vec3{ .x = 30.0, .y = 60.0, .z = 90.0 };
const time = Second{ .value = 3.0 };
const vel = pos.divByScalar(time); // Vec3 with dims L¹T⁻¹
const dist = vel.length(); // Euclidean length
```
### Dimension mismatch — compile error
```zig
const Meter = Quantity(f32, Dims.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f32, Dims.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 5.0 };
const t = Second{ .value = 2.0 };
// This will NOT compile:
const bad = d.add(t); // error: Dimension mismatch in add: L1 vs T1
```
---
## Running the tests
```bash
zig build test zig build test
zig build benchmark
``` ```
The test suite covers scalar and vector arithmetic, cross-scale operations, Benchmark results are very welcome — feel free to share yours!
conversion chains, negative values, formatting, and an optional benchmark
(`"Comprehensive Benchmark: All Ops × All Types"`).
--- ---
## Project layout ## Roadmap / Known Limitations
``` - More operations beyond `add`, `sub`, `mulBy`, `divBy` (e.g. `pow`, `sqrt`).
zig_units/ - SIMD acceleration for `Vector` operations.
├── build.zig # Build script; exposes the "zig_units" module - Some paths may still fall back to runtime computation — optimization ongoing.
├── build.zig.zon # Package manifest - More test coverage.
├── src/
│ ├── main.zig # Quantity, QuantityVec3, tests
│ ├── Dimensions.zig # SI base dimensions + comptime arithmetic
│ ├── Scales.zig # SI prefixes + scale helpers
│ └── helper.zig # Internal utilities (isInt, printSuperscript)
└── README.md
```
---
## Design notes
**Why comptime parameters?** Zig's `comptime` means the compiler can
evaluate all dimension arithmetic before any machine code is generated.
Two quantities with mismatched dimensions simply fail to compile —
there is no runtime overhead and no need for exception handling.
**Scale selection on arithmetic.** When two operands have different
scales (e.g. km and m), `zig_units` automatically picks the finer
(smaller-factor) scale for the result. This prevents silent precision
loss at the cost of an automatic rescaling of both operands.
**Integer backing types.** Division uses an `f64` intermediate and
rounds back to the integer type. For best accuracy, prefer `f32`/`f64`
for quantities that will be divided frequently.
--- ---
## License ## License
MIT — see `LICENSE` for details. See the repository for license details.
+25 -27
View File
@@ -2,40 +2,38 @@ const std = @import("std");
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{ .preferred_optimize_mode = .ReleaseSmall }); const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "Zig_Units", // 1. Define the module so other projects can import it
_ = b.addModule("dimal", .{
.root_source_file = b.path("src/main.zig"),
});
const exe_tests = b.addTest(.{
.root_module = b.createModule(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"), .root_source_file = b.path("src/main.zig"),
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
}),
.test_runner = .{ .path = b.path("test_runner.zig"), .mode = .simple },
});
const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_exe_tests.step);
const bench_exe = b.addExecutable(.{
.name = "benchmark",
.root_module = b.createModule(.{
.root_source_file = b.path("src/benchmark.zig"),
.target = target,
.imports = &.{}, .imports = &.{},
}), }),
}); });
b.installArtifact(exe); b.installArtifact(bench_exe);
const run_step = b.step("run", "Run the app");
const run_cmd = b.addRunArtifact(exe); const run_bench = b.addRunArtifact(bench_exe);
run_step.dependOn(&run_cmd.step); const bench_step = b.step("benchmark", "Run the benchmark suite");
bench_step.dependOn(&run_bench.step);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const exe_tests = b.addTest(.{
.root_module = exe.root_module,
.test_runner = .{
.path = .{ .cwd_relative = "test_runner.zig" },
.mode = .simple,
},
});
// A run step that will run the second test executable.
const run_exe_tests = b.addRunArtifact(exe_tests);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&run_exe_tests.step);
} }
+5 -73
View File
@@ -1,81 +1,13 @@
.{ .{
// This is the default name used by packages depending on this one. For .name = .dimal,
// example, when a user runs `zig fetch --save <url>`, this field is used .version = "0.1.0",
// as the key in the `dependencies` table. Although the user can choose a .fingerprint = 0x9453b1ff1e52d858,
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = .Zig_Units,
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// Together with name, this represents a globally unique package
// identifier. This field is generated by the Zig toolchain when the
// package is first created, and then *never changes*. This allows
// unambiguous detection of one package being an updated version of
// another.
//
// When forking a Zig project, this id should be regenerated (delete the
// field and run `zig build`) if the upstream project is still maintained.
// Otherwise, the fork is *hostile*, attempting to take control over the
// original project's identity. Thus it is recommended to leave the comment
// on the following line intact, so that it shows up in code reviews that
// modify the field.
.fingerprint = 0x934b00cf88f69b22, // Changing this has security and trust implications.
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.16.0", .minimum_zig_version = "0.16.0",
// This field is optional. .dependencies = .{},
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL. If the contents of a URL change this will result in a hash mismatch
// // which will prevent zig from using it.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
//
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{ .paths = .{
"build.zig", "build.zig",
"build.zig.zon", "build.zig.zon",
"src", "src",
// For example... "test_runner.zig",
//"LICENSE",
//"README.md",
}, },
} }
+155
View File
@@ -0,0 +1,155 @@
const std = @import("std");
// Adjust these imports to match your actual file names
const Dimensions = @import("Dimensions.zig");
const Scales = @import("Scales.zig");
const Scalar = @import("Scalar.zig").Scalar;
/// Helper function to create a clean namespace for each physical dimension.
/// It exposes the raw dimensions, and easy type-creators for Base or Scaled variants.
pub fn BaseScalar(comptime d: anytype) type {
return struct {
pub const dims = Dimensions.init(d);
/// Creates a Scalar of this dimension using default scales.
/// Example: const V = Quantities.Velocity.Base(f32);
pub fn Of(comptime T: type) type {
return Scalar(T, dims, Scales.init(.{}));
}
/// Creates a Scalar of this dimension using custom scales.
/// Example: const Kmh = Quantities.Velocity.Scaled(f32, Scales.init(.{ .L = .k, .T = .hour }));
pub fn Scaled(comptime T: type, comptime s: Scales) type {
return Scalar(T, dims, s);
}
};
}
pub const Dimless = BaseScalar(.{});
// ==========================================
// Base Quantities
// ==========================================
pub const Meter = BaseScalar(.{ .L = 1 });
pub const Second = BaseScalar(.{ .T = 1 });
pub const Gramm = BaseScalar(.{ .M = 1 });
pub const Kelvin = BaseScalar(.{ .Tr = 1 });
pub const ElectricCurrent = BaseScalar(.{ .I = 1 });
// ==========================================
// Electric
// ==========================================
pub const ElectricConductivity = BaseScalar(.{ .M = -1, .L = -3, .T = 3, .I = 2 });
pub const ElectricCharge = BaseScalar(.{ .T = 1, .I = 1 });
pub const ElectricPotential = BaseScalar(.{ .T = -3, .L = 2, .M = 1, .I = -1 });
pub const ElectricResistance = BaseScalar(.{ .M = 1, .L = 2, .T = -3, .I = -2 });
pub const ElectricResistivity = BaseScalar(.{ .M = 1, .L = 3, .T = -3, .I = -2 });
pub const ElectricCapacitance = BaseScalar(.{ .T = 4, .L = -2, .M = -1, .I = 2 });
pub const ElectricImpedance = ElectricResistance;
pub const MagneticFlux = BaseScalar(.{ .M = 1, .L = 2, .T = -2, .I = -1 });
pub const MagneticDensity = BaseScalar(.{ .M = 1, .T = -2, .I = -1 });
pub const MagneticStrength = BaseScalar(.{ .L = -1, .I = 1 }); // Fixed typo from MagneticStrengh
pub const MagneticMoment = BaseScalar(.{ .L = 2, .I = 1 });
// ==========================================
// Movement
// ==========================================
pub const Speed = BaseScalar(.{ .L = 1, .T = -1 });
pub const Acceleration = BaseScalar(.{ .L = 1, .T = -2 });
pub const Inertia = BaseScalar(.{ .M = 1, .L = 2 });
// ==========================================
// Forces / Energy
// ==========================================
pub const Force = BaseScalar(.{ .T = -2, .M = 1, .L = 1 });
pub const Pressure = BaseScalar(.{ .T = -2, .L = -1, .M = 1 });
pub const Energy = BaseScalar(.{ .T = -2, .L = 2, .M = 1 });
pub const Power = BaseScalar(.{ .T = -3, .L = 2, .M = 1 });
// ==========================================
// Dimension
// ==========================================
pub const Area = BaseScalar(.{ .L = 2 });
pub const Volume = BaseScalar(.{ .L = 3 });
pub const AreaDensity = BaseScalar(.{ .M = 1, .L = -2 });
pub const Density = BaseScalar(.{ .M = 1, .L = -3 });
// ==========================================
// Thermal
// ==========================================
pub const ThermalHeat = Energy;
pub const ThermalWork = Energy;
pub const ThermalCapacity = BaseScalar(.{ .M = 1, .L = 2, .T = -2, .Tr = -1 });
pub const ThermalCapacityPerMass = BaseScalar(.{ .L = 2, .T = -2, .Tr = -1 });
pub const ThermalFluxDensity = BaseScalar(.{ .M = 1, .T = -3 }); // Fixed typo from ThermalluxDensity
pub const ThermalConductance = BaseScalar(.{ .M = 1, .L = 2, .T = -3, .Tr = -1 });
pub const ThermalConductivity = BaseScalar(.{ .M = 1, .L = 1, .T = -3, .Tr = -1 });
pub const ThermalResistance = BaseScalar(.{ .M = -1, .L = -2, .T = 3, .Tr = 1 });
pub const ThermalResistivity = BaseScalar(.{ .M = -1, .L = -1, .T = 3, .Tr = 1 });
pub const ThermalEntropy = BaseScalar(.{ .M = 1, .L = 2, .T = -2, .Tr = -1 });
// ==========================================
// Others
// ==========================================
pub const Frequency = BaseScalar(.{ .T = -1 });
pub const Viscosity = BaseScalar(.{ .M = 1, .L = -1, .T = -1 });
pub const SurfaceTension = BaseScalar(.{ .M = 1, .T = -2 }); // Corrected from MT-2a
test "BaseQuantities - Core dimensions instantiation" {
// Basic types via generic wrappers
const M = Meter.Of(f32);
const distance = M{ .value = 100.0 };
try std.testing.expectEqual(100.0, distance.value);
try std.testing.expectEqual(1, M.dims.get(.L));
try std.testing.expectEqual(0, M.dims.get(.T));
// Test specific scale variants
const Kmh = Speed.Scaled(f32, Scales.init(.{ .L = .k, .T = .hour }));
const speed = Kmh{ .value = 120.0 };
try std.testing.expectEqual(120.0, speed.value);
try std.testing.expectEqual(.k, @TypeOf(speed).scales.get(.L));
try std.testing.expectEqual(.hour, @TypeOf(speed).scales.get(.T));
}
test "BaseQuantities - Kinematics equations" {
const d = Meter.Of(f32){ .value = 50.0 };
const t = Second.Of(f32){ .value = 2.0 };
// Velocity = Distance / Time
const v = d.divBy(t);
try std.testing.expectEqual(25.0, v.value);
try std.testing.expect(Speed.dims.eql(@TypeOf(v).dims));
// Acceleration = Velocity / Time
const a = v.divBy(t);
try std.testing.expectEqual(12.5, a.value);
try std.testing.expect(Acceleration.dims.eql(@TypeOf(a).dims));
}
test "BaseQuantities - Dynamics (Force and Work)" {
// 10 kg
const m = Gramm.Scaled(f32, Scales.init(.{ .M = .k })){ .value = 10.0 };
// 9.8 m/s^2
const a = Acceleration.Of(f32){ .value = 9.8 };
// Force = mass * acceleration
const f = m.mulBy(a);
try std.testing.expectEqual(98000, f.value);
try std.testing.expect(Force.dims.eql(@TypeOf(f).dims));
// Energy (Work) = Force * distance
const distance = Meter.Of(f32){ .value = 5.0 };
const energy = f.mulBy(distance);
try std.testing.expectEqual(490000, energy.value);
try std.testing.expect(Energy.dims.eql(@TypeOf(energy).dims));
}
test "BaseQuantities - Electric combinations" {
const current = ElectricCurrent.Of(f32){ .value = 2.0 }; // 2 A
const time = Second.Of(f32){ .value = 3.0 }; // 3 s
// Charge = Current * time
const charge = current.mulBy(time);
try std.testing.expectEqual(6.0, charge.value);
try std.testing.expect(ElectricCharge.dims.eql(@TypeOf(charge).dims));
}
+8 -8
View File
@@ -33,24 +33,24 @@ pub const Dimension = enum {
const Self = @This(); const Self = @This();
data: std.EnumArray(Dimension, i8), data: std.EnumArray(Dimension, comptime_int),
pub fn init(comptime init_val: anytype) Self { pub fn init(comptime init_val: anytype) Self {
var s = Self{ .data = std.EnumArray(Dimension, i8).initFill(0) }; var s = Self{ .data = std.EnumArray(Dimension, comptime_int).initFill(0) };
inline for (std.meta.fields(@TypeOf(init_val))) |f| inline for (std.meta.fields(@TypeOf(init_val))) |f|
s.data.set(@field(Dimension, f.name), @field(init_val, f.name)); s.data.set(@field(Dimension, f.name), @field(init_val, f.name));
return s; return s;
} }
pub fn initFill(val: i8) Self { pub fn initFill(comptime val: comptime_int) Self {
return .{ .data = std.EnumArray(Dimension, i8).initFill(val) }; return .{ .data = std.EnumArray(Dimension, comptime_int).initFill(val) };
} }
pub fn get(self: Self, key: Dimension) i8 { pub fn get(comptime self: Self, comptime key: Dimension) comptime_int {
return self.data.get(key); return self.data.get(key);
} }
pub fn set(self: *Self, key: Dimension, val: i8) void { pub fn set(comptime self: *Self, comptime key: Dimension, comptime val: i8) void {
self.data.set(key, val); self.data.set(key, val);
} }
@@ -64,13 +64,13 @@ pub fn add(comptime a: Self, comptime b: Self) Self {
pub fn sub(comptime a: Self, comptime b: Self) Self { pub fn sub(comptime a: Self, comptime b: Self) Self {
@setEvalBranchQuota(10_000); @setEvalBranchQuota(10_000);
var result = Self.initFill(0); var result = Self.initFill(0);
for (std.enums.values(Dimension)) |d| inline for (std.enums.values(Dimension)) |d|
result.set(d, a.get(d) - b.get(d)); result.set(d, a.get(d) - b.get(d));
return result; return result;
} }
pub fn eql(comptime a: Self, comptime b: Self) bool { pub fn eql(comptime a: Self, comptime b: Self) bool {
for (std.enums.values(Dimension)) |d| inline for (std.enums.values(Dimension)) |d|
if (a.get(d) != b.get(d)) return false; if (a.get(d) != b.get(d)) return false;
return true; return true;
} }
+396
View File
@@ -0,0 +1,396 @@
const std = @import("std");
const hlp = @import("helper.zig");
const Vector = @import("Vector.zig").Vector;
const Scales = @import("Scales.zig");
const UnitScale = Scales.UnitScale;
const Dimensions = @import("Dimensions.zig");
const Dimension = Dimensions.Dimension;
pub fn Scalar(comptime T: type, comptime d: Dimensions, comptime s: Scales) type {
@setEvalBranchQuota(10_000_000);
return struct {
value: T,
const Self = @This();
pub const Vec3: type = Vector(3, Self);
pub const ValueType: type = T;
pub const dims: Dimensions = d;
pub const scales = s;
pub inline fn add(self: Self, rhs: anytype) Scalar(
T,
dims,
scales.min(@TypeOf(rhs).scales),
) {
if (comptime !dims.eql(@TypeOf(rhs).dims))
@compileError("Dimension mismatch in add: " ++ dims.str() ++ " vs " ++ @TypeOf(rhs).dims.str());
if (comptime @TypeOf(rhs) == Self)
return .{ .value = self.value + rhs.value };
const TargetType = Scalar(T, dims, scales.min(@TypeOf(rhs).scales));
const lhs_val = if (comptime @TypeOf(self) == TargetType) self.value else self.to(TargetType).value;
const rhs_val = if (comptime @TypeOf(rhs) == TargetType) rhs.value else rhs.to(TargetType).value;
return .{ .value = lhs_val + rhs_val };
}
pub inline fn sub(self: Self, rhs: anytype) Scalar(
T,
dims,
scales.min(@TypeOf(rhs).scales),
) {
if (comptime !dims.eql(@TypeOf(rhs).dims))
@compileError("Dimension mismatch in sub: " ++ dims.str() ++ " vs " ++ @TypeOf(rhs).dims.str());
if (comptime @TypeOf(rhs) == Self)
return .{ .value = self.value - rhs.value };
const TargetType = Scalar(T, dims, scales.min(@TypeOf(rhs).scales));
const lhs_val = if (comptime @TypeOf(self) == TargetType) self.value else self.to(TargetType).value;
const rhs_val = if (comptime @TypeOf(rhs) == TargetType) rhs.value else rhs.to(TargetType).value;
return .{ .value = lhs_val - rhs_val };
}
pub inline fn mulBy(self: Self, rhs: anytype) Scalar(
T,
dims.add(@TypeOf(rhs).dims),
scales.min(@TypeOf(rhs).scales),
) {
const RhsType = @TypeOf(rhs);
const SelfNorm = Scalar(T, dims, scales.min(RhsType.scales));
const RhsNorm = Scalar(T, RhsType.dims, scales.min(RhsType.scales));
if (comptime Self == SelfNorm and RhsType == RhsNorm)
return .{ .value = self.value * rhs.value };
const lhs_val = if (comptime Self == SelfNorm) self.value else self.to(SelfNorm).value;
const rhs_val = if (comptime RhsType == RhsNorm) rhs.value else rhs.to(RhsNorm).value;
return .{ .value = lhs_val * rhs_val };
}
pub inline fn divBy(self: Self, rhs: anytype) Scalar(
T,
dims.sub(@TypeOf(rhs).dims),
scales.min(@TypeOf(rhs).scales),
) {
const RhsType = @TypeOf(rhs);
const SelfNorm = Scalar(T, dims, scales.min(RhsType.scales));
const RhsNorm = Scalar(T, RhsType.dims, scales.min(RhsType.scales));
const lhs_val = if (comptime Self == SelfNorm) self.value else self.to(SelfNorm).value;
const rhs_val = if (comptime RhsType == RhsNorm) rhs.value else rhs.to(RhsNorm).value;
if (comptime @typeInfo(T) == .int) {
return .{ .value = @divTrunc(lhs_val, rhs_val) };
} else {
return .{ .value = lhs_val / rhs_val };
}
}
pub inline fn to(self: Self, comptime Dest: type) Dest {
if (comptime !dims.eql(Dest.dims))
@compileError("Dimension mismatch in to: " ++ dims.str() ++ " vs " ++ Dest.dims.str());
if (comptime @TypeOf(self) == Dest)
return self;
const DestT = Dest.ValueType;
const ratio = comptime (scales.getFactor(dims) / Dest.scales.getFactor(Dest.dims));
// Fast-path: Native pure-integer exact conversions
if (comptime @typeInfo(T) == .int and @typeInfo(DestT) == .int) {
if (comptime ratio >= 1.0 and @round(ratio) == ratio) {
const mult: DestT = comptime @intFromFloat(ratio);
return .{ .value = @as(DestT, @intCast(self.value)) * mult };
} else if (comptime ratio < 1.0 and @round(1.0 / ratio) == 1.0 / ratio) {
const div: DestT = comptime @intFromFloat(1.0 / ratio);
const val = @as(DestT, @intCast(self.value));
const half = comptime div / 2;
// Native round-to-nearest
const rounded = if (val >= 0) @divTrunc(val + half, div) else @divTrunc(val - half, div);
return .{ .value = rounded };
}
}
// Fallback preserving native Float types (e.g., f128 shouldn't downcast to f64)
if (comptime @typeInfo(DestT) == .float) {
const val_f = switch (@typeInfo(T)) {
inline .int => @as(DestT, @floatFromInt(self.value)),
inline .float => @as(DestT, @floatCast(self.value)),
else => unreachable,
};
return .{ .value = val_f * @as(DestT, @floatCast(ratio)) };
} else {
const val_f = switch (@typeInfo(T)) {
inline .int => @as(f64, @floatFromInt(self.value)),
inline .float => @as(f64, @floatCast(self.value)),
else => unreachable,
};
return .{ .value = @intFromFloat(@round(val_f * ratio)) };
}
}
pub fn Vec(self: Self, comptime len: comptime_int) Vector(len, Self) {
return Vector(len, Self).initDefault(self.value);
}
pub fn vec3(self: Self) Vec3 {
return Vec3.initDefault(self.value);
}
pub fn formatNumber(
self: Self,
writer: *std.Io.Writer,
options: std.fmt.Number,
) !void {
switch (@typeInfo(T)) {
.float, .comptime_float => try writer.printFloat(self.value, options),
.int, .comptime_int => try writer.printInt(self.value, 10, .lower, .{
.width = options.width,
.alignment = options.alignment,
.fill = options.fill,
.precision = options.precision,
}),
else => unreachable,
}
var first = true;
inline for (std.enums.values(Dimension)) |bu| {
const v = dims.get(bu);
if (comptime v == 0) continue;
if (!first)
try writer.writeAll(".");
first = false;
const uscale = scales.get(bu);
if (bu == .T and (uscale == .min or uscale == .hour or uscale == .year))
try writer.print("{s}", .{uscale.str()})
else
try writer.print("{s}{s}", .{ uscale.str(), bu.unit() });
if (v != 1)
try hlp.printSuperscript(writer, v);
}
}
};
}
test "Generate quantity" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = -3 }));
const Second = Scalar(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{ .T = .n }));
const distance = Meter{ .value = 10 };
const time = Second{ .value = 2 };
try std.testing.expectEqual(10, distance.value);
try std.testing.expectEqual(2, time.value);
}
test "Add" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const distance = Meter{ .value = 10 };
const distance2 = Meter{ .value = 20 };
const added = distance.add(distance2);
try std.testing.expectEqual(30, added.value);
try std.testing.expectEqual(1, @TypeOf(added).dims.get(.L));
const KiloMeter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const distance3 = KiloMeter{ .value = 2 };
const added2 = distance.add(distance3);
try std.testing.expectEqual(2010, added2.value);
try std.testing.expectEqual(1, @TypeOf(added2).dims.get(.L));
const added3 = distance3.add(distance).to(KiloMeter);
try std.testing.expectEqual(2, added3.value);
try std.testing.expectEqual(1, @TypeOf(added3).dims.get(.L));
const KiloMeter_f = Scalar(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const distance4 = KiloMeter_f{ .value = 2 };
const added4 = distance4.add(distance).to(KiloMeter_f);
try std.testing.expectApproxEqAbs(2.01, added4.value, 0.000001);
try std.testing.expectEqual(1, @TypeOf(added4).dims.get(.L));
}
test "Sub" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const KiloMeter_f = Scalar(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const a = Meter{ .value = 500 };
const b = Meter{ .value = 200 };
const diff = a.sub(b);
try std.testing.expectEqual(300, diff.value);
const diff2 = b.sub(a);
try std.testing.expectEqual(-300, diff2.value);
const km_f = KiloMeter_f{ .value = 2.5 };
const m_f = Meter{ .value = 500 };
const diff3 = km_f.sub(m_f);
try std.testing.expectApproxEqAbs(2000, diff3.value, 1e-4);
}
test "MulBy" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Scalar(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 3.0 };
const t = Second{ .value = 4.0 };
const area_time = d.mulBy(t);
try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
const d2 = Meter{ .value = 5.0 };
const area = d.mulBy(d2);
try std.testing.expectEqual(15, area.value);
try std.testing.expectEqual(2, @TypeOf(area).dims.get(.L));
try std.testing.expectEqual(0, @TypeOf(area).dims.get(.T));
}
test "MulBy with scale" {
const KiloMeter = Scalar(f32, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const KiloGram = Scalar(f32, Dimensions.init(.{ .M = 1 }), Scales.init(.{ .M = .k }));
const dist = KiloMeter{ .value = 2.0 };
const mass = KiloGram{ .value = 3.0 };
const prod = dist.mulBy(mass);
try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.M));
}
test "MulBy with type change" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const Second = Scalar(f64, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const KmSec = Scalar(i64, Dimensions.init(.{ .L = 1, .T = 1 }), Scales.init(.{ .L = .k }));
const KmSec_f = Scalar(f32, Dimensions.init(.{ .L = 1, .T = 1 }), Scales.init(.{ .L = .k }));
const d = Meter{ .value = 3.0 };
const t = Second{ .value = 4.0 };
const area_time = d.mulBy(t).to(KmSec);
const area_time_f = d.mulBy(t).to(KmSec_f);
try std.testing.expectEqual(12, area_time.value);
try std.testing.expectApproxEqAbs(12, area_time_f.value, 0.0001);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
}
test "MulBy small" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .n }));
const Second = Scalar(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 3.0 };
const t = Second{ .value = 4.0 };
const area_time = d.mulBy(t);
try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
}
test "MulBy dimensionless" {
const DimLess = Scalar(i128, Dimensions.init(.{}), Scales.init(.{}));
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const d = Meter{ .value = 7 };
const scaled = d.mulBy(DimLess{ .value = 3 });
try std.testing.expectEqual(21, scaled.value);
try std.testing.expectEqual(1, @TypeOf(scaled).dims.get(.L));
}
test "Chained: velocity and acceleration" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Scalar(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const dist = Meter{ .value = 100.0 };
const t1 = Second{ .value = 5.0 };
const velocity = dist.divBy(t1);
try std.testing.expectEqual(20, velocity.value);
try std.testing.expectEqual(1, @TypeOf(velocity).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(velocity).dims.get(.T));
const t2 = Second{ .value = 4.0 };
const accel = velocity.divBy(t2);
try std.testing.expectEqual(5, accel.value);
try std.testing.expectEqual(1, @TypeOf(accel).dims.get(.L));
try std.testing.expectEqual(-2, @TypeOf(accel).dims.get(.T));
}
test "DivBy integer exact" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Scalar(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const dist = Meter{ .value = 120 };
const time = Second{ .value = 4 };
const vel = dist.divBy(time);
try std.testing.expectEqual(30, vel.value);
try std.testing.expectEqual(1, @TypeOf(vel).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(vel).dims.get(.T));
}
test "Conversion chain: km -> m -> cm" {
const KiloMeter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const CentiMeter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .c }));
const km = KiloMeter{ .value = 15 };
const m = km.to(Meter);
const cm = m.to(CentiMeter);
try std.testing.expectEqual(15_000, m.value);
try std.testing.expectEqual(1_500_000, cm.value);
}
test "Conversion: hours -> minutes -> seconds" {
const Hour = Scalar(i128, Dimensions.init(.{ .T = 1 }), Scales.init(.{ .T = .hour }));
const Minute = Scalar(i128, Dimensions.init(.{ .T = 1 }), Scales.init(.{ .T = .min }));
const Second = Scalar(i128, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const h = Hour{ .value = 1.0 };
const min = h.to(Minute);
const sec = min.to(Second);
try std.testing.expectEqual(60, min.value);
try std.testing.expectEqual(3600, sec.value);
}
test "Negative values" {
const Meter = Scalar(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const a = Meter{ .value = 5 };
const b = Meter{ .value = 20 };
const diff = a.sub(b);
try std.testing.expectEqual(-15, diff.value);
}
test "Format Scalar" {
const MeterPerSecondSq = Scalar(
f32,
Dimensions.init(.{ .L = 1, .T = -2 }),
Scales.init(.{ .T = .n }),
);
const KgMeterPerSecond = Scalar(
f32,
Dimensions.init(.{ .M = 1, .L = 1, .T = -1 }),
Scales.init(.{ .M = .k }),
);
const Meter = Scalar(f32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const m = Meter{ .value = 1.23456 };
const accel = MeterPerSecondSq{ .value = 9.81 };
const momentum = KgMeterPerSecond{ .value = 42.0 };
var buf: [64]u8 = undefined;
var res = try std.fmt.bufPrint(&buf, "{d:.2}", .{m});
try std.testing.expectEqualStrings("1.23m", res);
res = try std.fmt.bufPrint(&buf, "{d}", .{accel});
try std.testing.expectEqualStrings("9.81m.ns⁻²", res);
res = try std.fmt.bufPrint(&buf, "{d}", .{momentum});
try std.testing.expectEqualStrings("42m.kg.s⁻¹", res);
res = try std.fmt.bufPrint(&buf, "{d:_>10.1}", .{m});
try std.testing.expectEqualStrings("_______1.2m", res);
}
+21 -21
View File
@@ -3,7 +3,7 @@ const hlp = @import("helper.zig");
const Dimensions = @import("Dimensions.zig"); const Dimensions = @import("Dimensions.zig");
const Dimension = @import("Dimensions.zig").Dimension; const Dimension = @import("Dimensions.zig").Dimension;
pub const UnitScale = enum(i32) { pub const UnitScale = enum(isize) {
P = 15, P = 15,
T = 12, T = 12,
G = 9, G = 9,
@@ -28,28 +28,28 @@ pub const UnitScale = enum(i32) {
// Undefined // Undefined
_, _,
pub fn str(self: @This()) []const u8 { pub inline fn str(self: @This()) []const u8 {
var buf: [16]u8 = undefined; var buf: [16]u8 = undefined;
return switch (self) { return switch (self) {
.none => "", inline .none => "",
inline .P, .T, .G, .M, .k, .h, .da, .d, .c, .m, .u, .n, .p, .f, .min, .hour, .year => @tagName(self), inline .P, .T, .G, .M, .k, .h, .da, .d, .c, .m, .u, .n, .p, .f, .min, .hour, .year => @tagName(self),
else => std.fmt.bufPrint(&buf, "[{d}]", .{@intFromEnum(self)}) catch "[]", else => std.fmt.bufPrint(&buf, "[{d}]", .{@intFromEnum(self)}) catch "[]", // This cannot be inline because of non exhaustive enum, but that's ok, it is just str, not calculation
}; };
} }
/// Helper to get the actual scaling factor /// Helper to get the actual scaling factor
pub fn getFactor(self: @This()) f64 { pub inline fn getFactor(self: @This()) comptime_float {
return switch (self) { return switch (self) {
inline .P, .T, .G, .M, .k, .h, .da, .none, .d, .c, .m, .u, .n, .p, .f => std.math.pow(f64, 10.0, @floatFromInt(@intFromEnum(self))), inline .P, .T, .G, .M, .k, .h, .da, .none, .d, .c, .m, .u, .n, .p, .f => std.math.pow(f64, 10.0, @floatFromInt(@intFromEnum(self))),
else => @floatFromInt(@intFromEnum(self)), inline else => @floatFromInt(@intFromEnum(self)),
}; };
} }
/// Helper to get the actual scaling factor in i32 /// Helper to get the actual scaling factor in i32
pub fn getFactorInt(self: @This()) i32 { pub inline fn getFactorInt(self: @This()) comptime_int {
return switch (self) { return switch (self) {
inline .P, .T, .G, .M, .k, .h, .da, .none, .d, .c, .m, .u, .n, .p, .f => std.math.powi(i32, 10.0, @intFromEnum(self)) catch 0, inline .P, .T, .G, .M, .k, .h, .da, .none, .d, .c, .m, .u, .n, .p, .f => comptime std.math.powi(i32, 10.0, @intFromEnum(self)) catch 0,
else => @intFromEnum(self), inline else => comptime @intFromEnum(self),
}; };
} }
}; };
@@ -59,7 +59,7 @@ const Scales = @This();
data: std.EnumArray(Dimension, UnitScale), data: std.EnumArray(Dimension, UnitScale),
pub fn init(comptime init_val: anytype) Scales { pub fn init(comptime init_val: anytype) Scales {
var s = Scales{ .data = std.EnumArray(Dimension, UnitScale).initFill(.none) }; comptime var s = Scales{ .data = std.EnumArray(Dimension, UnitScale).initFill(.none) };
inline for (std.meta.fields(@TypeOf(init_val))) |f| { inline for (std.meta.fields(@TypeOf(init_val))) |f| {
if (comptime hlp.isInt(@TypeOf(@field(init_val, f.name)))) if (comptime hlp.isInt(@TypeOf(@field(init_val, f.name))))
s.data.set(@field(Dimension, f.name), @enumFromInt(@field(init_val, f.name))) s.data.set(@field(Dimension, f.name), @enumFromInt(@field(init_val, f.name)))
@@ -69,29 +69,29 @@ pub fn init(comptime init_val: anytype) Scales {
return s; return s;
} }
pub fn initFill(val: UnitScale) Scales { pub fn initFill(comptime val: UnitScale) Scales {
return .{ .data = std.EnumArray(Dimension, UnitScale).initFill(val) }; return comptime .{ .data = std.EnumArray(Dimension, UnitScale).initFill(val) };
} }
pub fn get(self: Scales, key: Dimension) UnitScale { pub fn get(comptime self: Scales, comptime key: Dimension) UnitScale {
return self.data.get(key); return comptime self.data.get(key);
} }
pub fn set(self: *Scales, key: Dimension, val: UnitScale) void { pub fn set(comptime self: *Scales, comptime key: Dimension, comptime val: UnitScale) void {
self.data.set(key, val); comptime self.data.set(key, val);
} }
pub fn min(comptime s1: Scales, comptime s2: Scales) Scales { pub fn min(comptime s1: Scales, comptime s2: Scales) Scales {
var out = Scales.initFill(.none); comptime var out = Scales.initFill(.none);
for (std.enums.values(Dimension)) |dim| inline for (std.enums.values(Dimension)) |dim|
out.set(dim, if (s1.get(dim).getFactorInt() > s2.get(dim).getFactorInt()) s2.get(dim) else s1.get(dim)); out.set(dim, if (s1.get(dim).getFactorInt() > s2.get(dim).getFactorInt()) s2.get(dim) else s1.get(dim));
return out; return out;
} }
pub fn getFactor(comptime s: Scales, comptime d: Dimensions) f64 { pub inline fn getFactor(comptime s: Scales, comptime d: Dimensions) comptime_float {
var factor: f64 = 1.0; comptime var factor: f64 = 1.0;
for (std.enums.values(Dimension)) |dim| { inline for (std.enums.values(Dimension)) |dim| {
const power = d.get(dim); const power = d.get(dim);
if (power == 0) continue; if (power == 0) continue;
+318
View File
@@ -0,0 +1,318 @@
const std = @import("std");
const hlp = @import("helper.zig");
const Scalar = @import("Scalar.zig").Scalar;
const Scales = @import("Scales.zig");
const UnitScale = Scales.UnitScale;
const Dimensions = @import("Dimensions.zig");
const Dimension = Dimensions.Dimension;
pub fn Vector(comptime len: usize, comptime Q: type) type {
const T = Q.ValueType;
const d: Dimensions = Q.dims;
const s: Scales = Q.scales;
return struct {
data: [len]T,
const Self = @This();
pub const ScalarType = Q;
pub const ValueType = T;
pub const dims: Dimensions = d;
pub const scales = s;
pub const zero = initDefault(0);
pub const one = initDefault(1);
pub fn initDefault(v: T) Self {
var data: [len]T = undefined;
inline for (&data) |*item| item.* = v;
return .{ .data = data };
}
pub inline fn add(self: Self, rhs: anytype) Vector(len, Scalar(T, d, s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d, s.min(Tr.scales))) = undefined;
inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).add(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value;
}
return res;
}
pub inline fn sub(self: Self, rhs: anytype) Vector(len, Scalar(T, d, s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d, s.min(Tr.scales))) = undefined;
inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).sub(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value;
}
return res;
}
pub inline fn divBy(
self: Self,
rhs: anytype,
) Vector(len, Scalar(T, d.sub(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d.sub(Tr.dims), s.min(Tr.scales))) = undefined;
inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).divBy(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value;
}
return res;
}
pub inline fn mulBy(
self: Self,
rhs: anytype,
) Vector(len, Scalar(T, d.add(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
var res: Vector(len, Scalar(T, d.add(Tr.dims), s.min(Tr.scales))) = undefined;
inline for (self.data, 0..) |v, i| {
const q = (Q{ .value = v }).mulBy(Tr.ScalarType{ .value = rhs.data[i] });
res.data[i] = q.value;
}
return res;
}
pub inline fn divByScalar(
self: Self,
scalar: anytype,
) Vector(len, Scalar(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) {
var res: Vector(len, Scalar(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) = undefined;
inline for (self.data, 0..) |v, i| {
const q = Q{ .value = v };
res.data[i] = q.divBy(scalar).value;
}
return res;
}
pub inline fn mulByScalar(
self: Self,
scalar: anytype,
) Vector(len, Scalar(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) {
var res: Vector(len, Scalar(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) = undefined;
inline for (self.data, 0..) |v, i| {
const q = Q{ .value = v };
res.data[i] = q.mulBy(scalar).value;
}
return res;
}
pub fn negate(self: Self) Self {
var res: Self = undefined;
inline for (self.data, 0..) |v, i| {
res.data[i] = -v;
}
return res;
}
pub inline fn to(self: Self, comptime DestQ: type) Vector(len, DestQ) {
var res: Vector(len, DestQ) = undefined;
inline for (self.data, 0..) |v, i| {
res.data[i] = (Q{ .value = v }).to(DestQ).value;
}
return res;
}
pub inline fn lengthSqr(self: Self) T {
var sum: T = 0;
inline for (self.data) |v| {
sum += v * v;
}
return sum;
}
pub inline fn length(self: Self) T {
const len_sq = self.lengthSqr();
if (comptime @typeInfo(T) == .int) {
// Construct the unsigned equivalent of T at comptime (e.g., i32 -> u32)
const UnsignedT = @Int(.unsigned, @typeInfo(T).int.bits);
// len_sq is always positive, so @intCast is perfectly safe
const u_len_sq = @as(UnsignedT, @intCast(len_sq));
return @as(T, @intCast(std.math.sqrt(u_len_sq)));
} else {
return @sqrt(len_sq);
}
}
pub fn formatNumber(
self: Self,
writer: *std.Io.Writer,
options: std.fmt.Number,
) !void {
try writer.writeAll("(");
for (self.data, 0..) |v, i| {
if (i > 0) try writer.writeAll(", ");
switch (@typeInfo(T)) {
.float, .comptime_float => try writer.printFloat(v, options),
.int, .comptime_int => try writer.printInt(v, 10, .lower, .{
.width = options.width,
.alignment = options.alignment,
.fill = options.fill,
.precision = options.precision,
}),
else => unreachable,
}
}
try writer.writeAll(")");
var first = true;
inline for (std.enums.values(Dimension)) |bu| {
const v = dims.get(bu);
if (comptime v == 0) continue;
if (!first)
try writer.writeAll(".");
first = false;
const uscale = scales.get(bu);
if (bu == .T and (uscale == .min or uscale == .hour or uscale == .year))
try writer.print("{s}", .{uscale.str()})
else
try writer.print("{s}{s}", .{ uscale.str(), bu.unit() });
if (v != 1)
try hlp.printSuperscript(writer, v);
}
}
};
}
test "Format VectorX" {
const MeterPerSecondSq = Scalar(
f32,
Dimensions.init(.{ .L = 1, .T = -2 }),
Scales.init(.{ .T = .n }),
);
const KgMeterPerSecond = Scalar(
f32,
Dimensions.init(.{ .M = 1, .L = 1, .T = -1 }),
Scales.init(.{ .M = .k }),
);
const accel = MeterPerSecondSq.Vec3.initDefault(9.81);
const momentum = KgMeterPerSecond.Vec3{ .data = .{ 43, 0, 11 } };
var buf: [64]u8 = undefined;
var res = try std.fmt.bufPrint(&buf, "{d}", .{accel});
try std.testing.expectEqualStrings("(9.81, 9.81, 9.81)m.ns⁻²", res);
res = try std.fmt.bufPrint(&buf, "{d:.2}", .{momentum});
try std.testing.expectEqualStrings("(43.00, 0.00, 11.00)m.kg.s⁻¹", res);
}
test "VecX Init and Basic Arithmetic" {
const Meter = Scalar(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Vec3M = Meter.Vec3;
// Test zero, one, initDefault
const v_zero = Vec3M.zero;
try std.testing.expectEqual(0, v_zero.data[0]);
try std.testing.expectEqual(0, v_zero.data[1]);
try std.testing.expectEqual(0, v_zero.data[2]);
const v_one = Vec3M.one;
try std.testing.expectEqual(1, v_one.data[0]);
try std.testing.expectEqual(1, v_one.data[1]);
try std.testing.expectEqual(1, v_one.data[2]);
const v_def = Vec3M.initDefault(5);
try std.testing.expectEqual(5, v_def.data[0]);
try std.testing.expectEqual(5, v_def.data[1]);
try std.testing.expectEqual(5, v_def.data[2]);
// Test add and sub
const v1 = Vec3M{ .data = .{ 10, 20, 30 } };
const v2 = Vec3M{ .data = .{ 2, 4, 6 } };
const added = v1.add(v2);
try std.testing.expectEqual(12, added.data[0]);
try std.testing.expectEqual(24, added.data[1]);
try std.testing.expectEqual(36, added.data[2]);
const subbed = v1.sub(v2);
try std.testing.expectEqual(8, subbed.data[0]);
try std.testing.expectEqual(16, subbed.data[1]);
try std.testing.expectEqual(24, subbed.data[2]);
// Test negate
const neg = v1.negate();
try std.testing.expectEqual(-10, neg.data[0]);
try std.testing.expectEqual(-20, neg.data[1]);
try std.testing.expectEqual(-30, neg.data[2]);
}
test "VecX Kinematics (Scalar Mul/Div)" {
const Meter = Scalar(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Scalar(i32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const Vec3M = Meter.Vec3;
const pos = Vec3M{ .data = .{ 100, 200, 300 } };
const time = Second{ .value = 10 };
// Vector divided by scalar (Velocity = Position / Time)
const vel = pos.divByScalar(time);
try std.testing.expectEqual(10, vel.data[0]);
try std.testing.expectEqual(20, vel.data[1]);
try std.testing.expectEqual(30, vel.data[2]);
try std.testing.expectEqual(1, @TypeOf(vel).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(vel).dims.get(.T));
// Vector multiplied by scalar (Position = Velocity * Time)
const new_pos = vel.mulByScalar(time);
try std.testing.expectEqual(100, new_pos.data[0]);
try std.testing.expectEqual(200, new_pos.data[1]);
try std.testing.expectEqual(300, new_pos.data[2]);
try std.testing.expectEqual(1, @TypeOf(new_pos).dims.get(.L));
try std.testing.expectEqual(0, @TypeOf(new_pos).dims.get(.T));
}
test "VecX Element-wise Math and Scaling" {
const Meter = Scalar(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Vec3M = Meter.Vec3;
const v1 = Vec3M{ .data = .{ 10, 20, 30 } };
const v2 = Vec3M{ .data = .{ 2, 5, 10 } };
// Element-wise division
const div = v1.divBy(v2);
try std.testing.expectEqual(5, div.data[0]);
try std.testing.expectEqual(4, div.data[1]);
try std.testing.expectEqual(3, div.data[2]);
try std.testing.expectEqual(0, @TypeOf(div).dims.get(.L)); // M / M = Dimensionless
}
test "VecX Conversions" {
const KiloMeter = Scalar(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const Meter = Scalar(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const v_km = KiloMeter.Vec3{ .data = .{ 1, 2, 3 } };
const v_m = v_km.to(Meter);
try std.testing.expectEqual(1000, v_m.data[0]);
try std.testing.expectEqual(2000, v_m.data[1]);
try std.testing.expectEqual(3000, v_m.data[2]);
// Type checking the result
try std.testing.expectEqual(1, @TypeOf(v_m).dims.get(.L));
try std.testing.expectEqual(UnitScale.none, @TypeOf(v_m).scales.get(.L));
}
test "VecX Length" {
const MeterInt = Scalar(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const MeterFloat = Scalar(f32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
// Integer length (using your custom isqrt)
// 3-4-5 triangle on XY plane
const v_int = MeterInt.Vec3{ .data = .{ 3, 4, 0 } };
try std.testing.expectEqual(25, v_int.lengthSqr());
try std.testing.expectEqual(5, v_int.length());
// Float length
const v_float = MeterFloat.Vec3{ .data = .{ 3.0, 4.0, 0.0 } };
try std.testing.expectApproxEqAbs(@as(f32, 25.0), v_float.lengthSqr(), 1e-4);
try std.testing.expectApproxEqAbs(@as(f32, 5.0), v_float.length(), 1e-4);
}
+429
View File
@@ -0,0 +1,429 @@
const std = @import("std");
const Io = std.Io;
const Scalar = @import("Scalar.zig").Scalar;
const Vector = @import("Vector.zig").Vector;
var io: Io = undefined;
pub fn main(init: std.process.Init) !void {
var stdout_buf: [4096]u8 = undefined;
var stdout_writer: std.Io.File.Writer = .init(.stdout(), init.io, &stdout_buf);
try stdout_writer.interface.print("Starting Benchmarks...", .{});
io = init.io;
try bench_Scalar(&stdout_writer.interface);
try stdout_writer.flush();
try bench_vsNative(&stdout_writer.interface);
try stdout_writer.flush();
try bench_crossTypeVsNative(&stdout_writer.interface);
try stdout_writer.flush();
try bench_Vector(&stdout_writer.interface);
try stdout_writer.flush();
}
fn getTime() Io.Timestamp {
return Io.Clock.awake.now(io);
}
fn fold(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
fn bench_Scalar(writer: *std.Io.Writer) !void {
const ITERS: usize = 100_000;
const SAMPLES: usize = 10;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Stats = struct {
median: f64,
delta: f64,
ops_per_sec: f64,
};
const computeStats = struct {
fn f(samples: []f64, iters: usize) Stats {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0) (samples[mid - 1] + samples[mid]) / 2.0 else samples[mid];
const low = samples[0];
const high = samples[samples.len - 1];
const delta_ns = (high - low) / 2.0;
const ns_per_op = median_ns / @as(f64, @floatFromInt(iters));
return .{
.median = ns_per_op,
.delta = (delta_ns / @as(f64, @floatFromInt(iters))),
.ops_per_sec = 1_000_000_000.0 / ns_per_op,
};
}
}.f;
try writer.print(
\\
\\ Scalar<T> benchmark — {d} iterations, {d} samples/cell
\\
\\┌───────────────────┬──────┬─────────────────────┬─────────────────────┐
\\│ Operation │ Type │ ns / op (± delta) │ Throughput (ops/s) │
\\├───────────────────┼──────┼─────────────────────┼─────────────────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i16, i32, i64, i128, i256, f32, f64, f128 };
const TNames = .{ "i16", "i32", "i64", "i128", "i256", "f32", "f64", "f128" };
const Ops = .{ "add", "sub", "mulBy", "divBy", "to" };
var results_matrix: [Ops.len][Types.len]f64 = undefined;
comptime var tidx: usize = 0;
inline for (Types, TNames) |T, tname| {
const M = Scalar(T, .init(.{ .L = 1 }), .init(.{}));
const KM = Scalar(T, .init(.{ .L = 1 }), .init(.{ .L = .k }));
const S = Scalar(T, .init(.{ .T = 1 }), .init(.{}));
inline for (Ops, 0..) |op_name, oidx| {
var samples: [SAMPLES]f64 = undefined;
for (0..SAMPLES) |s_idx| {
const t_start = getTime();
for (0..ITERS) |i| {
std.mem.doNotOptimizeAway(
{
_ = if (comptime std.mem.eql(u8, op_name, "add"))
(M{ .value = getVal(T, i, 63) }).add(M{ .value = getVal(T, i +% 7, 63) })
else if (comptime std.mem.eql(u8, op_name, "sub"))
(M{ .value = getVal(T, i +% 10, 63) }).sub(M{ .value = getVal(T, i, 63) })
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
(M{ .value = getVal(T, i, 63) }).mulBy(M{ .value = getVal(T, i +% 1, 63) })
else if (comptime std.mem.eql(u8, op_name, "divBy"))
(M{ .value = getVal(T, i +% 10, 63) }).divBy(S{ .value = getVal(T, i, 63) })
else
(KM{ .value = getVal(T, i, 15) }).to(M);
},
);
}
const t_end = getTime();
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
}
const stats = computeStats(&samples, ITERS);
results_matrix[oidx][tidx] = stats.median;
try writer.print("│ {s:<17} │ {s:<4} │ {d:>8.2} ns ±{d:<6.2} │ {d:>19.0} │\n", .{ op_name, tname, stats.median, stats.delta, stats.ops_per_sec });
}
if (comptime tidx < Types.len - 1) {
try writer.print("├───────────────────┼──────┼─────────────────────┼─────────────────────┤\n", .{});
}
tidx += 1;
}
// Median Summary Table
try writer.print("└───────────────────┴──────┴─────────────────────┴─────────────────────┘\n\n", .{});
try writer.print("Median Summary (ns/op):\n", .{});
try writer.print("┌──────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n", .{});
try writer.print("│ Operation │ i16 │ i32 │ i64 │ i128 │ i256 │ f32 │ f64 │ f128 │\n", .{});
try writer.print("├──────────────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┤\n", .{});
inline for (Ops, 0..) |op_name, oidx| {
try writer.print("│ {s:<11} │", .{op_name});
var i: usize = 0;
while (i < Types.len) : (i += 1)
try writer.print("{d:>6.1} │", .{results_matrix[oidx][i]});
try writer.print("\n", .{});
}
try writer.print("└──────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n", .{});
}
fn bench_vsNative(writer: *std.Io.Writer) !void {
const ITERS: usize = 100_000;
const SAMPLES: usize = 5;
// Helper to safely get a value of type T from a loop index
const getValT = struct {
fn f(comptime TT: type, i: usize) TT {
const v = (i % 100) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Types = .{ i32, i64, i128, f32, f64 };
const TNames = .{ "i32", "i64", "i128", "f32", "f64" };
const Ops = .{ "add", "mulBy", "divBy" };
try writer.print(
\\
\\ Scalar vs Native Overhead Analysis
\\
\\┌───────────┬──────┬───────────┬───────────┬───────────┐
\\│ Operation │ Type │ Native │ Scalar │ Slowdown │
\\├───────────┼──────┼───────────┼───────────┼───────────┤
\\
, .{});
inline for (Ops, 0..) |op_name, j| {
inline for (Types, 0..) |T, tidx| {
var native_total_ns: f64 = 0;
var quantity_total_ns: f64 = 0;
const M = Scalar(T, .init(.{ .L = 1 }), .init(.{}));
const S = Scalar(T, .init(.{ .T = 1 }), .init(.{}));
std.mem.doNotOptimizeAway({
for (0..SAMPLES) |_| {
// --- 1. Benchmark Native ---
const n_start = getTime();
for (0..ITERS) |i| {
const a = getValT(T, i);
const b = getValT(T, 2);
_ = if (comptime std.mem.eql(u8, op_name, "add"))
a + b
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
a * b
else if (comptime @typeInfo(T) == .int) @divTrunc(a, b) else a / b;
}
const n_end = getTime();
native_total_ns += @as(f64, @floatFromInt(n_start.durationTo(n_end).toNanoseconds()));
// --- 2. Benchmark Scalar ---
const q_start = getTime();
for (0..ITERS) |i| {
const qa = M{ .value = getValT(T, i) };
const qb = if (comptime std.mem.eql(u8, op_name, "divBy")) S{ .value = getValT(T, 2) } else M{ .value = getValT(T, 2) };
_ = if (comptime std.mem.eql(u8, op_name, "add"))
qa.add(qb)
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
qa.mulBy(qb)
else
qa.divBy(qb);
}
const q_end = getTime();
quantity_total_ns += @as(f64, @floatFromInt(q_start.durationTo(q_end).toNanoseconds()));
}
});
const avg_n = (native_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const avg_q = (quantity_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const slowdown = avg_q / avg_n;
try writer.print("│ {s:<9} │ {s:<4} │ {d:>7.2}ns │ {d:>7.2}ns │ {d:>8.2}x │\n", .{
op_name, TNames[tidx], avg_n, avg_q, slowdown,
});
}
if (j != Ops.len - 1) try writer.print("├───────────┼──────┼───────────┼───────────┼───────────┤\n", .{});
}
try writer.print("└───────────┴──────┴───────────┴───────────┴───────────┘\n", .{});
}
fn bench_crossTypeVsNative(writer: *std.Io.Writer) !void {
const ITERS: usize = 100_000;
const SAMPLES: usize = 5;
const getValT = struct {
fn f(comptime TT: type, i: usize) TT {
// Keep values safe and non-zero to avoid division by zero or overflows during cross-casting
const v = (i % 50) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
// Helper for the Native baseline: explicitly casting T2 to T1 before the operation
const castTo = struct {
fn f(comptime DestT: type, comptime SrcT: type, val: SrcT) DestT {
if (comptime DestT == SrcT) return val;
const src_info = @typeInfo(SrcT);
const dest_info = @typeInfo(DestT);
if (dest_info == .int and src_info == .int) return @intCast(val);
if (dest_info == .float and src_info == .int) return @floatFromInt(val);
if (dest_info == .int and src_info == .float) return @intFromFloat(val);
if (dest_info == .float and src_info == .float) return @floatCast(val);
unreachable;
}
}.f;
const Types = .{ i16, i64, i128, f32, f64 };
const TNames = .{ "i16", "i64", "i128", "f32", "f64" };
const Ops = .{ "add", "mulBy", "divBy" };
try writer.print(
\\
\\ Cross-Type Overhead Analysis: Scalar vs Native
\\
\\┌─────────┬──────┬──────┬───────────┬───────────┬───────────┐
\\│ Op │ T1 │ T2 │ Native │ Scalar │ Slowdown │
\\├─────────┼──────┼──────┼───────────┼───────────┼───────────┤
\\
, .{});
inline for (Ops, 0..) |op_name, j| {
inline for (Types, 0..) |T1, t1_idx| {
inline for (Types, 0..) |T2, t2_idx| {
var native_total_ns: f64 = 0;
var quantity_total_ns: f64 = 0;
const M1 = Scalar(T1, .init(.{ .L = 1 }), .init(.{}));
const M2 = Scalar(T2, .init(.{ .L = 1 }), .init(.{}));
const S2 = Scalar(T2, .init(.{ .T = 1 }), .init(.{}));
std.mem.doNotOptimizeAway({
for (0..SAMPLES) |_| {
// --- 1. Benchmark Native (Cast T2 to T1, then math) ---
const n_start = getTime();
for (0..ITERS) |i| {
const a = getValT(T1, i);
const b_raw = getValT(T2, 2);
const b = castTo(T1, T2, b_raw);
_ = if (comptime std.mem.eql(u8, op_name, "add"))
a + b
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
a * b
else if (comptime @typeInfo(T1) == .int)
@divTrunc(a, b)
else
a / b;
}
const n_end = getTime();
native_total_ns += @as(f64, @floatFromInt(n_start.durationTo(n_end).toNanoseconds()));
// --- 2. Benchmark Scalar ---
const q_start = getTime();
for (0..ITERS) |i| {
const qa = M1{ .value = getValT(T1, i) };
const qb = if (comptime std.mem.eql(u8, op_name, "divBy"))
S2{ .value = getValT(T2, 2) }
else
M2{ .value = getValT(T2, 2) };
_ = if (comptime std.mem.eql(u8, op_name, "add"))
qa.add(qb)
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
qa.mulBy(qb)
else
qa.divBy(qb);
}
const q_end = getTime();
quantity_total_ns += @as(f64, @floatFromInt(q_start.durationTo(q_end).toNanoseconds()));
}
const avg_n = (native_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const avg_q = (quantity_total_ns / SAMPLES) / @as(f64, @floatFromInt(ITERS));
const slowdown = avg_q / avg_n;
try writer.print("│ {s:<7} │ {s:<4} │ {s:<4} │ {d:>7.2}ns │ {d:>7.2}ns │ {d:>8.2}x │\n", .{
op_name, TNames[t1_idx], TNames[t2_idx], avg_n, avg_q, slowdown,
});
});
}
}
if (j != Ops.len - 1) {
try writer.print("├─────────┼──────┼──────┼───────────┼───────────┼───────────┤\n", .{});
}
}
try writer.print("└─────────┴──────┴──────┴───────────┴───────────┴───────────┘\n", .{});
}
fn bench_Vector(writer: *std.Io.Writer) !void {
const ITERS: usize = 10_000;
const SAMPLES: usize = 10;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const computeStats = struct {
fn f(samples: []f64, iters: usize) f64 {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0)
(samples[mid - 1] + samples[mid]) / 2.0
else
samples[mid];
return median_ns / @as(f64, @floatFromInt(iters));
}
}.f;
try writer.print(
\\
\\ Vector<N, T> benchmark — {d} iterations, {d} samples/cell
\\ (Results in ns/op)
\\
\\┌─────────────┬──────┬─────────┬─────────┬─────────┐
\\│ Operation │ Type │ Len=3 │ Len=4 │ Len=16 │
\\├─────────────┼──────┼─────────┼─────────┼─────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i32, i64, i128, f32, f64 };
const TNames = .{ "i32", "i64", "i128", "f32", "f64" };
const Lengths = .{ 3, 4, 16 };
const Ops = .{ "add", "divBy", "mulByScalar", "length" };
inline for (Ops, 0..) |op_name, o_idx| {
inline for (Types, TNames) |T, tname| {
try writer.print("│ {s:<11} │ {s:<4} │", .{ op_name, tname });
inline for (Lengths) |len| {
const Q_base = Scalar(T, .init(.{ .L = 1 }), .init(.{}));
const Q_time = Scalar(T, .init(.{ .T = 1 }), .init(.{}));
const V = Vector(len, Q_base);
var samples: [SAMPLES]f64 = undefined;
std.mem.doNotOptimizeAway({
for (0..SAMPLES) |s_idx| {
const t_start = getTime();
for (0..ITERS) |i| {
const v1 = V.initDefault(getVal(T, i, 63));
if (comptime std.mem.eql(u8, op_name, "add")) {
const v2 = V.initDefault(getVal(T, i +% 7, 63));
_ = v1.add(v2);
} else if (comptime std.mem.eql(u8, op_name, "divBy")) {
_ = v1.divBy(V.initDefault(getVal(T, i +% 2, 63)));
} else if (comptime std.mem.eql(u8, op_name, "mulByScalar")) {
const s_val = Q_time{ .value = getVal(T, i +% 2, 63) };
_ = v1.mulByScalar(s_val);
} else if (comptime std.mem.eql(u8, op_name, "length")) {
_ = v1.length();
}
}
const t_end = getTime();
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
}
const median_ns_per_op = computeStats(&samples, ITERS);
try writer.print(" {d:>7.1} │", .{median_ns_per_op});
});
}
try writer.print("\n", .{});
}
if (o_idx < Ops.len - 1) {
try writer.print("├─────────────┼──────┼─────────┼─────────┼─────────┤\n", .{});
}
}
try writer.print("└─────────────┴──────┴─────────┴─────────┴─────────┘\n", .{});
}
+12 -822
View File
@@ -1,826 +1,16 @@
const std = @import("std"); const std = @import("std");
const hlp = @import("helper.zig");
const Scales = @import("Scales.zig"); pub const Scalar = @import("Scalar.zig").Scalar;
const UnitScale = Scales.UnitScale; pub const Vector = @import("Vector.zig").Vector;
const Dimensions = @import("Dimensions.zig"); pub const Dimensions = @import("Dimensions.zig");
const Dimension = Dimensions.Dimension; pub const Scales = @import("Scales.zig");
pub const Base = @import("Base.zig");
pub fn Quantity(T: type, d: Dimensions, s: Scales) type { test {
return struct { _ = @import("Scalar.zig");
value: T, _ = @import("Vector.zig");
_ = @import("Dimensions.zig");
const Self = @This(); _ = @import("Scales.zig");
pub const Vec3: type = QuantityVec3(Self); _ = @import("Base.zig");
pub const ValueType: type = T; _ = @import("helper.zig");
pub const dims: Dimensions = d;
pub const scales = s;
/// Internal helper to convert any supported T to f64 for math
fn toF64(val: anytype) f64 {
const TIn = @TypeOf(val);
return switch (@typeInfo(TIn)) {
.int => @floatFromInt(val),
.float => @floatCast(val),
else => @compileError("Unsupported type for Quantity"),
};
}
/// Internal helper to convert f64 back to the target T
fn fromF64(val: f64) T {
return switch (@typeInfo(T)) {
.int => @intFromFloat(@round(val)),
.float => @floatCast(val),
else => unreachable,
};
}
/// Helper for integer power of 10 at comptime
fn pow10(comptime exp: i32) T {
var res: T = 1;
var i: i32 = 0;
const abs_exp = if (exp < 0) -exp else exp;
while (i < abs_exp) : (i += 1) res *= 10;
return res;
}
pub fn add(self: Self, rhs: anytype) Quantity(
T,
dims,
scales.min(@TypeOf(rhs).scales),
) {
if (comptime !dims.eql(@TypeOf(rhs).dims))
@compileError("Dimension mismatch in add");
const TargetType = Quantity(T, dims, scales.min(@TypeOf(rhs).scales));
const lhs_converted = self.to(TargetType);
const rhs_converted = rhs.to(TargetType);
return .{ .value = lhs_converted.value + rhs_converted.value };
}
pub fn sub(self: Self, rhs: anytype) Quantity(
T,
dims,
scales.min(@TypeOf(rhs).scales),
) {
if (comptime !dims.eql(@TypeOf(rhs).dims))
@compileError("Dimension mismatch in sub");
const TargetType = Quantity(T, dims, scales.min(@TypeOf(rhs).scales));
const lhs_converted = self.to(TargetType);
const rhs_converted = rhs.to(TargetType);
return .{ .value = lhs_converted.value - rhs_converted.value };
}
pub fn mulBy(self: Self, rhs: anytype) Quantity(
T,
dims.add(@TypeOf(rhs).dims),
scales.min(@TypeOf(rhs).scales),
) {
const self_ = self.to(Quantity(T, dims, scales.min(@TypeOf(rhs).scales)));
const rhs_ = rhs.to(Quantity(T, @TypeOf(rhs).dims, scales.min(@TypeOf(rhs).scales)));
return .{ .value = self_.value * rhs_.value };
}
pub fn divBy(self: Self, rhs: anytype) Quantity(
T,
dims.sub(@TypeOf(rhs).dims),
scales.min(@TypeOf(rhs).scales),
) {
const self_ = self.to(Quantity(T, dims, scales.min(@TypeOf(rhs).scales)));
const rhs_ = rhs.to(Quantity(T, @TypeOf(rhs).dims, scales.min(@TypeOf(rhs).scales)));
return .{ .value = fromF64((toF64(self_.value) / toF64(rhs_.value))) };
}
pub fn scale(self: Self, sc: T) Self {
return .{ .value = self.value * sc };
}
pub fn to(self: Self, comptime Dest: type) Dest {
if (comptime !dims.eql(Dest.dims))
@compileError("Dimension mismatch: " ++ dims.str() ++ " vs " ++ Dest.dims.str());
if (comptime @TypeOf(self) == Dest)
return self;
const source_factor = scales.getFactor(dims);
const dest_factor = Dest.scales.getFactor(Dest.dims);
const ratio = source_factor / dest_factor;
const result_f = toF64(self.value) * ratio;
const DestT = Dest.ValueType;
return .{ .value = switch (@typeInfo(DestT)) {
.int => @intFromFloat(@round(result_f)),
.float => @floatCast(result_f),
else => unreachable,
} };
}
pub fn vec3(self: Self) Vec3 {
return .{ .x = self.value, .y = self.value, .z = self.value };
}
pub fn format(
self: Self,
writer: *std.Io.Writer,
) !void {
try writer.print("{d}", .{self.value});
var iter = std.EnumSet(Dimension).initFull().iterator();
var first = true;
while (iter.next()) |bu| {
const v = dims.get(bu);
if (v == 0) continue;
if (!first)
try writer.writeAll(".");
first = false;
const uscale = scales.get(bu);
if (bu == .T and (uscale == .min or uscale == .hour or uscale == .year))
try writer.print("{s}", .{uscale.str()})
else
try writer.print("{s}{s}", .{ uscale.str(), bu.unit() });
if (v != 1)
try hlp.printSuperscript(writer, v);
}
}
};
}
pub fn QuantityVec3(Q: type) type {
const T = Q.ValueType;
const d: Dimensions = Q.dims;
const s: Scales = Q.scales;
return struct {
x: T,
y: T,
z: T,
const Self = @This();
pub const QuantityType = Q;
pub const ValueType = T;
pub const dims: Dimensions = d;
pub const scales = s;
pub const zero = Self{ .x = 0, .y = 0, .z = 0 };
pub const one = Self{ .x = 1, .y = 1, .z = 1 };
pub fn initDefault(v: T) Self {
return .{ .x = v, .y = v, .z = v };
}
pub fn add(self: Self, rhs: anytype) QuantityVec3(Quantity(T, d, s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
// We leverage the logic in the scalar Quantity.add
const qx = (Q{ .value = self.x }).add(Tr.QuantityType{ .value = rhs.x });
const qy = (Q{ .value = self.y }).add(Tr.QuantityType{ .value = rhs.y });
const qz = (Q{ .value = self.z }).add(Tr.QuantityType{ .value = rhs.z });
return .{
.x = qx.value,
.y = qy.value,
.z = qz.value,
};
}
pub fn sub(self: Self, rhs: anytype) QuantityVec3(Quantity(T, d, s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
const qx = (Q{ .value = self.x }).sub(Tr.QuantityType{ .value = rhs.x });
const qy = (Q{ .value = self.y }).sub(Tr.QuantityType{ .value = rhs.y });
const qz = (Q{ .value = self.z }).sub(Tr.QuantityType{ .value = rhs.z });
return .{
.x = qx.value,
.y = qy.value,
.z = qz.value,
};
}
pub fn divBy(
self: Self,
rhs: anytype,
) QuantityVec3(Quantity(T, d.sub(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
return .{
.x = (Q{ .value = self.x }).divBy(Tr.QuantityType{ .value = rhs.x }).value,
.y = (Q{ .value = self.y }).divBy(Tr.QuantityType{ .value = rhs.y }).value,
.z = (Q{ .value = self.z }).divBy(Tr.QuantityType{ .value = rhs.z }).value,
};
}
pub fn mulBy(
self: Self,
rhs: anytype,
) QuantityVec3(Quantity(T, d.sub(@TypeOf(rhs).dims), s.min(@TypeOf(rhs).scales))) {
const Tr = @TypeOf(rhs);
return .{
.x = (Q{ .value = self.x }).mulBy(Tr.QuantityType{ .value = rhs.x }).value,
.y = (Q{ .value = self.y }).mulBy(Tr.QuantityType{ .value = rhs.y }).value,
.z = (Q{ .value = self.z }).mulBy(Tr.QuantityType{ .value = rhs.z }).value,
};
}
pub fn divByScalar(
self: Self,
scalar: anytype,
) QuantityVec3(Quantity(T, d.sub(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) {
const q_x = Q{ .value = self.x };
const q_y = Q{ .value = self.y };
const q_z = Q{ .value = self.z };
return .{
.x = q_x.divBy(scalar).value,
.y = q_y.divBy(scalar).value,
.z = q_z.divBy(scalar).value,
};
}
pub fn mulByScalar(
self: Self,
scalar: anytype,
) QuantityVec3(Quantity(T, d.add(@TypeOf(scalar).dims), s.min(@TypeOf(scalar).scales))) {
const q_x = Q{ .value = self.x };
const q_y = Q{ .value = self.y };
const q_z = Q{ .value = self.z };
return .{
.x = q_x.mulBy(scalar).value,
.y = q_y.mulBy(scalar).value,
.z = q_z.mulBy(scalar).value,
};
}
pub fn negate(self: Self) Self {
return .{ .x = -self.x, .y = -self.y, .z = -self.z };
}
pub fn scale(self: Self, rhs: T) Self {
return .{
.x = (Q{ .value = self.x }).scale(rhs).value,
.y = (Q{ .value = self.y }).scale(rhs).value,
.z = (Q{ .value = self.z }).scale(rhs).value,
};
}
pub fn to(self: Self, comptime DestQ: type) QuantityVec3(DestQ) {
return .{
.x = (Q{ .value = self.x }).to(DestQ).value,
.y = (Q{ .value = self.y }).to(DestQ).value,
.z = (Q{ .value = self.z }).to(DestQ).value,
};
}
pub fn format(self: Self, writer: *std.Io.Writer) !void {
try writer.print("({d:.2}, {d:.2}, {d:.2})", .{ self.x, self.y, self.z });
var iter = std.EnumSet(Dimension).initFull().iterator();
var first = true;
while (iter.next()) |bu| {
const v = dims.get(bu);
if (v == 0) continue;
if (!first) try writer.writeAll(".");
first = false;
try writer.print("{s}{s}", .{ scales.get(bu).str(), bu.unit() });
if (v != 1) try hlp.printSuperscript(writer, v);
}
}
pub fn lengthSqr(self: Self) T {
return self.x * self.x + self.y * self.y + self.z * self.z;
}
pub fn length(self: Self) T {
if (comptime hlp.isInt(T))
return self.isqrt()
else
return @sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
}
fn isqrt(self: Self) T {
const squared_sum = (self.x * self.x) + (self.y * self.y) + (self.z * self.z);
if (squared_sum <= 0) return 0;
var x = squared_sum;
var y = @divTrunc(x + 1, 2);
while (y < x) {
x = y;
y = @divTrunc(x + @divTrunc(squared_sum, x), 2);
}
return x;
}
};
}
pub fn main(_: std.process.Init) void {}
test "Generate quantity" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = -3 }));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{ .T = .n }));
const distance = Meter{ .value = 10 };
const time = Second{ .value = 2 };
try std.testing.expectEqual(10, distance.value);
try std.testing.expectEqual(2, time.value);
}
test "Add" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const distance = Meter{ .value = 10 };
const distance2 = Meter{ .value = 20 };
const added = distance.add(distance2);
try std.testing.expectEqual(30, added.value);
try std.testing.expectEqual(1, @TypeOf(added).dims.get(.L));
std.debug.print("KiloMeter {f} + {f} = {f} OK\n", .{ distance, distance2, added });
const KiloMeter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const distance3 = KiloMeter{ .value = 2 };
const added2 = distance.add(distance3);
try std.testing.expectEqual(2010, added2.value);
try std.testing.expectEqual(1, @TypeOf(added2).dims.get(.L));
std.debug.print("KiloMeter {f} + {f} = {f} OK\n", .{ distance, distance3, added2 });
const added3 = distance3.add(distance).to(KiloMeter);
try std.testing.expectEqual(2, added3.value);
try std.testing.expectEqual(1, @TypeOf(added3).dims.get(.L));
std.debug.print("KiloMeter {f} + {f} = {f} OK\n", .{ distance3, distance, added3 });
const KiloMeter_f = Quantity(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const distance4 = KiloMeter_f{ .value = 2 };
const added4 = distance4.add(distance).to(KiloMeter_f);
try std.testing.expectApproxEqAbs(2.01, added4.value, 0.000001);
try std.testing.expectEqual(1, @TypeOf(added4).dims.get(.L));
std.debug.print("KiloMeter_f {f} + {f} = {f} OK\n", .{ distance4, distance, added4 });
}
test "Sub" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const KiloMeter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const KiloMeter_f = Quantity(f64, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const a = Meter{ .value = 500 };
const b = Meter{ .value = 200 };
const diff = a.sub(b);
try std.testing.expectEqual(300, diff.value);
std.debug.print("Sub: {f} - {f} = {f} OK\n", .{ a, b, diff });
const km = KiloMeter{ .value = 1 };
const diff2 = a.sub(km);
std.debug.print("Sub cross-scale: {f} - {f} = {f}\n", .{ a, km, diff2 });
const km_f = KiloMeter_f{ .value = 2.5 };
const m_f = Meter{ .value = 500 };
const diff3 = km_f.sub(m_f);
try std.testing.expectApproxEqAbs(2000, diff3.value, 1e-4);
std.debug.print("Sub float cross-scale: {f} - {f} = {f} OK\n", .{ km_f, m_f, diff3 });
}
test "MulBy" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 3.0 };
const t = Second{ .value = 4.0 };
const area_time = d.mulBy(t);
try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, t, area_time });
const d2 = Meter{ .value = 5.0 };
const area = d.mulBy(d2);
try std.testing.expectEqual(15, area.value);
try std.testing.expectEqual(2, @TypeOf(area).dims.get(.L));
try std.testing.expectEqual(0, @TypeOf(area).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, d2, area });
}
test "MulBy with scale" {
const KiloMeter = Quantity(f32, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const KiloGram = Quantity(f32, Dimensions.init(.{ .M = 1 }), Scales.init(.{ .M = .k }));
const dist = KiloMeter{ .value = 2.0 };
const mass = KiloGram{ .value = 3.0 };
const prod = dist.mulBy(mass);
try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(prod).dims.get(.M));
std.debug.print("MulBy scaled: {f} * {f} = {f} OK\n", .{ dist, mass, prod });
}
test "MulBy with type change" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const KmSec = Quantity(f32, Dimensions.init(.{ .L = 1, .T = 1 }), Scales.init(.{ .L = .k }));
const d = Meter{ .value = 3.0 };
const t = Second{ .value = 4.0 };
const area_time = d.mulBy(t).to(KmSec);
try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, t, area_time });
}
test "MulBy small" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .n }));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 3.0 };
const t = Second{ .value = 4.0 };
const area_time = d.mulBy(t);
try std.testing.expectEqual(12, area_time.value);
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.L));
try std.testing.expectEqual(1, @TypeOf(area_time).dims.get(.T));
std.debug.print("MulBy: {f} * {f} = {f} OK\n", .{ d, t, area_time });
}
test "Scale" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const d = Meter{ .value = 7 };
const scaled = d.scale(3);
try std.testing.expectEqual(21, scaled.value);
try std.testing.expectEqual(1, @TypeOf(scaled).dims.get(.L));
std.debug.print("Scale int: {f} * 3 = {f} OK\n", .{ d, scaled });
const t = Second{ .value = 1.5 };
const scaled_f = t.scale(4.0);
try std.testing.expectApproxEqAbs(@as(f32, 6.0), scaled_f.value, 1e-4);
std.debug.print("Scale float: {f} * 4 = {f} OK\n", .{ t, scaled_f });
}
test "Chained: velocity and acceleration" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const dist = Meter{ .value = 100.0 };
const t1 = Second{ .value = 5.0 };
const velocity = dist.divBy(t1);
try std.testing.expectEqual(20, velocity.value);
try std.testing.expectEqual(1, @TypeOf(velocity).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(velocity).dims.get(.T));
const t2 = Second{ .value = 4.0 };
const accel = velocity.divBy(t2);
try std.testing.expectEqual(5, accel.value);
try std.testing.expectEqual(1, @TypeOf(accel).dims.get(.L));
try std.testing.expectEqual(-2, @TypeOf(accel).dims.get(.T));
std.debug.print("Velocity: {f}, Acceleration: {f} OK\n", .{ velocity, accel });
}
test "DivBy integer exact" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(f32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const dist = Meter{ .value = 120 };
const time = Second{ .value = 4 };
const vel = dist.divBy(time);
try std.testing.expectEqual(30, vel.value);
try std.testing.expectEqual(1, @TypeOf(vel).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(vel).dims.get(.T));
std.debug.print("DivBy int: {f} / {f} = {f} OK\n", .{ dist, time, vel });
}
test "Conversion chain: km -> m -> cm" {
const KiloMeter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const CentiMeter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .c }));
const km = KiloMeter{ .value = 15 };
const m = km.to(Meter);
const cm = m.to(CentiMeter);
try std.testing.expectEqual(15_000, m.value);
try std.testing.expectEqual(1_500_000, cm.value);
std.debug.print("Chain: {f} -> {f} -> {f} OK\n", .{ km, m, cm });
}
test "Conversion: hours -> minutes -> seconds" {
const Hour = Quantity(i128, Dimensions.init(.{ .T = 1 }), Scales.init(.{ .T = .hour }));
const Minute = Quantity(i128, Dimensions.init(.{ .T = 1 }), Scales.init(.{ .T = .min }));
const Second = Quantity(i128, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const h = Hour{ .value = 1.0 };
const min = h.to(Minute);
const sec = min.to(Second);
try std.testing.expectEqual(60, min.value);
try std.testing.expectEqual(3600, sec.value);
std.debug.print("Time chain: {f} -> {f} -> {f} OK\n", .{ h, min, sec });
}
test "Negative values" {
const Meter = Quantity(i128, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const a = Meter{ .value = 5 };
const b = Meter{ .value = 20 };
const diff = a.sub(b);
try std.testing.expectEqual(-15, diff.value);
std.debug.print("Negative sub: {f} - {f} = {f} OK\n", .{ a, b, diff });
}
test "Format Quantity" {
const MeterPerSecondSq = Quantity(
f32,
Dimensions.init(.{ .L = 1, .T = -2 }),
Scales.init(.{ .T = .n }),
);
const KgMeterPerSecond = Quantity(
f32,
Dimensions.init(.{ .M = 1, .L = 1, .T = -1 }),
Scales.init(.{ .M = .k }),
);
const accel = MeterPerSecondSq{ .value = 9.81 };
const momentum = KgMeterPerSecond{ .value = 42.0 };
std.debug.print("Acceleration: {f}\n", .{accel});
std.debug.print("Momentum: {f}\n", .{momentum});
}
test "Format Vector3" {
const MeterPerSecondSq = Quantity(
f32,
Dimensions.init(.{ .L = 1, .T = -2 }),
Scales.init(.{ .T = .n }),
);
const KgMeterPerSecond = Quantity(
f32,
Dimensions.init(.{ .M = 1, .L = 1, .T = -1 }),
Scales.init(.{ .M = .k }),
);
const accel = MeterPerSecondSq.Vec3.initDefault(9.81);
const momentum = KgMeterPerSecond.Vec3{ .x = 43, .y = 0, .z = 11 };
std.debug.print("Acceleration: {f}\n", .{accel});
std.debug.print("Momentum: {f}\n", .{momentum});
}
test "Vec3 Init and Basic Arithmetic" {
const Meter = Quantity(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Vec3M = Meter.Vec3;
// Test zero, one, initDefault
const v_zero = Vec3M.zero;
try std.testing.expectEqual(0, v_zero.x);
const v_one = Vec3M.one;
try std.testing.expectEqual(1, v_one.x);
const v_def = Vec3M.initDefault(5);
try std.testing.expectEqual(5, v_def.x);
try std.testing.expectEqual(5, v_def.y);
try std.testing.expectEqual(5, v_def.z);
// Test add and sub
const v1 = Vec3M{ .x = 10, .y = 20, .z = 30 };
const v2 = Vec3M{ .x = 2, .y = 4, .z = 6 };
const added = v1.add(v2);
try std.testing.expectEqual(12, added.x);
try std.testing.expectEqual(24, added.y);
try std.testing.expectEqual(36, added.z);
const subbed = v1.sub(v2);
try std.testing.expectEqual(8, subbed.x);
try std.testing.expectEqual(16, subbed.y);
try std.testing.expectEqual(24, subbed.z);
// Test negate
const neg = v1.negate();
try std.testing.expectEqual(-10, neg.x);
try std.testing.expectEqual(-20, neg.y);
try std.testing.expectEqual(-30, neg.z);
}
test "Vec3 Kinematics (Scalar Mul/Div)" {
const Meter = Quantity(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Second = Quantity(i32, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
const Vec3M = Meter.Vec3;
const pos = Vec3M{ .x = 100, .y = 200, .z = 300 };
const time = Second{ .value = 10 };
// Vector divided by scalar Quantity (Velocity = Position / Time)
const vel = pos.divByScalar(time);
try std.testing.expectEqual(10, vel.x);
try std.testing.expectEqual(20, vel.y);
try std.testing.expectEqual(30, vel.z);
try std.testing.expectEqual(1, @TypeOf(vel).dims.get(.L));
try std.testing.expectEqual(-1, @TypeOf(vel).dims.get(.T));
// Vector multiplied by scalar Quantity (Position = Velocity * Time)
const new_pos = vel.mulByScalar(time);
try std.testing.expectEqual(100, new_pos.x);
try std.testing.expectEqual(200, new_pos.y);
try std.testing.expectEqual(300, new_pos.z);
try std.testing.expectEqual(1, @TypeOf(new_pos).dims.get(.L));
try std.testing.expectEqual(0, @TypeOf(new_pos).dims.get(.T));
}
test "Vec3 Element-wise Math and Scaling" {
const Meter = Quantity(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const Vec3M = Meter.Vec3;
const v1 = Vec3M{ .x = 10, .y = 20, .z = 30 };
const v2 = Vec3M{ .x = 2, .y = 5, .z = 10 };
// Element-wise division
const div = v1.divBy(v2);
try std.testing.expectEqual(5, div.x);
try std.testing.expectEqual(4, div.y);
try std.testing.expectEqual(3, div.z);
try std.testing.expectEqual(0, @TypeOf(div).dims.get(.L)); // M / M = Dimensionless
// Scale by primitive
const scaled = v1.scale(2);
try std.testing.expectEqual(20, scaled.x);
try std.testing.expectEqual(40, scaled.y);
try std.testing.expectEqual(60, scaled.z);
}
test "Vec3 Conversions" {
const KiloMeter = Quantity(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const Meter = Quantity(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const v_km = KiloMeter.Vec3{ .x = 1, .y = 2, .z = 3 };
const v_m = v_km.to(Meter);
try std.testing.expectEqual(1000, v_m.x);
try std.testing.expectEqual(2000, v_m.y);
try std.testing.expectEqual(3000, v_m.z);
// Type checking the result
try std.testing.expectEqual(1, @TypeOf(v_m).dims.get(.L));
try std.testing.expectEqual(UnitScale.none, @TypeOf(v_m).scales.get(.L));
}
test "Vec3 Length" {
const MeterInt = Quantity(i32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const MeterFloat = Quantity(f32, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
// Integer length (using your custom isqrt)
// 3-4-5 triangle on XY plane
const v_int = MeterInt.Vec3{ .x = 3, .y = 4, .z = 0 };
try std.testing.expectEqual(25, v_int.lengthSqr());
try std.testing.expectEqual(5, v_int.length());
// Float length
const v_float = MeterFloat.Vec3{ .x = 3.0, .y = 4.0, .z = 0.0 };
try std.testing.expectApproxEqAbs(@as(f32, 25.0), v_float.lengthSqr(), 1e-4);
try std.testing.expectApproxEqAbs(@as(f32, 5.0), v_float.length(), 1e-4);
}
test "Comprehensive Benchmark: All Ops × All Types" {
const Io = std.Io;
const ITERS: usize = 100_000;
const SAMPLES: usize = 10; // Number of samples for stats
var gsink: f64 = 0;
const io = std.testing.io;
// Standard Zig 0.16 timestamp retrieval
const getTime = struct {
fn f(i: Io) Io.Timestamp {
return Io.Clock.awake.now(i);
}
}.f;
const fold = struct {
fn f(comptime TT: type, s: *f64, v: TT) void {
s.* += if (comptime @typeInfo(TT) == .float)
@as(f64, @floatCast(v))
else
@as(f64, @floatFromInt(v));
}
}.f;
const getVal = struct {
fn f(comptime TT: type, i: usize, comptime mask: u7) TT {
const v: u8 = @as(u8, @truncate(i & @as(usize, mask))) + 1;
return if (comptime @typeInfo(TT) == .float) @floatFromInt(v) else @intCast(v);
}
}.f;
const Stats = struct {
median: f64,
delta: f64,
ops_per_sec: f64,
};
const computeStats = struct {
fn f(samples: []f64, iters: usize) Stats {
std.mem.sort(f64, samples, {}, std.sort.asc(f64));
const mid = samples.len / 2;
const median_ns = if (samples.len % 2 == 0) (samples[mid - 1] + samples[mid]) / 2.0 else samples[mid];
const low = samples[0];
const high = samples[samples.len - 1];
const delta_ns = (high - low) / 2.0;
const ns_per_op = median_ns / @as(f64, @floatFromInt(iters));
return .{
.median = ns_per_op,
.delta = (delta_ns / @as(f64, @floatFromInt(iters))),
.ops_per_sec = 1_000_000_000.0 / ns_per_op,
};
}
}.f;
std.debug.print(
\\
\\ Quantity<T> benchmark — {d} iterations, {d} samples/cell
\\
\\┌───────────────────┬──────┬─────────────────────┬─────────────────────┐
\\│ Operation │ Type │ ns / op (± delta) │ Throughput (ops/s) │
\\├───────────────────┼──────┼─────────────────────┼─────────────────────┤
\\
, .{ ITERS, SAMPLES });
const Types = .{ i16, i32, i64, i128, i256, f32, f64, f128 };
const TNames = .{ "i16", "i32", "i64", "i128", "i256", "f32", "f64", "f128" };
const Ops = .{ "add", "sub", "mulBy", "divBy", "scale", "to" };
var results_matrix: [Ops.len][Types.len]f64 = undefined;
comptime var tidx: usize = 0;
inline for (Types, TNames) |T, tname| {
const M = Quantity(T, Dimensions.init(.{ .L = 1 }), Scales.init(.{}));
const KM = Quantity(T, Dimensions.init(.{ .L = 1 }), Scales.init(.{ .L = .k }));
const S = Quantity(T, Dimensions.init(.{ .T = 1 }), Scales.init(.{}));
inline for (Ops, 0..) |op_name, oidx| {
var samples: [SAMPLES]f64 = undefined;
for (0..SAMPLES) |s_idx| {
var sink: T = 0;
const t_start = getTime(io);
for (0..ITERS) |i| {
const r = if (comptime std.mem.eql(u8, op_name, "add"))
(M{ .value = getVal(T, i, 63) }).add(M{ .value = getVal(T, i +% 7, 63) })
else if (comptime std.mem.eql(u8, op_name, "sub"))
(M{ .value = getVal(T, i +% 10, 63) }).sub(M{ .value = getVal(T, i, 63) })
else if (comptime std.mem.eql(u8, op_name, "mulBy"))
(M{ .value = getVal(T, i, 63) }).mulBy(M{ .value = getVal(T, i +% 1, 63) })
else if (comptime std.mem.eql(u8, op_name, "divBy"))
(M{ .value = getVal(T, i +% 10, 63) }).divBy(S{ .value = getVal(T, i, 63) })
else if (comptime std.mem.eql(u8, op_name, "scale"))
(M{ .value = getVal(T, i, 63) }).scale(getVal(T, i +% 2, 63))
else
(KM{ .value = getVal(T, i, 15) }).to(M);
if (comptime @typeInfo(T) == .float) sink += r.value else sink ^= r.value;
}
const t_end = getTime(io);
samples[s_idx] = @as(f64, @floatFromInt(t_start.durationTo(t_end).toNanoseconds()));
fold(T, &gsink, sink);
}
const stats = computeStats(&samples, ITERS);
results_matrix[oidx][tidx] = stats.median;
std.debug.print("│ {s:<17} │ {s:<4} │ {d:>8.2} ns ±{d:<6.2} │ {d:>19.0} │\n", .{ op_name, tname, stats.median, stats.delta, stats.ops_per_sec });
}
if (comptime tidx < Types.len - 1) {
std.debug.print("├───────────────────┼──────┼─────────────────────┼─────────────────────┤\n", .{});
}
tidx += 1;
}
// Median Summary Table
std.debug.print("└───────────────────┴──────┴─────────────────────┴─────────────────────┘\n\n", .{});
std.debug.print("Median Summary (ns/op):\n", .{});
std.debug.print("┌──────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐\n", .{});
std.debug.print("│ Operation │ i16 │ i32 │ i64 │ i128 │ i256 │ f32 │ f64 │ f128 │\n", .{});
std.debug.print("├──────────────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┼───────┤\n", .{});
inline for (Ops, 0..) |op_name, oidx| {
std.debug.print("│ {s:<11} │", .{op_name});
var i: usize = 0;
while (i < Types.len) : (i += 1) {
std.debug.print("{d:>6.1} │", .{results_matrix[oidx][i]});
}
std.debug.print("\n", .{});
}
std.debug.print("└──────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┘\n", .{});
std.debug.print("\nAnti-optimisation sink: {d:.4}\n", .{gsink});
try std.testing.expect(gsink != 0);
} }