Function parseAlloc [src]
Higher level API. Does not return extra info about parse errors.
Caller owns returned memory.
Prototype
pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]u8 Parameters
allocator: std.mem.Allocatorbytes: []const u8 Possible Errors
Example
test parseAlloc {
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const eql = std.mem.eql;
var fixed_buf_mem: [512]u8 = undefined;
var fixed_buf_alloc = std.heap.FixedBufferAllocator.init(&fixed_buf_mem);
const alloc = fixed_buf_alloc.allocator();
try expectError(error.InvalidLiteral, parseAlloc(alloc, "\"\\x6\""));
try expect(eql(u8, "foo\nbar", try parseAlloc(alloc, "\"foo\\nbar\"")));
try expect(eql(u8, "\x12foo", try parseAlloc(alloc, "\"\\x12foo\"")));
try expect(eql(u8, "bytes\u{1234}foo", try parseAlloc(alloc, "\"bytes\\u{1234}foo\"")));
try expect(eql(u8, "foo", try parseAlloc(alloc, "\"foo\"")));
try expect(eql(u8, "foo", try parseAlloc(alloc, "\"f\x6f\x6f\"")));
try expect(eql(u8, "f💯", try parseAlloc(alloc, "\"f\u{1f4af}\"")));
} Source
pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]u8 {
var aw: Writer.Allocating = .init(allocator);
defer aw.deinit();
const result = parseWrite(&aw.writer, bytes) catch |err| switch (err) {
error.WriteFailed => return error.OutOfMemory,
};
switch (result) {
.success => return aw.toOwnedSlice(),
.failure => return error.InvalidLiteral,
}
}