This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
location.zig
82 lines (74 loc) · 2.38 KB
/
location.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const Location = @This();
const std = @import("std");
filename: ?[]const u8,
line_number: usize,
column_number: usize,
pub fn new(filename: ?[]const u8, line_number: usize, column_number: usize) Location {
return .{
.filename = filename,
.line_number = line_number,
.column_number = column_number,
};
}
pub fn dirname(location: Location) ?[]const u8 {
if (location.filename) |filename| {
if (std.fs.path.dirname(filename)) |result| {
return result;
}
return "/"; // TODO: this is how Crystal's File.dirname works, but is it necessary?
}
return null;
}
pub fn isBetween(location: Location, min: ?Location, max: ?Location) bool {
if (min) |a| {
if (max) |b| {
return a.compare(.lte, location) and location.compare(.lte, b);
}
}
return false;
}
pub fn format(location: Location, comptime fmt: []const u8, opt: std.fmt.FormatOptions, writer: anytype) !void {
_ = opt;
_ = fmt;
if (location.filename) |filename| {
try writer.writeAll(filename);
}
try writer.print(":{}:{}", .{ location.line_number, location.column_number });
}
pub fn order(a: Location, b: Location) ?std.math.Order {
if (a.filename) |file_a| {
if (b.filename) |file_b| {
if (std.mem.eql(u8, file_a, file_b)) {
return switch (std.math.order(a.line_number, b.line_number)) {
.eq => std.math.order(a.column_number, b.column_number),
.lt, .gt => |result| result,
};
}
}
}
return null;
}
pub fn compare(a: Location, op: std.math.CompareOperator, b: Location) bool {
if (a.order(b)) |ord| {
return ord.compare(op);
}
return switch (op) {
.lt, .lte, .eq, .gte, .gt => false,
.neq => true,
};
}
// zig fmt: off
pub fn main() void {
const p = @import("std").debug.print;
p("{?s}\n", .{std.fs.path.dirname("/")});
p("{?s}\n", .{Location.new("/", 0, 0).dirname()});
p("{}\n", .{Location.new("/", 0, 0)});
const loc1 = Location.new("foo", 0, 0);
const loc2 = Location.new("foo", 0, 1);
const loc3 = Location.new("foo", 0, 2);
p("{?}\n", .{loc1.order(loc2)});
p("{}\n", .{loc1.compare(.lt, loc2)});
p("{}\n", .{loc1.compare(.lte, loc2)});
p("{}\n", .{loc1.compare(.gt, loc2)});
p("{}\n", .{loc2.isBetween(loc2, loc3)});
}