From 4b7dfe149422efa848e62a791b5ca73c2065480b Mon Sep 17 00:00:00 2001 From: Jose Colon Rodriguez Date: Fri, 16 Feb 2024 19:36:19 -0400 Subject: display_width with table --- build.zig | 25 +++++- codegen/dwp.zig | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/display_width.zig | 111 +++++++++++++++++++++++ src/main.zig | 14 +-- 4 files changed, 386 insertions(+), 7 deletions(-) create mode 100644 codegen/dwp.zig create mode 100644 src/display_width.zig diff --git a/build.zig b/build.zig index 6353874..2a39549 100644 --- a/build.zig +++ b/build.zig @@ -17,6 +17,15 @@ pub fn build(b: *std.Build) void { const run_gbp_gen_exe = b.addRunArtifact(gbp_gen_exe); const gbp_gen_out = run_gbp_gen_exe.addOutputFileArg("gbp.zig"); + const dwp_gen_exe = b.addExecutable(.{ + .name = "dwp", + .root_source_file = .{ .path = "codegen/dwp.zig" }, + .target = b.host, + .optimize = .Debug, + }); + const run_dwp_gen_exe = b.addRunArtifact(dwp_gen_exe); + const dwp_gen_out = run_dwp_gen_exe.addOutputFileArg("dwp.zig"); + // Modules we provide const code_point = b.addModule("CodePoint", .{ .root_source_file = .{ .path = "src/CodePoint.zig" }, @@ -32,6 +41,15 @@ pub fn build(b: *std.Build) void { grapheme.addImport("CodePoint", code_point); grapheme.addAnonymousImport("gbp", .{ .root_source_file = gbp_gen_out }); + const display_width = b.addModule("display_width", .{ + .root_source_file = .{ .path = "src/display_width.zig" }, + .target = target, + .optimize = optimize, + }); + display_width.addImport("CodePoint", code_point); + display_width.addImport("Grapheme", grapheme); + display_width.addAnonymousImport("dwp", .{ .root_source_file = dwp_gen_out }); + // Benchmark rig const exe = b.addExecutable(.{ .name = "zgbench", @@ -40,7 +58,9 @@ pub fn build(b: *std.Build) void { .optimize = optimize, }); exe.root_module.addImport("ziglyph", ziglyph.module("ziglyph")); + exe.root_module.addImport("CodePoint", code_point); exe.root_module.addImport("Grapheme", grapheme); + exe.root_module.addImport("display_width", display_width); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); @@ -52,12 +72,13 @@ pub fn build(b: *std.Build) void { // Tests const exe_unit_tests = b.addTest(.{ - .root_source_file = .{ .path = "src/main.zig" }, + .root_source_file = .{ .path = "src/display_width.zig" }, .target = target, .optimize = optimize, }); - exe_unit_tests.root_module.addImport("ziglyph", ziglyph.module("ziglyph")); + exe_unit_tests.root_module.addImport("CodePoint", code_point); exe_unit_tests.root_module.addImport("Grapheme", grapheme); + exe_unit_tests.root_module.addAnonymousImport("dwp", .{ .root_source_file = dwp_gen_out }); const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); diff --git a/codegen/dwp.zig b/codegen/dwp.zig new file mode 100644 index 0000000..a8cef57 --- /dev/null +++ b/codegen/dwp.zig @@ -0,0 +1,243 @@ +const std = @import("std"); + +const block_size = 256; +const Block = [block_size]i3; + +const BlockMap = std.HashMap( + Block, + u16, + struct { + pub fn hash(_: @This(), k: Block) u64 { + var hasher = std.hash.Wyhash.init(0); + std.hash.autoHashStrat(&hasher, k, .DeepRecursive); + return hasher.final(); + } + + pub fn eql(_: @This(), a: Block, b: Block) bool { + return std.mem.eql(i3, &a, &b); + } + }, + std.hash_map.default_max_load_percentage, +); + +pub fn main() !void { + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + var flat_map = std.AutoHashMap(u21, i3).init(allocator); + defer flat_map.deinit(); + + var line_buf: [4096]u8 = undefined; + + // Process DerivedEastAsianWidth.txt + var deaw_file = try std.fs.cwd().openFile("unicode/extracted/DerivedEastAsianWidth.txt", .{}); + defer deaw_file.close(); + var deaw_buf = std.io.bufferedReader(deaw_file.reader()); + const deaw_reader = deaw_buf.reader(); + + while (try deaw_reader.readUntilDelimiterOrEof(&line_buf, '\n')) |line| { + if (line.len == 0) continue; + + // @missing ranges + if (std.mem.startsWith(u8, line, "# @missing: ")) { + const semi = std.mem.indexOfScalar(u8, line, ';').?; + const field = line[12..semi]; + const dots = std.mem.indexOf(u8, field, "..").?; + const from = try std.fmt.parseInt(u21, field[0..dots], 16); + const to = try std.fmt.parseInt(u21, field[dots + 2 ..], 16); + if (from == 0 and to == 0x10ffff) continue; + for (from..to + 1) |cp| try flat_map.put(@intCast(cp), 2); + continue; + } + + if (line[0] == '#') continue; + + const no_comment = if (std.mem.indexOfScalar(u8, line, '#')) |octo| line[0..octo] else line; + + var field_iter = std.mem.tokenizeAny(u8, no_comment, "; "); + var current_code: [2]u21 = undefined; + + var i: usize = 0; + while (field_iter.next()) |field| : (i += 1) { + switch (i) { + 0 => { + // Code point(s) + if (std.mem.indexOf(u8, field, "..")) |dots| { + current_code = .{ + try std.fmt.parseInt(u21, field[0..dots], 16), + try std.fmt.parseInt(u21, field[dots + 2 ..], 16), + }; + } else { + const code = try std.fmt.parseInt(u21, field, 16); + current_code = .{ code, code }; + } + }, + 1 => { + // Width + if (std.mem.eql(u8, field, "W") or std.mem.eql(u8, field, "F")) { + for (current_code[0]..current_code[1] + 1) |cp| try flat_map.put(@intCast(cp), 2); + } + }, + else => {}, + } + } + } + + // Process DerivedGeneralCategory.txt + var dgc_file = try std.fs.cwd().openFile("unicode/extracted/DerivedGeneralCategory.txt", .{}); + defer dgc_file.close(); + var dgc_buf = std.io.bufferedReader(dgc_file.reader()); + const dgc_reader = dgc_buf.reader(); + + while (try dgc_reader.readUntilDelimiterOrEof(&line_buf, '\n')) |line| { + if (line.len == 0 or line[0] == '#') continue; + const no_comment = if (std.mem.indexOfScalar(u8, line, '#')) |octo| line[0..octo] else line; + + var field_iter = std.mem.tokenizeAny(u8, no_comment, "; "); + var current_code: [2]u21 = undefined; + + var i: usize = 0; + while (field_iter.next()) |field| : (i += 1) { + switch (i) { + 0 => { + // Code point(s) + if (std.mem.indexOf(u8, field, "..")) |dots| { + current_code = .{ + try std.fmt.parseInt(u21, field[0..dots], 16), + try std.fmt.parseInt(u21, field[dots + 2 ..], 16), + }; + } else { + const code = try std.fmt.parseInt(u21, field, 16); + current_code = .{ code, code }; + } + }, + 1 => { + // General category + if (std.mem.eql(u8, field, "Mn")) { + // Nonspacing_Mark + for (current_code[0]..current_code[1] + 1) |cp| try flat_map.put(@intCast(cp), 0); + } else if (std.mem.eql(u8, field, "Me")) { + // Enclosing_Mark + for (current_code[0]..current_code[1] + 1) |cp| try flat_map.put(@intCast(cp), 0); + } else if (std.mem.eql(u8, field, "Mc")) { + // Spacing_Mark + for (current_code[0]..current_code[1] + 1) |cp| try flat_map.put(@intCast(cp), 0); + } else if (std.mem.eql(u8, field, "Cf")) { + if (std.mem.indexOf(u8, line, "ARABIC") == null) { + // Format except Arabic + for (current_code[0]..current_code[1] + 1) |cp| try flat_map.put(@intCast(cp), 0); + } + } + }, + else => {}, + } + } + } + + var blocks_map = BlockMap.init(allocator); + defer blocks_map.deinit(); + + var stage1 = std.ArrayList(u16).init(allocator); + defer stage1.deinit(); + + var stage2 = std.ArrayList(i3).init(allocator); + defer stage2.deinit(); + + var block: Block = [_]i3{0} ** block_size; + var block_len: u16 = 0; + + for (0..0x110000) |i| { + const cp: u21 = @intCast(i); + var width = flat_map.get(cp) orelse 1; + + // Specific overrides + switch (cp) { + // Three-em dash + 0x2e3b => width = 3, + + // C0/C1 control codes + 0...0x20, + 0x80...0xa0, + + // Line separator + 0x2028, + + // Paragraph separator + 0x2029, + + // Hangul syllable and ignorable. + 0x1160...0x11ff, + 0xd7b0...0xd7ff, + 0x2060...0x206f, + 0xfff0...0xfff8, + 0xe0000...0xE0fff, + + // Sk with EMOJI MODIFIER comment + 0x1f3fb...0x1f3ff, + => width = 0, + + // Two-em dash + 0x2e3a, + + // Regional indicators + 0x1f1e6...0x1f200, + + // CJK Blocks + 0x3400...0x4dbf, // CJK Unified Ideographs Extension A + 0x4e00...0x9fff, // CJK Unified Ideographs + 0xf900...0xfaff, // CJK Compatibility Ideographs + 0x20000...0x2fffd, // Plane 2 + 0x30000...0x3fffd, // Plane 3 + => width = 2, + + else => {}, + } + + // ASCII + if (0x20 <= cp and cp < 0x7f) width = 1; + + // Soft hyphen + if (cp == 0xad) width = 1; + + // Backspace and delete + if (cp == 0x8 or cp == 0x7f) width = -1; + + // Process block + block[block_len] = width; + block_len += 1; + + if (block_len < block_size and cp != 0x10ffff) continue; + + const gop = try blocks_map.getOrPut(block); + if (!gop.found_existing) { + gop.value_ptr.* = @intCast(stage2.items.len); + try stage2.appendSlice(&block); + } + + try stage1.append(gop.value_ptr.*); + block_len = 0; + } + + var args_iter = std.process.args(); + _ = args_iter.skip(); + const output_path = args_iter.next() orelse @panic("No output file arg!"); + + var out_file = try std.fs.cwd().createFile(output_path, .{}); + defer out_file.close(); + var out_buf = std.io.bufferedWriter(out_file.writer()); + const writer = out_buf.writer(); + + try writer.writeAll("const std = @import(\"std\");\n"); + + try writer.print("const Stage2Int = std.math.IntFittingRange(0, {});\n", .{stage2.items.len}); + try writer.print("pub const stage_1 = [{}]Stage2Int{{", .{stage1.items.len}); + for (stage1.items) |v| try writer.print("{},", .{v}); + try writer.writeAll("};\n"); + + try writer.print("pub const stage_2 = [{}]i3{{", .{stage2.items.len}); + for (stage2.items) |v| try writer.print("{},", .{v}); + try writer.writeAll("};\n"); + + try out_buf.flush(); +} diff --git a/src/display_width.zig b/src/display_width.zig new file mode 100644 index 0000000..e06aa8f --- /dev/null +++ b/src/display_width.zig @@ -0,0 +1,111 @@ +const std = @import("std"); +const testing = std.testing; + +const CodePointIterator = @import("CodePoint").CodePointIterator; +const GraphemeIterator = @import("Grapheme").GraphemeIterator; +const dwp = @import("dwp"); + +/// codePointWidth returns the number of cells `cp` requires when rendered +/// in a fixed-pitch font (i.e. a terminal screen). This can range from -1 to +/// 3, where BACKSPACE and DELETE return -1 and 3-em-dash returns 3. C0/C1 +/// control codes return 0. If `cjk` is true, ambiguous code points return 2, +/// otherwise they return 1. +pub fn codePointWidth(cp: u21) i3 { + return dwp.stage_2[dwp.stage_1[cp >> 8] + (cp & 0xff)]; +} + +fn strWidth(str: []const u8) usize { + var total: isize = 0; + var giter = GraphemeIterator.init(str); + + while (giter.next()) |gc| { + var cp_iter = CodePointIterator{ .bytes = str[gc.offset..][0..gc.len] }; + var gc_total: isize = 0; + + while (cp_iter.next()) |cp| { + var w = codePointWidth(cp.code); + + if (w != 0) { + // Handle text emoji sequence. + if (cp_iter.next()) |ncp| { + // emoji text sequence. + if (ncp.code == 0xFE0E) w = 1; + } + + // Only adding width of first non-zero-width code point. + if (gc_total == 0) gc_total = w; + } + } + + total += gc_total; + } + + return if (total > 0) @intCast(total) else 0; +} + +test "display_width Width" { + try testing.expectEqual(@as(i3, 0), codePointWidth(0x0000)); // null + try testing.expectEqual(@as(i3, -1), codePointWidth(0x8)); // \b + try testing.expectEqual(@as(i3, -1), codePointWidth(0x7f)); // DEL + try testing.expectEqual(@as(i3, 0), codePointWidth(0x0005)); // Cf + try testing.expectEqual(@as(i3, 0), codePointWidth(0x0007)); // \a BEL + try testing.expectEqual(@as(i3, 0), codePointWidth(0x000A)); // \n LF + try testing.expectEqual(@as(i3, 0), codePointWidth(0x000B)); // \v VT + try testing.expectEqual(@as(i3, 0), codePointWidth(0x000C)); // \f FF + try testing.expectEqual(@as(i3, 0), codePointWidth(0x000D)); // \r CR + try testing.expectEqual(@as(i3, 0), codePointWidth(0x000E)); // SQ + try testing.expectEqual(@as(i3, 0), codePointWidth(0x000F)); // SI + + try testing.expectEqual(@as(i3, 0), codePointWidth(0x070F)); // Cf + try testing.expectEqual(@as(i3, 1), codePointWidth(0x0603)); // Cf Arabic + + try testing.expectEqual(@as(i3, 1), codePointWidth(0x00AD)); // soft-hyphen + try testing.expectEqual(@as(i3, 2), codePointWidth(0x2E3A)); // two-em dash + try testing.expectEqual(@as(i3, 3), codePointWidth(0x2E3B)); // three-em dash + + try testing.expectEqual(@as(i3, 1), codePointWidth(0x00BD)); // ambiguous halfwidth + + try testing.expectEqual(@as(i3, 1), codePointWidth('é')); + try testing.expectEqual(@as(i3, 2), codePointWidth('😊')); + try testing.expectEqual(@as(i3, 2), codePointWidth('统')); + + try testing.expectEqual(@as(usize, 5), strWidth("Hello\r\n")); + try testing.expectEqual(@as(usize, 1), strWidth("\u{0065}\u{0301}")); + try testing.expectEqual(@as(usize, 2), strWidth("\u{1F476}\u{1F3FF}\u{0308}\u{200D}\u{1F476}\u{1F3FF}")); + try testing.expectEqual(@as(usize, 8), strWidth("Hello 😊")); + try testing.expectEqual(@as(usize, 8), strWidth("Héllo 😊")); + try testing.expectEqual(@as(usize, 8), strWidth("Héllo :)")); + try testing.expectEqual(@as(usize, 8), strWidth("Héllo 🇪🇸")); + try testing.expectEqual(@as(usize, 2), strWidth("\u{26A1}")); // Lone emoji + try testing.expectEqual(@as(usize, 1), strWidth("\u{26A1}\u{FE0E}")); // Text sequence + try testing.expectEqual(@as(usize, 2), strWidth("\u{26A1}\u{FE0F}")); // Presentation sequence + try testing.expectEqual(@as(usize, 0), strWidth("A\x08")); // Backspace + try testing.expectEqual(@as(usize, 0), strWidth("\x7FA")); // DEL + try testing.expectEqual(@as(usize, 0), strWidth("\x7FA\x08\x08")); // never less than o + + // wcwidth Python lib tests. See: https://github.com/jquast/wcwidth/blob/master/tests/test_core.py + const empty = ""; + try testing.expectEqual(@as(usize, 0), strWidth(empty)); + const with_null = "hello\x00world"; + try testing.expectEqual(@as(usize, 10), strWidth(with_null)); + const hello_jp = "コンニチハ, セカイ!"; + try testing.expectEqual(@as(usize, 19), strWidth(hello_jp)); + const control = "\x1b[0m"; + try testing.expectEqual(@as(usize, 3), strWidth(control)); + const balinese = "\u{1B13}\u{1B28}\u{1B2E}\u{1B44}"; + try testing.expectEqual(@as(usize, 3), strWidth(balinese)); + + // These commented out tests require a new specification for complex scripts. + // See: https://www.unicode.org/L2/L2023/23107-terminal-suppt.pdf + // const jamo = "\u{1100}\u{1160}"; + // try testing.expectEqual(@as(usize, 3), strWidth(jamo)); + // const devengari = "\u{0915}\u{094D}\u{0937}\u{093F}"; + // try testing.expectEqual(@as(usize, 3), strWidth(devengari)); + // const tamal = "\u{0b95}\u{0bcd}\u{0bb7}\u{0bcc}"; + // try testing.expectEqual(@as(usize, 5), strWidth(tamal)); + // const kannada_1 = "\u{0cb0}\u{0ccd}\u{0c9d}\u{0cc8}"; + // try testing.expectEqual(@as(usize, 3), strWidth(kannada_1)); + // The following passes but as a mere coincidence. + const kannada_2 = "\u{0cb0}\u{0cbc}\u{0ccd}\u{0c9a}"; + try testing.expectEqual(@as(usize, 2), strWidth(kannada_2)); +} diff --git a/src/main.zig b/src/main.zig index fe49300..3e65c7b 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,7 +1,10 @@ const std = @import("std"); // const GraphemeIterator = @import("ziglyph").GraphemeIterator; -const GraphemeIterator = @import("Grapheme").GraphemeIterator; +// const GraphemeIterator = @import("Grapheme").GraphemeIterator; +// const codePointWidth = @import("ziglyph").display_width.codePointWidth; +const codePointWidth = @import("display_width").codePointWidth; +const CodePointIterator = @import("CodePoint").CodePointIterator; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; @@ -11,14 +14,15 @@ pub fn main() !void { const input = try std.fs.cwd().readFileAlloc(allocator, "lang_mix.txt", std.math.maxInt(u32)); defer allocator.free(input); - var result: usize = 0; - var iter = GraphemeIterator.init(input); + var result: isize = 0; + // var iter = GraphemeIterator.init(input); + var iter = CodePointIterator{ .bytes = input }; var timer = try std.time.Timer.start(); // for (0..50) |_| { - while (iter.next()) |_| result += 1; - iter.cp_iter.i = 0; + while (iter.next()) |cp| result += codePointWidth(@intCast(cp.code)); + // iter.cp_iter.i = 0; // } std.debug.print("result: {}, took: {}\n", .{ result, timer.lap() / std.time.ns_per_ms }); -- cgit v1.2.3