DoxigAlpha

parseCharLiteral

Asserts the slice starts and ends with single-quotes. Returns an error if there is not exactly one UTF-8 codepoint in between.

Function parameters

Parameters

#
slice:[]const u8

Type definitions in this namespace

Types

#

Asserts the slice starts and ends with single-quotes.

Functions

#
parseCharLiteral
Asserts the slice starts and ends with single-quotes.
parseEscapeSequence
Parse an escape sequence from `slice[offset..]`.
parseWrite
Parses `bytes` as a Zig string literal and writes the result to the `Writer` type.
parseAlloc
Higher level API.

Error sets in this namespace

Error Sets

#

Source

Implementation

#
pub fn parseCharLiteral(slice: []const u8) ParsedCharLiteral {
    if (slice.len < 3) return .{ .failure = .empty_char_literal };
    assert(slice[0] == '\'');
    assert(slice[slice.len - 1] == '\'');

    switch (slice[1]) {
        '\\' => {
            var offset: usize = 1;
            const result = parseEscapeSequence(slice, &offset);
            if (result == .success and (offset + 1 != slice.len or slice[offset] != '\''))
                return .{ .failure = .{ .expected_single_quote = offset } };

            return result;
        },
        0 => return .{ .failure = .{ .invalid_character = 1 } },
        else => {
            const inner = slice[1 .. slice.len - 1];
            const n = std.unicode.utf8ByteSequenceLength(inner[0]) catch return .{
                .failure = .{ .invalid_unicode_codepoint = 1 },
            };
            if (inner.len > n) return .{ .failure = .{ .expected_single_quote = 1 + n } };
            const codepoint = switch (n) {
                1 => inner[0],
                2 => std.unicode.utf8Decode2(inner[0..2].*),
                3 => std.unicode.utf8Decode3(inner[0..3].*),
                4 => std.unicode.utf8Decode4(inner[0..4].*),
                else => unreachable,
            } catch return .{ .failure = .{ .invalid_unicode_codepoint = 1 } };
            return .{ .success = codepoint };
        },
    }
}