stdassertAllocatorArenaAllocatorArrayListScannerTokenAllocWhendefault_max_value_lenisNumberFormattedLikeAnIntegerValueArrayParseOptionsParsedparseFromSliceparseFromSliceLeakyparseFromTokenSourceparseFromTokenSourceLeakyparseFromValueparseFromValueLeakyParseErrorParseFromValueErrorinnerParseinternalParseArrayinnerParseFromValueinnerParseArrayFromArrayValuesliceToIntsliceToEnumfillDefaultStructValuesfreeAllocated
std.json.static.Allocator
别名
别名目标 std.mem.Allocator
std.json.static.AllocWhen
别名
std.json.static.ArenaAllocator
别名
std.json.static.Array
别名
std.json.static.ArrayList
别名
std.json.static.assert
别名
别名目标 std.debug.assert
std.json.static.default_max_value_len
别名
std.json.static.fillDefaultStructValues
函数
fn fillDefaultStructValues(comptime T: type, r: *T, fields_seen: *[@typeInfo(T).@"struct".field_names.len]bool) !void
参数
T: type
r: *T
fields_seen: *[@typeInfo(T).@"struct".field_names.len]bool
std.json.static.freeAllocated
函数
fn freeAllocated(allocator: Allocator, token: Token) void
参数
std.json.static.innerParse
函数
此内部函数在 parseFromTokenSourceLeaky 等函数的实现过程中递归调用。
公开它主要是为了让自定义 jsonParse() 方法能够回调 parseFrom* 系统。例如,实现 T 类型的自定义容器时,可对每个容器元素调用 innerParse(T, ...)。
注意,调用此函数时,null 字段不允许出现在 options 中。
在 options 中,即 jsonParse 方法所收到的选项,不包含 null 字段。
pub fn innerParse( comptime T: type, allocator: Allocator, source: anytype, options: ParseOptions, ) ParseError(@TypeOf(source.*))!T
参数
std.json.static.innerParseArrayFromArrayValue
函数
fn innerParseArrayFromArrayValue( comptime T: type, comptime Child: type, comptime len: comptime_int, allocator: Allocator, array: Array, options: ParseOptions, ) !T
参数
std.json.static.innerParseFromValue
函数
这是 parseFromValueLeaky 实现中
递归调用的内部函数。
公开它主要是为了让自定义 jsonParseFromValue() 方法回调 parseFromValue* 系统,
例如实现自定义 T 类型容器时,
可对容器中的每个元素调用 innerParseFromValue(T, ...)。
pub fn innerParseFromValue( comptime T: type, allocator: Allocator, source: Value, options: ParseOptions, ) ParseFromValueError!T
参数
错误
- DuplicateField
- InvalidCharacter ParseIntError
输入为空或包含无效字符。
- InvalidEnumTag
- InvalidNumber
- LengthMismatch
- MissingField
- OutOfMemory Error
- Overflow ParseIntError
结果无法由指定类型容纳。
- UnexpectedToken
- UnknownField
std.json.static.internalParseArray
函数
fn internalParseArray( comptime T: type, comptime Child: type, allocator: Allocator, source: anytype, options: ParseOptions, ) !T
参数
std.json.static.isNumberFormattedLikeAnInteger
别名
std.json.static.Parsed
类型函数
pub fn Parsed(comptime T: type) type
参数
T: type
字段
arena: *ArenaAllocator
value: T
std.json.static.Parsed.deinit
函数
pub fn deinit(self: @This()) void
参数
self: @This()
std.json.static.ParseError
类型函数
从 *Source 解析时将返回的错误集合。
注意,其中可能包含 error.BufferUnderrun,但实际上绝不会返回该错误。
pub fn ParseError(comptime Source: type) type
参数
Source: type
std.json.static.parseFromSlice
函数
从 s 解析 JSON 文档,并将结果包装为 std.json.Parsed 返回。
必须调用返回对象的 deinit(),清理已分配资源。
如果使用 std.heap.ArenaAllocator 或类似分配器,请考虑改用 parseFromSliceLeaky。
注意,此函数实际不可能返回 error.BufferUnderrun。
pub fn parseFromSlice( comptime T: type, allocator: Allocator, s: []const u8, options: ParseOptions, ) ParseError(Scanner)!Parsed(T)
参数
std.json.static.parseFromSliceLeaky
函数
从 s 解析 JSON 文档并返回结果。
此操作中的分配不会被仔细跟踪,可能无法单独清理。
建议使用 std.heap.ArenaAllocator 或类似分配器。
pub fn parseFromSliceLeaky( comptime T: type, allocator: Allocator, s: []const u8, options: ParseOptions, ) ParseError(Scanner)!T
参数
std.json.static.parseFromTokenSource
函数
scanner_or_reader 必须为具有完整输入的 *std.json.Scanner,或为 *std.json.Reader。
注意,此函数实际上不可能返回 error.BufferUnderrun。
pub fn parseFromTokenSource( comptime T: type, allocator: Allocator, scanner_or_reader: anytype, options: ParseOptions, ) ParseError(@TypeOf(scanner_or_reader.*))!Parsed(T)
参数
std.json.static.parseFromTokenSourceLeaky
函数
scanner_or_reader 必须是包含完整输入的 *std.json.Scanner,或 *std.json.Reader。
此操作中的分配不会被仔细跟踪,可能无法单独清理。
建议使用 std.heap.ArenaAllocator 或类似分配器。
pub fn parseFromTokenSourceLeaky( comptime T: type, allocator: Allocator, scanner_or_reader: anytype, options: ParseOptions, ) ParseError(@TypeOf(scanner_or_reader.*))!T
参数
std.json.static.parseFromValue
函数
类似 parseFromSlice,但输入是已经解析的 std.json.Value 对象。
仅使用 options 中的 options.ignore_unknown_fields。
pub fn parseFromValue( comptime T: type, allocator: Allocator, source: Value, options: ParseOptions, ) ParseFromValueError!Parsed(T)
参数
错误
- DuplicateField
- InvalidCharacter ParseIntError
输入为空或包含无效字符。
- InvalidEnumTag
- InvalidNumber
- LengthMismatch
- MissingField
- OutOfMemory Error
- Overflow ParseIntError
结果无法由指定类型容纳。
- UnexpectedToken
- UnknownField
std.json.static.ParseFromValueError
错误集合
错误
- DuplicateField
- InvalidCharacter ParseIntError
输入为空或包含无效字符。
- InvalidEnumTag
- InvalidNumber
- LengthMismatch
- MissingField
- OutOfMemory Error
- Overflow ParseIntError
结果无法由指定类型容纳。
- UnexpectedToken
- UnknownField
std.json.static.parseFromValueLeaky
函数
pub fn parseFromValueLeaky( comptime T: type, allocator: Allocator, source: Value, options: ParseOptions, ) ParseFromValueError!T
参数
错误
- DuplicateField
- InvalidCharacter ParseIntError
输入为空或包含无效字符。
- InvalidEnumTag
- InvalidNumber
- LengthMismatch
- MissingField
- OutOfMemory Error
- Overflow ParseIntError
结果无法由指定类型容纳。
- UnexpectedToken
- UnknownField
std.json.static.ParseOptions
容器
控制如何处理 JSON 文档与传入 Zig 结构体类型之间的各种不一致。 对于重复字段或未知字段,可在此结构体中设置选项。 对于缺失字段,应为 Zig 结构体字段提供默认值。
字段
duplicate_field_behavior: enum {
use_first,
@"error",
use_last,
} = .@"error"遇到重复字段时的行为。
默认返回 error.DuplicateField。
ignore_unknown_fields: bool = false若为 false,则发现未知字段时返回 error.UnknownField。
max_value_len: ?usize = null传给 std.json.Scanner.nextAllocMax 或 std.json.Reader.nextAllocMax。
对 parseFromSlice,或 parseFromTokenSource(以 *std.json.Scanner 为输入),默认值为输入切片长度,因此绝不会返回 error.ValueTooLong。
对 parseFromTokenSource(以 *std.json.Reader 为输入),默认值为 std.json.default_max_value_len。
不需要分配或不复制的值会忽略此选项,参见 allocate。
parseFromValue 和 parseFromValueLeaky 忽略此选项。
allocate: ?AllocWhen = null决定是否始终复制字符串,
或在可能时优先引用给定缓冲区。
parseFromSlice 或输入为 *std.json.Scanner 的 parseFromTokenSource,
默认为 .alloc_if_needed。
输入为 *std.json.Reader 时,默认为 .alloc_always。
parseFromValue 和 parseFromValueLeaky 忽略此设置。
parse_numbers: bool = true解析为 std.json.Value 时,将此选项设为 false,可始终将
JSON 数字作为未解析的 std.json.Value.number_string 生成。
否则,根据 JSON 数字的格式和值,将其解析为 std.json.Value.integer、
std.json.Value.float,或保留为未解析的 std.json.Value.number_string。
此选项为 true 时,以浮点格式编码的 JSON 数字,参见 std.json.isNumberFormattedLikeAnInteger,
解析为 std.json.Value.float 时可能损失精度。
std.json.static.Scanner
别名
别名目标 std.json.Scanner
std.json.static.sliceToEnum
函数
fn sliceToEnum(comptime T: type, slice: []const u8) !T
参数
T: type
slice: []const u8
std.json.static.sliceToInt
函数
fn sliceToInt(comptime T: type, slice: []const u8) !T
参数
T: type
slice: []const u8
std.json.static.std
别名
别名目标 std
std.json.static.Token
别名
std.json.static.Value
别名
源码
std/json/static.zig
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const ArrayList = std.array_list.Managed;
const Scanner = @import("Scanner.zig");
const Token = Scanner.Token;
const AllocWhen = Scanner.AllocWhen;
const default_max_value_len = Scanner.default_max_value_len;
const isNumberFormattedLikeAnInteger = Scanner.isNumberFormattedLikeAnInteger;
const Value = @import("./dynamic.zig").Value;
const Array = @import("./dynamic.zig").Array;
/// 控制如何处理 JSON 文档与传入 Zig 结构体类型之间的各种不一致。
/// 对于重复字段或未知字段,可在此结构体中设置选项。
/// 对于缺失字段,应为 Zig 结构体字段提供默认值。
pub const ParseOptions = struct {
/// 遇到重复字段时的行为。
/// 默认返回 `error.DuplicateField`。
duplicate_field_behavior: enum {
use_first,
@"error",
use_last,
} = .@"error",
/// 若为 false,则发现未知字段时返回 `error.UnknownField`。
ignore_unknown_fields: bool = false,
/// 传给 `std.json.Scanner.nextAllocMax` 或 `std.json.Reader.nextAllocMax`。
/// 对 `parseFromSlice`,或 `parseFromTokenSource`(以 `*std.json.Scanner` 为输入),默认值为输入切片长度,因此绝不会返回 `error.ValueTooLong`。
/// 对 `parseFromTokenSource`(以 `*std.json.Reader` 为输入),默认值为 `std.json.default_max_value_len`。
/// 不需要分配或不复制的值会忽略此选项,参见 `allocate`。
/// `parseFromValue` 和 `parseFromValueLeaky` 忽略此选项。
///
max_value_len: ?usize = null,
/// 决定是否始终复制字符串,
/// 或在可能时优先引用给定缓冲区。
/// `parseFromSlice` 或输入为 `*std.json.Scanner` 的 `parseFromTokenSource`,
/// 默认为 `.alloc_if_needed`。
/// 输入为 `*std.json.Reader` 时,默认为 `.alloc_always`。
/// `parseFromValue` 和 `parseFromValueLeaky` 忽略此设置。
allocate: ?AllocWhen = null,
/// 解析为 `std.json.Value` 时,将此选项设为 false,可始终将
/// JSON 数字作为未解析的 `std.json.Value.number_string` 生成。
/// 否则,根据 JSON 数字的格式和值,将其解析为 `std.json.Value.integer`、
/// `std.json.Value.float`,或保留为未解析的 `std.json.Value.number_string`。
///
/// 此选项为 true 时,以浮点格式编码的 JSON 数字,参见 `std.json.isNumberFormattedLikeAnInteger`,
/// 解析为 `std.json.Value.float` 时可能损失精度。
parse_numbers: bool = true,
};
pub fn Parsed(comptime T: type) type {
return struct {
arena: *ArenaAllocator,
value: T,
pub fn deinit(self: @This()) void {
const allocator = self.arena.child_allocator;
self.arena.deinit();
allocator.destroy(self.arena);
}
};
}
/// 从 `s` 解析 JSON 文档,并将结果包装为 `std.json.Parsed` 返回。
/// 必须调用返回对象的 `deinit()`,清理已分配资源。
/// 如果使用 `std.heap.ArenaAllocator` 或类似分配器,请考虑改用 `parseFromSliceLeaky`。
/// 注意,此函数实际不可能返回 `error.BufferUnderrun`。
pub fn parseFromSlice(
comptime T: type,
allocator: Allocator,
s: []const u8,
options: ParseOptions,
) ParseError(Scanner)!Parsed(T) {
var scanner = Scanner.initCompleteInput(allocator, s);
defer scanner.deinit();
return parseFromTokenSource(T, allocator, &scanner, options);
}
/// 从 `s` 解析 JSON 文档并返回结果。
/// 此操作中的分配不会被仔细跟踪,可能无法单独清理。
/// 建议使用 `std.heap.ArenaAllocator` 或类似分配器。
pub fn parseFromSliceLeaky(
comptime T: type,
allocator: Allocator,
s: []const u8,
options: ParseOptions,
) ParseError(Scanner)!T {
var scanner = Scanner.initCompleteInput(allocator, s);
defer scanner.deinit();
return parseFromTokenSourceLeaky(T, allocator, &scanner, options);
}
/// `scanner_or_reader` 必须为具有完整输入的 `*std.json.Scanner`,或为 `*std.json.Reader`。
/// 注意,此函数实际上不可能返回 `error.BufferUnderrun`。
pub fn parseFromTokenSource(
comptime T: type,
allocator: Allocator,
scanner_or_reader: anytype,
options: ParseOptions,
) ParseError(@TypeOf(scanner_or_reader.*))!Parsed(T) {
var parsed = Parsed(T){
.arena = try allocator.create(ArenaAllocator),
.value = undefined,
};
errdefer allocator.destroy(parsed.arena);
parsed.arena.* = ArenaAllocator.init(allocator);
errdefer parsed.arena.deinit();
parsed.value = try parseFromTokenSourceLeaky(T, parsed.arena.allocator(), scanner_or_reader, options);
return parsed;
}
/// `scanner_or_reader` 必须是包含完整输入的 `*std.json.Scanner`,或 `*std.json.Reader`。
/// 此操作中的分配不会被仔细跟踪,可能无法单独清理。
/// 建议使用 `std.heap.ArenaAllocator` 或类似分配器。
pub fn parseFromTokenSourceLeaky(
comptime T: type,
allocator: Allocator,
scanner_or_reader: anytype,
options: ParseOptions,
) ParseError(@TypeOf(scanner_or_reader.*))!T {
if (@TypeOf(scanner_or_reader.*) == Scanner) {
assert(scanner_or_reader.is_end_of_input);
}
var resolved_options = options;
if (resolved_options.max_value_len == null) {
if (@TypeOf(scanner_or_reader.*) == Scanner) {
resolved_options.max_value_len = scanner_or_reader.input.len;
} else {
resolved_options.max_value_len = default_max_value_len;
}
}
if (resolved_options.allocate == null) {
if (@TypeOf(scanner_or_reader.*) == Scanner) {
resolved_options.allocate = .alloc_if_needed;
} else {
resolved_options.allocate = .alloc_always;
}
}
const value = try innerParse(T, allocator, scanner_or_reader, resolved_options);
assert(.end_of_document == try scanner_or_reader.next());
return value;
}
/// 类似 `parseFromSlice`,但输入是已经解析的 `std.json.Value` 对象。
/// 仅使用 `options` 中的 `options.ignore_unknown_fields`。
pub fn parseFromValue(
comptime T: type,
allocator: Allocator,
source: Value,
options: ParseOptions,
) ParseFromValueError!Parsed(T) {
var parsed = Parsed(T){
.arena = try allocator.create(ArenaAllocator),
.value = undefined,
};
errdefer allocator.destroy(parsed.arena);
parsed.arena.* = ArenaAllocator.init(allocator);
errdefer parsed.arena.deinit();
parsed.value = try parseFromValueLeaky(T, parsed.arena.allocator(), source, options);
return parsed;
}
pub fn parseFromValueLeaky(
comptime T: type,
allocator: Allocator,
source: Value,
options: ParseOptions,
) ParseFromValueError!T {
// 此函数可能没有存在的必要,
// 但将此公开转发函数放在文件上部、将实现放在下部,
// 有助于清楚地组织源码并顺畅阅读。
return innerParseFromValue(T, allocator, source, options);
}
/// 从 `*Source` 解析时将返回的错误集合。
/// 注意,其中可能包含 `error.BufferUnderrun`,但实际上绝不会返回该错误。
pub fn ParseError(comptime Source: type) type {
// 其中几项始终存在,或存在频率足够高,因此省略它们比始终包含更令人困惑。
//
return ParseFromValueError || Source.NextError || Source.PeekError || Source.AllocError;
}
pub const ParseFromValueError = std.fmt.ParseIntError || std.fmt.ParseFloatError || Allocator.Error || error{
UnexpectedToken,
InvalidNumber,
Overflow,
InvalidEnumTag,
DuplicateField,
UnknownField,
MissingField,
LengthMismatch,
};
/// 此内部函数在 `parseFromTokenSourceLeaky` 等函数的实现过程中递归调用。
/// 公开它主要是为了让自定义 `jsonParse()` 方法能够回调 `parseFrom*` 系统。例如,实现 `T` 类型的自定义容器时,可对每个容器元素调用 `innerParse(T, ...)`。
/// 注意,调用此函数时,`null` 字段不允许出现在 `options` 中。
/// 在 `options` 中,即 `jsonParse` 方法所收到的选项,不包含 `null` 字段。
///
///
///
pub fn innerParse(
comptime T: type,
allocator: Allocator,
source: anytype,
options: ParseOptions,
) ParseError(@TypeOf(source.*))!T {
switch (@typeInfo(T)) {
.bool => {
return switch (try source.next()) {
.true => true,
.false => false,
else => error.UnexpectedToken,
};
},
.float, .comptime_float => {
const token = try source.nextAllocMax(allocator, .alloc_if_needed, options.max_value_len.?);
defer freeAllocated(allocator, token);
const slice = switch (token) {
inline .number, .allocated_number, .string, .allocated_string => |slice| slice,
else => return error.UnexpectedToken,
};
return try std.fmt.parseFloat(T, slice);
},
.int, .comptime_int => {
const token = try source.nextAllocMax(allocator, .alloc_if_needed, options.max_value_len.?);
defer freeAllocated(allocator, token);
const slice = switch (token) {
inline .number, .allocated_number, .string, .allocated_string => |slice| slice,
else => return error.UnexpectedToken,
};
return sliceToInt(T, slice);
},
.optional => |optionalInfo| {
switch (try source.peekNextTokenType()) {
.null => {
_ = try source.next();
return null;
},
else => {
return try innerParse(optionalInfo.child, allocator, source, options);
},
}
},
.@"enum" => {
if (std.meta.hasFn(T, "jsonParse")) {
return T.jsonParse(allocator, source, options);
}
const token = try source.nextAllocMax(allocator, .alloc_if_needed, options.max_value_len.?);
defer freeAllocated(allocator, token);
const slice = switch (token) {
inline .number, .allocated_number, .string, .allocated_string => |slice| slice,
else => return error.UnexpectedToken,
};
return sliceToEnum(T, slice);
},
.@"union" => |unionInfo| {
if (std.meta.hasFn(T, "jsonParse")) {
return T.jsonParse(allocator, source, options);
}
if (unionInfo.tag_type == null) @compileError("Unable to parse into untagged union '" ++ @typeName(T) ++ "'");
if (.object_begin != try source.next()) return error.UnexpectedToken;
var result: ?T = null;
var name_token: ?Token = try source.nextAllocMax(allocator, .alloc_if_needed, options.max_value_len.?);
const field_name = switch (name_token.?) {
inline .string, .allocated_string => |slice| slice,
else => {
return error.UnexpectedToken;
},
};
inline for (unionInfo.field_names, unionInfo.field_types) |u_field_name, u_field_type| {
if (std.mem.eql(u8, u_field_name, field_name)) {
// 立即释放名称词法标记,以利用可能对释放最后分配对象进行优化的分配器。
// 递归进入 innerParse() 可能触发更多分配。
freeAllocated(allocator, name_token.?);
name_token = null;
if (u_field_type == void) {
// void 并非真正的 json 类型,但可支持以 {} 为值的 void 载荷联合体标签。
if (.object_begin != try source.next()) return error.UnexpectedToken;
if (.object_end != try source.next()) return error.UnexpectedToken;
result = @unionInit(T, u_field_name, {});
} else {
// 递归。
result = @unionInit(T, u_field_name, try innerParse(u_field_type, allocator, source, options));
}
break;
}
} else {
// 未匹配任何内容。
return error.UnknownField;
}
if (.object_end != try source.next()) return error.UnexpectedToken;
return result.?;
},
.@"struct" => |structInfo| {
if (structInfo.is_tuple) {
if (.array_begin != try source.next()) return error.UnexpectedToken;
var r: T = undefined;
inline for (structInfo.field_types, 0..) |field_type, i| {
r[i] = try innerParse(field_type, allocator, source, options);
}
if (.array_end != try source.next()) return error.UnexpectedToken;
return r;
}
if (std.meta.hasFn(T, "jsonParse")) {
return T.jsonParse(allocator, source, options);
}
if (.object_begin != try source.next()) return error.UnexpectedToken;
var r: T = undefined;
var fields_seen: [structInfo.field_names.len]bool = @splat(false);
while (true) {
var name_token: ?Token = try source.nextAllocMax(allocator, .alloc_if_needed, options.max_value_len.?);
const field_name = switch (name_token.?) {
inline .string, .allocated_string => |slice| slice,
.object_end => { // 没有更多字段。
break;
},
else => {
return error.UnexpectedToken;
},
};
inline for (
structInfo.field_names,
structInfo.field_types,
structInfo.field_attrs,
0..,
) |f_name, f_type, f_attrs, i| {
if (f_attrs.@"comptime") @compileError("comptime fields are not supported: " ++ @typeName(T) ++ "." ++ f_name);
if (std.mem.eql(u8, f_name, field_name)) {
// 立即释放名称词法标记,以利用可能对释放最后分配对象进行优化的分配器。
// 递归进入 innerParse() 可能触发更多分配。
freeAllocated(allocator, name_token.?);
name_token = null;
if (fields_seen[i]) {
switch (options.duplicate_field_behavior) {
.use_first => {
// 解析并忽略冗余值。
// 不直接跳过此值,因为需要进行类型检查。
_ = try innerParse(f_type, allocator, source, options);
break;
},
.@"error" => return error.DuplicateField,
.use_last => {},
}
}
@field(r, f_name) = try innerParse(f_type, allocator, source, options);
fields_seen[i] = true;
break;
}
} else {
// 未匹配任何内容。
freeAllocated(allocator, name_token.?);
if (options.ignore_unknown_fields) {
try source.skipValue();
} else {
return error.UnknownField;
}
}
}
try fillDefaultStructValues(T, &r, &fields_seen);
return r;
},
.array => |arrayInfo| {
switch (try source.peekNextTokenType()) {
.array_begin => {
// 典型数组。
return internalParseArray(T, arrayInfo.child, allocator, source, options);
},
.string => {
if (arrayInfo.child != u8) return error.UnexpectedToken;
// 定长字符串。
var r: T = undefined;
var i: usize = 0;
while (true) {
switch (try source.next()) {
.string => |slice| {
if (i + slice.len != r.len) return error.LengthMismatch;
@memcpy(r[i..][0..slice.len], slice);
break;
},
.partial_string => |slice| {
if (i + slice.len > r.len) return error.LengthMismatch;
@memcpy(r[i..][0..slice.len], slice);
i += slice.len;
},
.partial_string_escaped_1 => |arr| {
if (i + arr.len > r.len) return error.LengthMismatch;
@memcpy(r[i..][0..arr.len], arr[0..]);
i += arr.len;
},
.partial_string_escaped_2 => |arr| {
if (i + arr.len > r.len) return error.LengthMismatch;
@memcpy(r[i..][0..arr.len], arr[0..]);
i += arr.len;
},
.partial_string_escaped_3 => |arr| {
if (i + arr.len > r.len) return error.LengthMismatch;
@memcpy(r[i..][0..arr.len], arr[0..]);
i += arr.len;
},
.partial_string_escaped_4 => |arr| {
if (i + arr.len > r.len) return error.LengthMismatch;
@memcpy(r[i..][0..arr.len], arr[0..]);
i += arr.len;
},
else => unreachable,
}
}
return r;
},
else => return error.UnexpectedToken,
}
},
.vector => |vector_info| {
switch (try source.peekNextTokenType()) {
.array_begin => {
const A = [vector_info.len]vector_info.child;
return try internalParseArray(A, vector_info.child, allocator, source, options);
},
else => return error.UnexpectedToken,
}
},
.pointer => |ptrInfo| {
switch (ptrInfo.size) {
.one => {
const r: *ptrInfo.child = try allocator.create(ptrInfo.child);
r.* = try innerParse(ptrInfo.child, allocator, source, options);
return r;
},
.slice => {
switch (try source.peekNextTokenType()) {
.array_begin => {
_ = try source.next();
// 典型数组。
var arraylist = ArrayList(ptrInfo.child).init(allocator);
while (true) {
switch (try source.peekNextTokenType()) {
.array_end => {
_ = try source.next();
break;
},
else => {},
}
try arraylist.ensureUnusedCapacity(1);
arraylist.appendAssumeCapacity(try innerParse(ptrInfo.child, allocator, source, options));
}
if (ptrInfo.sentinel()) |s| {
return try arraylist.toOwnedSliceSentinel(s);
}
return try arraylist.toOwnedSlice();
},
.string => {
if (ptrInfo.child != u8) return error.UnexpectedToken;
// 动态长度字符串。
if (ptrInfo.sentinel()) |s| {
// 使用自己的数组列表,以便追加哨兵值。
var value_list = ArrayList(u8).init(allocator);
_ = try source.allocNextIntoArrayListMax(&value_list, .alloc_always, options.max_value_len.?);
return try value_list.toOwnedSliceSentinel(s);
}
if (ptrInfo.attrs.@"const") {
switch (try source.nextAllocMax(allocator, options.allocate.?, options.max_value_len.?)) {
inline .string, .allocated_string => |slice| return slice,
else => unreachable,
}
} else {
// 必须分配内存以获取可变副本。
switch (try source.nextAllocMax(allocator, .alloc_always, options.max_value_len.?)) {
.allocated_string => |slice| return slice,
else => unreachable,
}
}
},
else => return error.UnexpectedToken,
}
},
else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"),
}
},
else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"),
}
unreachable;
}
fn internalParseArray(
comptime T: type,
comptime Child: type,
allocator: Allocator,
source: anytype,
options: ParseOptions,
) !T {
assert(.array_begin == try source.next());
var r: T = undefined;
for (&r) |*elem| {
elem.* = try innerParse(Child, allocator, source, options);
}
if (.array_end != try source.next()) return error.UnexpectedToken;
return r;
}
/// 这是 `parseFromValueLeaky` 实现中
/// 递归调用的内部函数。
/// 公开它主要是为了让自定义 `jsonParseFromValue()` 方法回调 `parseFromValue*` 系统,
/// 例如实现自定义 `T` 类型容器时,
/// 可对容器中的每个元素调用 `innerParseFromValue(T, ...)`。
pub fn innerParseFromValue(
comptime T: type,
allocator: Allocator,
source: Value,
options: ParseOptions,
) ParseFromValueError!T {
switch (@typeInfo(T)) {
.bool => {
switch (source) {
.bool => |b| return b,
else => return error.UnexpectedToken,
}
},
.float, .comptime_float => {
switch (source) {
.float => |f| return @as(T, @floatCast(f)),
.integer => |i| return @as(T, @floatFromInt(i)),
.number_string, .string => |s| return std.fmt.parseFloat(T, s),
else => return error.UnexpectedToken,
}
},
.int, .comptime_int => {
switch (source) {
.float => |f| {
if (@round(f) != f) return error.InvalidNumber;
if (f > @as(@TypeOf(f), @floatFromInt(std.math.maxInt(T)))) return error.Overflow;
if (f < @as(@TypeOf(f), @floatFromInt(std.math.minInt(T)))) return error.Overflow;
return @intFromFloat(f);
},
.integer => |i| {
if (i > std.math.maxInt(T)) return error.Overflow;
if (i < std.math.minInt(T)) return error.Overflow;
return @intCast(i);
},
.number_string, .string => |s| {
return sliceToInt(T, s);
},
else => return error.UnexpectedToken,
}
},
.optional => |optionalInfo| {
switch (source) {
.null => return null,
else => return try innerParseFromValue(optionalInfo.child, allocator, source, options),
}
},
.@"enum" => {
if (std.meta.hasFn(T, "jsonParseFromValue")) {
return T.jsonParseFromValue(allocator, source, options);
}
switch (source) {
.float => return error.InvalidEnumTag,
.integer => |i| return std.enums.fromInt(T, i) orelse return error.InvalidEnumTag,
.number_string, .string => |s| return sliceToEnum(T, s),
else => return error.UnexpectedToken,
}
},
.@"union" => |unionInfo| {
if (std.meta.hasFn(T, "jsonParseFromValue")) {
return T.jsonParseFromValue(allocator, source, options);
}
if (unionInfo.tag_type == null) @compileError("Unable to parse into untagged union '" ++ @typeName(T) ++ "'");
if (source != .object) return error.UnexpectedToken;
if (source.object.count() != 1) return error.UnexpectedToken;
var it = source.object.iterator();
const kv = it.next().?;
const field_name = kv.key_ptr.*;
inline for (unionInfo.field_names, unionInfo.field_types) |u_field_name, u_field_type| {
if (std.mem.eql(u8, u_field_name, field_name)) {
if (u_field_type == void) {
// void 并非真正的 json 类型,但可支持以 {} 为值的 void 载荷联合体标签。
if (kv.value_ptr.* != .object) return error.UnexpectedToken;
if (kv.value_ptr.*.object.count() != 0) return error.UnexpectedToken;
return @unionInit(T, u_field_name, {});
}
// 递归。
return @unionInit(T, u_field_name, try innerParseFromValue(u_field_type, allocator, kv.value_ptr.*, options));
}
}
// 未匹配任何内容。
return error.UnknownField;
},
.@"struct" => |structInfo| {
if (structInfo.is_tuple) {
if (source != .array) return error.UnexpectedToken;
if (source.array.items.len != structInfo.field_names.len) return error.UnexpectedToken;
var r: T = undefined;
inline for (0..structInfo.field_names.len, source.array.items) |i, item| {
r[i] = try innerParseFromValue(structInfo.field_types[i], allocator, item, options);
}
return r;
}
if (std.meta.hasFn(T, "jsonParseFromValue")) {
return T.jsonParseFromValue(allocator, source, options);
}
if (source != .object) return error.UnexpectedToken;
var r: T = undefined;
var fields_seen: [structInfo.field_names.len]bool = @splat(false);
var it = source.object.iterator();
while (it.next()) |kv| {
const field_name = kv.key_ptr.*;
inline for (
structInfo.field_names,
structInfo.field_types,
structInfo.field_attrs,
0..,
) |f_name, f_type, f_attrs, i| {
if (f_attrs.@"comptime") @compileError("comptime fields are not supported: " ++ @typeName(T) ++ "." ++ f_name);
if (std.mem.eql(u8, f_name, field_name)) {
assert(!fields_seen[i]); // Value.object 中不能有重复键。
@field(r, f_name) = try innerParseFromValue(f_type, allocator, kv.value_ptr.*, options);
fields_seen[i] = true;
break;
}
} else {
// 未匹配任何内容。
if (!options.ignore_unknown_fields) return error.UnknownField;
}
}
try fillDefaultStructValues(T, &r, &fields_seen);
return r;
},
.array => |arrayInfo| {
switch (source) {
.array => |array| {
// 典型数组。
return innerParseArrayFromArrayValue(T, arrayInfo.child, arrayInfo.len, allocator, array, options);
},
.string => |s| {
if (arrayInfo.child != u8) return error.UnexpectedToken;
// 定长字符串。
if (s.len != arrayInfo.len) return error.LengthMismatch;
var r: T = undefined;
@memcpy(r[0..], s);
return r;
},
else => return error.UnexpectedToken,
}
},
.vector => |vecInfo| {
switch (source) {
.array => |array| {
return innerParseArrayFromArrayValue(T, vecInfo.child, vecInfo.len, allocator, array, options);
},
else => return error.UnexpectedToken,
}
},
.pointer => |ptrInfo| {
switch (ptrInfo.size) {
.one => {
const r: *ptrInfo.child = try allocator.create(ptrInfo.child);
r.* = try innerParseFromValue(ptrInfo.child, allocator, source, options);
return r;
},
.slice => {
switch (source) {
.array => |array| {
const r = if (ptrInfo.sentinel()) |sentinel|
try allocator.allocSentinel(ptrInfo.child, array.items.len, sentinel)
else
try allocator.alloc(ptrInfo.child, array.items.len);
for (array.items, r) |item, *dest| {
dest.* = try innerParseFromValue(ptrInfo.child, allocator, item, options);
}
return r;
},
.string => |s| {
if (ptrInfo.child != u8) return error.UnexpectedToken;
// 动态长度字符串。
const r = if (ptrInfo.sentinel()) |sentinel|
try allocator.allocSentinel(ptrInfo.child, s.len, sentinel)
else
try allocator.alloc(ptrInfo.child, s.len);
@memcpy(r[0..], s);
return r;
},
else => return error.UnexpectedToken,
}
},
else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"),
}
},
else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"),
}
}
fn innerParseArrayFromArrayValue(
comptime T: type,
comptime Child: type,
comptime len: comptime_int,
allocator: Allocator,
array: Array,
options: ParseOptions,
) !T {
if (array.items.len != len) return error.LengthMismatch;
var r: T = undefined;
for (array.items, 0..) |item, i| {
r[i] = try innerParseFromValue(Child, allocator, item, options);
}
return r;
}
fn sliceToInt(comptime T: type, slice: []const u8) !T {
if (isNumberFormattedLikeAnInteger(slice))
return std.fmt.parseInt(T, slice, 10);
// 尝试将浮点数强制转换为整数。
const float = try std.fmt.parseFloat(f128, slice);
if (@round(float) != float) return error.InvalidNumber;
if (float > @as(f128, @floatFromInt(std.math.maxInt(T))) or float < @as(f128, @floatFromInt(std.math.minInt(T)))) return error.Overflow;
return @as(T, @intCast(@as(i128, @intFromFloat(float))));
}
fn sliceToEnum(comptime T: type, slice: []const u8) !T {
// 检查是否存在命名值。
if (std.meta.stringToEnum(T, slice)) |value| return value;
// 检查是否为数值。
if (!isNumberFormattedLikeAnInteger(slice)) return error.InvalidEnumTag;
const n = std.fmt.parseInt(@typeInfo(T).@"enum".tag_type, slice, 10) catch return error.InvalidEnumTag;
return std.enums.fromInt(T, n) orelse return error.InvalidEnumTag;
}
fn fillDefaultStructValues(comptime T: type, r: *T, fields_seen: *[@typeInfo(T).@"struct".field_names.len]bool) !void {
const info = @typeInfo(T).@"struct";
inline for (
info.field_names,
info.field_types,
info.field_attrs,
0..,
) |field_name, field_type, field_attrs, i| {
if (!fields_seen[i]) {
if (field_attrs.defaultValue(field_type)) |default| {
@field(r, field_name) = default;
} else {
return error.MissingField;
}
}
}
}
fn freeAllocated(allocator: Allocator, token: Token) void {
switch (token) {
.allocated_number, .allocated_string => |slice| {
allocator.free(slice);
},
else => {},
}
}
test {
_ = @import("./static_test.zig");
}