-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsonschema.zig
348 lines (313 loc) · 11.7 KB
/
jsonschema.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/// Zig API for the Zig JSON Schema library
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Type = enum {
Object,
Array,
String,
Number,
Integer,
Bool,
Null,
};
const Types = struct {
// This is a enum set as a number can be an int or float
// and a int can be either a int or a float if the float can be represented as a int without rounding
types: std.EnumSet(Type) = std.EnumSet(Type){},
const Self = @This();
fn str_to_schema_enum(str: []const u8) Schema.CompileError!std.EnumSet(Type) {
var set = std.EnumSet(Type){};
if (std.mem.eql(u8, str, "integer")) {
set.insert(.Integer);
} else if (std.mem.eql(u8, str, "number")) {
set.insert(.Number);
} else if (std.mem.eql(u8, str, "string")) {
set.insert(.String);
} else if (std.mem.eql(u8, str, "object")) {
set.insert(.Object);
} else if (std.mem.eql(u8, str, "array")) {
set.insert(.Array);
} else if (std.mem.eql(u8, str, "boolean")) {
set.insert(.Bool);
} else if (std.mem.eql(u8, str, "null")) {
set.insert(.Null);
} else {
return error.InvalidType;
}
return set;
}
pub fn compile(type_schema: std.json.Value) Schema.CompileError!Self {
return switch (type_schema) {
.String => |val| .{ .types = try Types.str_to_schema_enum(val) },
.Array => |array| brk: {
var comp_types_schema = std.EnumSet(Type){};
for (array.items) |string| {
comp_types_schema.setUnion(try Types.str_to_schema_enum(string.String));
}
break :brk .{ .types = comp_types_schema };
},
else => error.InvalidType,
};
}
pub fn validate(self: Self, data: std.json.Value) Schema.ValidateError!bool {
return switch (data) {
.Object => self.types.contains(.Object),
.Array => self.types.contains(.Array),
.String => self.types.contains(.String),
.Integer => self.types.contains(.Integer) or self.types.contains(.Number),
.Float => |val| self.types.contains(.Number) or (self.types.contains(.Integer) and (@floor(val) == val and @ceil(val) == val)),
.NumberString => error.TODOTopLevel,
.Bool => self.types.contains(.Bool),
.Null => self.types.contains(.Null),
};
}
};
const MinMaxItems = struct {
min: i64 = 0,
max: ?i64 = null,
const Self = @This();
pub fn compile(min_items_schema: ?std.json.Value, max_items_schema: ?std.json.Value) Schema.CompileError!Self {
var range = MinMaxItems{};
if (min_items_schema) |min_items| {
switch (min_items) {
.Integer => |ival| range.min = ival,
.Float => |fval| {
if (@floor(fval) == fval and @ceil(fval) == fval) {
range.min = @floatToInt(i64, fval);
} else {
return error.InvalidFloatToInt;
}
},
.NumberString => return error.TODONumberString,
else => return error.InvalidMinMaxItemsType,
}
}
if (max_items_schema) |max_items| {
switch (max_items) {
.Integer => |ival| range.max = ival,
.Float => |fval| {
if (@floor(fval) == fval and @ceil(fval) == fval) {
range.max = @floatToInt(i64, fval);
} else {
return error.InvalidFloatToInt;
}
},
.NumberString => return error.TODONumberString,
else => return error.InvalidMinMaxItemsType,
}
}
return range;
}
pub fn validate(self: Self, data: std.json.Value) Schema.ValidateError!bool {
switch (data) {
.Array => |array| {
var is_valid = array.items.len >= self.min;
if (self.max) |max| {
is_valid = is_valid and array.items.len <= max;
}
return is_valid;
},
else => return true,
}
}
};
const MinimumMaximum = struct {
min: union(enum) { Int: i64, Float: f64 } = .{ .Int = 0 },
max: ?union(enum) { Int: i64, Float: f64 } = null,
const Self = @This();
fn toInt(self: Self) Self {
var range = MinimumMaximum{};
range.min = .{ .Int = switch (self.min) {
.Int => |val| val,
.Float => |val| @floatToInt(i64, val),
} };
if (self.max) |max| {
range.max = .{ .Int = switch (max) {
.Int => |val| val,
.Float => |val| @floatToInt(i64, val),
} };
}
return range;
}
fn toFloat(self: Self) Self {
var range = MinimumMaximum{};
range.min = .{ .Float = switch (self.min) {
.Int => |val| @intToFloat(f64, val),
.Float => |val| val,
} };
if (self.max) |max| {
range.max = .{ .Float = switch (max) {
.Int => |val| @intToFloat(f64, val),
.Float => |val| val,
} };
}
return range;
}
pub fn compile(minimum_schema: ?std.json.Value, maximum_schema: ?std.json.Value) Schema.CompileError!Self {
var range = MinimumMaximum{};
if (minimum_schema) |minimum| {
switch (minimum) {
.Integer => |ival| range.min = .{ .Int = ival },
.Float => |fval| range.min = .{ .Float = fval },
.NumberString => return error.TODONumberString,
else => return error.InvalidMinimumMaximumType,
}
}
if (maximum_schema) |maximum| {
switch (maximum) {
.Integer => |ival| range.max = .{ .Int = ival },
.Float => |fval| range.max = .{ .Float = fval },
.NumberString => return error.TODONumberString,
else => return error.InvalidMinimumMaximumType,
}
}
return range;
}
pub fn validate(self: Self, data: std.json.Value) Schema.ValidateError!bool {
switch (data) {
.Integer => |val| {
const int_val = self.toInt();
var is_valid = val >= int_val.min.Int;
if (int_val.max) |max| {
is_valid = is_valid and val <= max.Int;
}
return is_valid;
},
.Float => |val| {
const float_val = self.toFloat();
var is_valid = val >= float_val.min.Float;
if (float_val.max) |max| {
is_valid = is_valid and val <= max.Float;
}
return is_valid;
},
else => return true,
}
}
};
/// The root compiled schema object
pub const Schema = union(enum) {
Schemas: []Schema,
Bool: bool,
Types: Types,
MinMaxItems: MinMaxItems,
MinimumMaximum: MinimumMaximum,
const Self = @This();
/// Error relating to the compilation of the schema
pub const CompileError = error{
/// TODO top level compiler
TODOTopLevel,
TODONumberString,
InvalidType,
InvalidMinMaxItemsType,
InvalidFloatToInt,
InvalidMinimumMaximumType,
NonExhaustiveSchemaValidators,
} || Allocator.Error;
/// Error relating to the validation of JSON data against the schema
pub const ValidateError = error{
/// TODO top level compiler
TODOTopLevel,
};
///
/// Compile the provided JSON schema into a more refined form for faster validation.
///
/// Arguments:
/// IN allocator: Allocator - An allocator.
/// IN schema: std.json.Value - The JSON data representing a schema to be compiled.
///
/// Return: Schema
/// A schema object that can be used to validate against data. See Schema.validate().
///
/// Error: CompileError
/// TODOTopLevel - TODO top level validator
///
pub fn compile(allocator: Allocator, schema: std.json.Value) CompileError!Self {
return switch (schema) {
.Bool => |b| .{ .Bool = b },
.Object => |object| brk: {
var schema_used: usize = 0;
var schema_list = std.ArrayList(Schema).init(allocator);
errdefer schema_list.deinit();
if (object.get("type")) |type_schema| {
const sub_schema = Schema{ .Types = try Types.compile(type_schema) };
try schema_list.append(sub_schema);
schema_used += 1;
}
const min_items_schema = object.get("minItems");
const max_items_schema = object.get("maxItems");
if (min_items_schema != null or max_items_schema != null) {
const sub_schema = Schema{ .MinMaxItems = try MinMaxItems.compile(min_items_schema, max_items_schema) };
try schema_list.append(sub_schema);
schema_used += 1;
}
const minimum_schema = object.get("minimum");
const maximum_schema = object.get("maximum");
if (minimum_schema != null or maximum_schema != null) {
const sub_schema = Schema{ .MinimumMaximum = try MinimumMaximum.compile(minimum_schema, maximum_schema) };
try schema_list.append(sub_schema);
schema_used += 1;
}
if (object.count() != schema_used) {
break :brk error.NonExhaustiveSchemaValidators;
}
break :brk .{ .Schemas = schema_list.toOwnedSlice() };
},
else => CompileError.TODOTopLevel,
};
}
pub fn deinit(self: Self, allocator: Allocator) void {
switch (self) {
.Schemas => |schemas| allocator.free(schemas),
else => {},
}
}
///
/// Validate JSON data against a compiled schema.
///
/// Arguments:
/// IN self: Self - The compiled schema.
/// IN data: std.json.Value - The JSON data to validate.
///
/// Return: bool
/// Whether the JSON data matches the schema.
///
/// Error: ValidateError
/// TODOTopLevel - TODO top level compiler
///
pub fn validate(self: Self, data: std.json.Value) ValidateError!bool {
return switch (self) {
.Bool => |b| b,
.Schemas => |schemas| {
for (schemas) |schema| {
if (!try schema.validate(data)) {
return false;
}
}
return true;
},
inline else => |sch| sch.validate(data),
};
}
};
///
/// Compile then validate the data against the provided schema.
/// This will first compile the provided JSON schema then validate against the data.
///
/// Arguments:
/// IN allocator: Allocator - An allocator.
/// IN schema: std.json.Value - The JSON data representing a schema to be compiled.
/// IN data: std.json.Value - The JSON data to test against the schema.
///
/// Return: bool
/// True if the data matched the schema.
///
/// Error: CompileError || ValidateError
/// TODOTopLevel - TODO top level validator
///
pub fn validate(allocator: Allocator, schema: std.json.Value, data: std.json.Value) (Schema.CompileError || Schema.ValidateError)!bool {
const js_cmp = try Schema.compile(allocator, schema);
defer js_cmp.deinit(allocator);
return js_cmp.validate(data);
}