Something went wrong. Try again.
Positions on the Earth for Zig: point-in-polygon, bounding boxes, and great-circle distance and bearing.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the functions must do with positions nobody chose.//!//! Every target reads its positions out of the input as pairs of `u32`s//! scaled onto the valid ranges, so that every input is a set of real places//! rather than mostly NaNs and infinities -- which the functions would//! faithfully turn into more NaNs, and which would test nothing.//!//! The properties://!//! * `sphere`: a distance is finite, no more than half the circumference,//! the same both ways, and no longer than a detour through a third point;//! a bearing is in [0, 360); and setting off on the bearing for the//! distance arrives where it should.//! * `ellipsoid`: the same, on the ellipsoid by way of `Geodesic`, and a//! distance there within the 0.56 per cent the mean sphere can be out by.//! * `ring`: whether a ring contains a point does not depend on which vertex//! it starts at, nor on whether it is written closed.//! * `bbox`: the box around some positions contains every one of them, and//! the merge of two boxes contains everything either did.//!//! Each target is an ordinary test as well as a fuzz target: without `--fuzz`//! it runs the seeds beside it, and `zig build fuzz --fuzz` fuzzes them with//! coverage feedback. `tools/fuzz.zig` is a loop that runs these without//! Zig's fuzzer, bounded by a count and replayable from a seed.
const builtin = @import("builtin");const std = @import("std");const Allocator = std.mem.Allocator;const testing = std.testing;const Smith = std.testing.Smith;
const geo = @import("geo");const Position = geo.Position;
/// The allocator the targets run against. None of them allocates, but/// `tools/fuzz.zig` sets it and checks it for leaks all the same.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;
/// Eight octets as a position: two little-endian `u32`s, scaled onto/// [-180, 180) and [-90, 90].fn position(bytes: *const [8]u8) Position { const x = std.mem.readInt(u32, bytes[0..4], .little); const y = std.mem.readInt(u32, bytes[4..8], .little); const scale = 1.0 / 4294967296.0; return .{ .longitude = -180 + 360 * @as(f64, @floatFromInt(x)) * scale, .latitude = -90 + 180 * @as(f64, @floatFromInt(y)) * (1.0 / 4294967295.0), };}
/// A position as the eight octets `position` reads, for writing seeds.fn encode(comptime p: Position) [8]u8 { var out: [8]u8 = undefined; const x: u32 = @intFromFloat((p.longitude + 180) / 360 * 4294967296.0); const y: u32 = @intFromFloat((p.latitude + 90) / 180 * 4294967295.0); std.mem.writeInt(u32, out[0..4], x, .little); std.mem.writeInt(u32, out[4..8], y, .little); return out;}
fn positions(input: []const u8, out: []Position) []Position { const n = @min(input.len / 8, out.len); for (0..n) |i| out[i] = position(input[i * 8 ..][0..8]); return out[0..n];}
// -- the sphere ----------------------------------------------------------------
const sphere_seeds = [_][]const u8{ &(encode(.{ .longitude = -93.625, .latitude = 41.5868 }) ++ encode(.{ .longitude = -87.6298, .latitude = 41.8781 }) ++ encode(.{ .longitude = -90.2, .latitude = 38.6 })), &(encode(.{ .longitude = 0, .latitude = 0 }) ++ encode(.{ .longitude = 179.99, .latitude = 0 }) ++ encode(.{ .longitude = 0, .latitude = 89.9 })), &(encode(.{ .longitude = 179.5, .latitude = 10 }) ++ encode(.{ .longitude = -179.5, .latitude = -10 }) ++ encode(.{ .longitude = 0, .latitude = 0 })),};
fn sphereProperty(input: []const u8) !void { var buffer: [3]Position = undefined; const p = positions(input, &buffer); if (p.len < 3) return; // The default sphere, and the smallest and largest of the others: the // polar radius of Zach 1812 and the equatorial one of International 1924. const spheres = [_]geo.sphere.Sphere{ geo.sphere.mean, geo.Ellipsoid.epsg.zach_1812.sphere(.polar), geo.Ellipsoid.epsg.international_1924.sphere(.equatorial), }; for (spheres) |sphere| try sphereProperties(sphere, p[0], p[1], p[2]);}
fn sphereProperties(sphere: geo.sphere.Sphere, a: Position, b: Position, c: Position) !void { const half_way_round = sphere.radius * std.math.pi; const ab = sphere.distance(a, b); if (!std.math.isFinite(ab) or ab < 0 or ab > half_way_round * (1 + 1e-12)) return error.DistanceOutOfRange; if (ab != sphere.distance(b, a)) return error.DistanceNotSymmetric;
const ac = sphere.distance(a, c); const bc = sphere.distance(b, c); if (ac > ab + bc + 1e-6) return error.TriangleInequality;
const bearing = geo.sphere.initialBearing(a, b); if (!(bearing >= 0 and bearing < 360)) return error.BearingOutOfRange;
// Setting off on the bearing for the distance arrives at `b` -- except // where there is no one bearing to set off on: from a pole, or between // points that coincide or are antipodal. const near_pole = @abs(a.latitude) > 89.999; if (!near_pole and ab > 1 and ab < half_way_round - 1000) { const arrived = sphere.destination(a, bearing, ab); if (!arrived.isValid()) return error.DestinationInvalid; if (sphere.distance(arrived, b) > 1e-3 * @max(1, ab / 1e6)) return error.DestinationMissed; }}
test "fuzz sphere" { for (sphere_seeds) |seed| try sphereProperty(seed); try testing.fuzz({}, fuzzSphere, .{});}
fn fuzzSphere(_: void, smith: *Smith) !void { var buffer: [24]u8 = undefined; const len = smith.slice(&buffer); try sphereProperty(buffer[0..len]);}
// -- rings ---------------------------------------------------------------------
const max_ring = 32;
const ring_seeds = [_][]const u8{ // A square and a point inside it; the point is the last position. &(encode(.{ .longitude = 0, .latitude = 0 }) ++ encode(.{ .longitude = 10, .latitude = 0 }) ++ encode(.{ .longitude = 10, .latitude = 10 }) ++ encode(.{ .longitude = 0, .latitude = 10 }) ++ encode(.{ .longitude = 5, .latitude = 5 })), // A U and a point in its notch. &(encode(.{ .longitude = 0, .latitude = 0 }) ++ encode(.{ .longitude = 30, .latitude = 0 }) ++ encode(.{ .longitude = 30, .latitude = 30 }) ++ encode(.{ .longitude = 20, .latitude = 30 }) ++ encode(.{ .longitude = 20, .latitude = 10 }) ++ encode(.{ .longitude = 10, .latitude = 10 }) ++ encode(.{ .longitude = 10, .latitude = 30 }) ++ encode(.{ .longitude = 0, .latitude = 30 }) ++ encode(.{ .longitude = 15, .latitude = 20 })),};
fn ringProperty(input: []const u8) !void { var buffer: [max_ring + 1]Position = undefined; const every = positions(input, &buffer); if (every.len < 4) return; const point = every[every.len - 1]; const ring = every[0 .. every.len - 1];
const inside = geo.ring.contains(ring, point);
// The same ring from every starting vertex. var rotated: [max_ring + 1]Position = undefined; for (1..ring.len) |start| { for (0..ring.len) |i| rotated[i] = ring[(start + i) % ring.len]; if (geo.ring.contains(rotated[0..ring.len], point) != inside) return error.DependsOnStart; }
// And written closed. @memcpy(rotated[0..ring.len], ring); rotated[ring.len] = ring[0]; if (geo.ring.contains(rotated[0 .. ring.len + 1], point) != inside) return error.DependsOnClosure; if (!geo.ring.isClosed(rotated[0 .. ring.len + 1])) return error.NotClosed;
std.mem.doNotOptimizeAway(geo.ring.isCounterClockwise(ring));}
test "fuzz rings" { for (ring_seeds) |seed| try ringProperty(seed); try testing.fuzz({}, fuzzRing, .{});}
fn fuzzRing(_: void, smith: *Smith) !void { var buffer: [(max_ring + 1) * 8]u8 = undefined; const len = smith.slice(&buffer); try ringProperty(buffer[0..len]);}
// -- bounding boxes ------------------------------------------------------------
fn bboxProperty(input: []const u8) !void { var buffer: [16]Position = undefined; const every = positions(input, &buffer); if (every.len < 2) return; const half = every.len / 2; const first = every[0..half]; const second = every[half..];
const a = geo.BoundingBox.of(first) orelse return; const b = geo.BoundingBox.of(second) orelse return; for (first) |p| if (!a.contains(p)) return error.BoxMissesItsOwnPoint; for (second) |p| if (!b.contains(p)) return error.BoxMissesItsOwnPoint;
if (a.intersects(b) != b.intersects(a)) return error.IntersectsNotSymmetric;
const merged = a.merge(b); for (every) |p| if (!merged.contains(p)) return error.MergeLostAPoint; if (!merged.intersects(a) or !merged.intersects(b)) return error.MergeLostABox;}
const bbox_seeds = [_][]const u8{ &(encode(.{ .longitude = 175, .latitude = 0 }) ++ encode(.{ .longitude = 179, .latitude = 1 }) ++ encode(.{ .longitude = -179, .latitude = 0 }) ++ encode(.{ .longitude = -175, .latitude = 1 })), &(encode(.{ .longitude = -93.6, .latitude = 41.5 }) ++ encode(.{ .longitude = -87.6, .latitude = 41.9 }) ++ encode(.{ .longitude = 2.35, .latitude = 48.85 }) ++ encode(.{ .longitude = 151.2, .latitude = -33.9 })),};
test "fuzz bounding boxes" { for (bbox_seeds) |seed| try bboxProperty(seed); try testing.fuzz({}, fuzzBbox, .{});}
fn fuzzBbox(_: void, smith: *Smith) !void { var buffer: [128]u8 = undefined; const len = smith.slice(&buffer); try bboxProperty(buffer[0..len]);}
// -- the ellipsoid ---------------------------------------------------------------
const ellipsoid_seeds = sphere_seeds ++ [_][]const u8{ // Nearly antipodal, where Vincenty's method fails to converge. &(encode(.{ .longitude = 0, .latitude = 56.320923501171 }) ++ encode(.{ .longitude = 179.664747671772880215, .latitude = -56.320923501171 }) ++ encode(.{ .longitude = 90, .latitude = 0 })), // Antipodal on the equator, where every meridian is a shortest path. &(encode(.{ .longitude = 0, .latitude = 0 }) ++ encode(.{ .longitude = -180, .latitude = 0 }) ++ encode(.{ .longitude = 0, .latitude = 90 })),};
fn ellipsoidProperty(input: []const u8) !void { var buffer: [3]Position = undefined; const p = positions(input, &buffer); if (p.len < 3) return; for ([_]geo.Ellipsoid{ geo.Ellipsoid.wgs84, geo.Ellipsoid.epsg.international_1924 }) |ellipsoid| { try ellipsoidProperties(ellipsoid, p[0], p[1], p[2]); }}
fn ellipsoidProperties(ellipsoid: geo.Ellipsoid, a: Position, b: Position, c: Position) !void { // No geodesic is longer than half the equator. const half_way_round = ellipsoid.semi_major * std.math.pi; const ab = ellipsoid.distance(a, b); if (!std.math.isFinite(ab) or ab < 0 or ab > half_way_round * (1 + 1e-12)) return error.DistanceOutOfRange; if (@abs(ab - ellipsoid.distance(b, a)) > 1e-8) return error.DistanceNotSymmetric;
const ac = ellipsoid.distance(a, c); const bc = ellipsoid.distance(b, c); if (ac > ab + bc + 1e-6) return error.TriangleInequality;
// The sphere of the mean radius is out by at most the difference between // it and the radius of curvature in the meridian at the equator, // a(1 - e²): 0.561 per cent on WGS 84. const on_sphere = ellipsoid.sphere(.mean).distance(a, b); if (@abs(on_sphere - ab) > 0.0057 * ab + 1e-6) return error.SphereTooFarOut;
const bearing = ellipsoid.initialBearing(a, b); if (!(bearing >= 0 and bearing < 360)) return error.BearingOutOfRange;
// As on the sphere: no one bearing from a pole, or between points that // coincide or are nearly antipodal, where the shortest path is not // unique and a small change in the bearing is a large one in arrival. const near_pole = @abs(a.latitude) > 89.999; if (!near_pole and ab > 1 and ab < half_way_round - 200_000) { const arrived = ellipsoid.destination(a, bearing, ab); if (!arrived.isValid()) return error.DestinationInvalid; if (ellipsoid.distance(arrived, b) > 1e-6) return error.DestinationMissed; }}
test "fuzz ellipsoid" { for (ellipsoid_seeds) |seed| try ellipsoidProperty(seed); try testing.fuzz({}, fuzzEllipsoid, .{});}
fn fuzzEllipsoid(_: void, smith: *Smith) !void { var buffer: [24]u8 = undefined; const len = smith.slice(&buffer); try ellipsoidProperty(buffer[0..len]);}
// -- the table tools/fuzz.zig drives -------------------------------------------
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run, which are /// what stands in for the coverage feedback a real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. `Smith.slice` yields an /// *empty* slice for a length larger than the buffer rather than a /// truncated one, so a generator that does not know this number hands /// the target nothing at all most of the time. content_max: usize, /// How many `Smith.slice` calls this target makes. slices: usize = 1,};
fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
pub const all = [_]Target{ .{ .name = "sphere", .run = Driven(fuzzSphere).run, .corpus = &sphere_seeds, .content_max = 24 }, .{ .name = "ellipsoid", .run = Driven(fuzzEllipsoid).run, .corpus = &ellipsoid_seeds, .content_max = 24 }, .{ .name = "ring", .run = Driven(fuzzRing).run, .corpus = &ring_seeds, .content_max = (max_ring + 1) * 8 }, .{ .name = "bbox", .run = Driven(fuzzBbox).run, .corpus = &bbox_seeds, .content_max = 128 },};