From 789625d2ce4b6e74f2372f87c20304639fa343ef Mon Sep 17 00:00:00 2001 From: Jose Colon Rodriguez Date: Sun, 24 Mar 2024 20:03:45 -0400 Subject: NumericData --- build.zig | 34 ++++++++++--- codegen/numeric.zig | 141 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/NumericData.zig | 75 ++++++++++++++++++++++++++++ src/main.zig | 32 +++++++----- 4 files changed, 263 insertions(+), 19 deletions(-) create mode 100644 codegen/numeric.zig create mode 100644 src/NumericData.zig diff --git a/build.zig b/build.zig index c3d9fe0..316292e 100644 --- a/build.zig +++ b/build.zig @@ -97,6 +97,16 @@ pub fn build(b: *std.Build) void { const run_fold_gen_exe = b.addRunArtifact(fold_gen_exe); const fold_gen_out = run_fold_gen_exe.addOutputFileArg("fold.bin.z"); + // Numeric types + const num_gen_exe = b.addExecutable(.{ + .name = "numeric", + .root_source_file = .{ .path = "codegen/numeric.zig" }, + .target = b.host, + .optimize = .Debug, + }); + const run_num_gen_exe = b.addRunArtifact(num_gen_exe); + const num_gen_out = run_num_gen_exe.addOutputFileArg("numeric.bin.z"); + // Modules we provide // Code points const code_point = b.addModule("code_point", .{ @@ -228,6 +238,14 @@ pub fn build(b: *std.Build) void { case_fold.addImport("FoldData", fold_data); case_fold.addImport("Normalize", norm); + // Numeric type + const num_data = b.createModule(.{ + .root_source_file = .{ .path = "src/NumericData.zig" }, + .target = target, + .optimize = optimize, + }); + num_data.addAnonymousImport("numeric", .{ .root_source_file = num_gen_out }); + // Benchmark rig const exe = b.addExecutable(.{ .name = "zg", @@ -238,12 +256,13 @@ pub fn build(b: *std.Build) void { }); // exe.root_module.addImport("ziglyph", ziglyph.module("ziglyph")); // exe.root_module.addImport("ascii", ascii); - // exe.root_module.addImport("code_point", code_point); + exe.root_module.addImport("code_point", code_point); // exe.root_module.addImport("grapheme", grapheme); // exe.root_module.addImport("DisplayWidth", display_width); - exe.root_module.addImport("Normalize", norm); + // exe.root_module.addImport("Normalize", norm); // exe.root_module.addImport("CaseFold", case_fold); // exe.root_module.addImport("GenCatData", gencat_data); + exe.root_module.addImport("NumericData", num_data); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); @@ -255,20 +274,21 @@ pub fn build(b: *std.Build) void { // Tests const exe_unit_tests = b.addTest(.{ - .root_source_file = .{ .path = "src/CaseFold.zig" }, + .root_source_file = .{ .path = "src/NumericData.zig" }, .target = target, .optimize = optimize, }); - exe_unit_tests.root_module.addImport("ascii", ascii); + // exe_unit_tests.root_module.addImport("ascii", ascii); // exe_unit_tests.root_module.addImport("code_point", code_point); // exe_unit_tests.root_module.addImport("GraphemeData", grapheme_data); // exe_unit_tests.root_module.addImport("grapheme", grapheme); // exe_unit_tests.root_module.addImport("ziglyph", ziglyph.module("ziglyph")); // exe_unit_tests.root_module.addAnonymousImport("normp", .{ .root_source_file = normp_gen_out }); // exe_unit_tests.root_module.addImport("DisplayWidthData", dw_data); - exe_unit_tests.root_module.addImport("NormData", norm_data); - exe_unit_tests.root_module.addImport("Normalize", norm); - exe_unit_tests.root_module.addImport("FoldData", fold_data); + // exe_unit_tests.root_module.addImport("NormData", norm_data); + // exe_unit_tests.root_module.addImport("Normalize", norm); + // exe_unit_tests.root_module.addImport("FoldData", fold_data); + exe_unit_tests.root_module.addAnonymousImport("numeric", .{ .root_source_file = num_gen_out }); // exe_unit_tests.filter = "nfd !ASCII"; const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); diff --git a/codegen/numeric.zig b/codegen/numeric.zig new file mode 100644 index 0000000..80fc7c2 --- /dev/null +++ b/codegen/numeric.zig @@ -0,0 +1,141 @@ +const std = @import("std"); +const builtin = @import("builtin"); + +const block_size = 256; +const Block = [block_size]u8; + +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(u8, &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, u8).init(allocator); + defer flat_map.deinit(); + + var line_buf: [4096]u8 = undefined; + + // Process DerivedCombiningClass.txt + var num_file = try std.fs.cwd().openFile("data/unicode/extracted/DerivedNumericType.txt", .{}); + defer num_file.close(); + var num_buf = std.io.bufferedReader(num_file.reader()); + const num_reader = num_buf.reader(); + + while (try num_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 => { + // Numeric type + if (std.mem.eql(u8, field, "Numeric")) { + for (current_code[0]..current_code[1] + 1) |cp| { + const gop = try flat_map.getOrPut(@intCast(cp)); + if (!gop.found_existing) gop.value_ptr.* = 0; + gop.value_ptr.* |= 1; + } + } else if (std.mem.eql(u8, field, "Digit")) { + for (current_code[0]..current_code[1] + 1) |cp| { + const gop = try flat_map.getOrPut(@intCast(cp)); + if (!gop.found_existing) gop.value_ptr.* = 0; + gop.value_ptr.* |= 2; + } + } else if (std.mem.eql(u8, field, "Decimal")) { + for (current_code[0]..current_code[1] + 1) |cp| { + const gop = try flat_map.getOrPut(@intCast(cp)); + if (!gop.found_existing) gop.value_ptr.* = 0; + gop.value_ptr.* |= 4; + } + } else continue; + }, + 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(u8).init(allocator); + defer stage2.deinit(); + + var block: Block = [_]u8{0} ** block_size; + var block_len: u16 = 0; + + for (0..0x110000) |i| { + const cp: u21 = @intCast(i); + const nt = flat_map.get(cp) orelse 0; + + // Process block + block[block_len] = nt; + 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 = try std.process.argsWithAllocator(allocator); + defer args_iter.deinit(); + _ = args_iter.skip(); + const output_path = args_iter.next() orelse @panic("No output file arg!"); + + const compressor = std.compress.deflate.compressor; + var out_file = try std.fs.cwd().createFile(output_path, .{}); + defer out_file.close(); + var out_comp = try compressor(allocator, out_file.writer(), .{ .level = .best_compression }); + defer out_comp.deinit(); + const writer = out_comp.writer(); + + const endian = builtin.cpu.arch.endian(); + try writer.writeInt(u16, @intCast(stage1.items.len), endian); + for (stage1.items) |i| try writer.writeInt(u16, i, endian); + + try writer.writeInt(u16, @intCast(stage2.items.len), endian); + try writer.writeAll(stage2.items); + + try out_comp.flush(); +} diff --git a/src/NumericData.zig b/src/NumericData.zig new file mode 100644 index 0000000..baf8f11 --- /dev/null +++ b/src/NumericData.zig @@ -0,0 +1,75 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const compress = std.compress; +const mem = std.mem; +const testing = std.testing; + +allocator: mem.Allocator, +s1: []u16 = undefined, +s2: []u8 = undefined, + +const Self = @This(); + +pub fn init(allocator: mem.Allocator) !Self { + const decompressor = compress.deflate.decompressor; + const in_bytes = @embedFile("numeric"); + var in_fbs = std.io.fixedBufferStream(in_bytes); + var in_decomp = try decompressor(allocator, in_fbs.reader(), null); + defer in_decomp.deinit(); + var reader = in_decomp.reader(); + + const endian = builtin.cpu.arch.endian(); + + var self = Self{ .allocator = allocator }; + + const stage_1_len: u16 = try reader.readInt(u16, endian); + self.s1 = try allocator.alloc(u16, stage_1_len); + for (0..stage_1_len) |i| self.s1[i] = try reader.readInt(u16, endian); + + const stage_2_len: u16 = try reader.readInt(u16, endian); + self.s2 = try allocator.alloc(u8, stage_2_len); + _ = try reader.readAll(self.s2); + + return self; +} + +pub fn deinit(self: *Self) void { + self.allocator.free(self.s1); + self.allocator.free(self.s2); +} + +/// True if `cp` is any numeric type. +pub fn isNumber(self: Self, cp: u21) bool { + return self.isNumeric(cp) or self.isDigit(cp) or self.isDecimal(cp); +} + +/// True if `cp` is numeric. +pub inline fn isNumeric(self: Self, cp: u21) bool { + return self.s2[self.s1[cp >> 8] + (cp & 0xff)] & 1 == 1; +} + +/// True if `cp` is a digit. +pub inline fn isDigit(self: Self, cp: u21) bool { + return self.s2[self.s1[cp >> 8] + (cp & 0xff)] & 2 == 2; +} + +/// True if `cp` is decimal. +pub inline fn isDecimal(self: Self, cp: u21) bool { + return self.s2[self.s1[cp >> 8] + (cp & 0xff)] & 4 == 4; +} + +test "isDecimal" { + var self = try init(testing.allocator); + defer self.deinit(); + + try testing.expect(self.isNumber('\u{277f}')); + try testing.expect(self.isNumber('3')); + try testing.expect(self.isNumeric('\u{277f}')); + try testing.expect(self.isDigit('\u{2070}')); + try testing.expect(self.isDecimal('3')); + + try testing.expect(!self.isNumber('z')); + try testing.expect(!self.isNumeric('1')); + try testing.expect(!self.isDigit('2')); + try testing.expect(!self.isDecimal('g')); +} diff --git a/src/main.zig b/src/main.zig index 0b0d550..52d823c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -11,18 +11,20 @@ const std = @import("std"); // const strWidth = @import("display_width").strWidth; // const CodePointIterator = @import("ziglyph").CodePointIterator; -// const CodePointIterator = @import("code_point").Iterator; +const CodePointIterator = @import("code_point").Iterator; // const ascii = @import("ascii"); // const ascii = std.ascii; // const Normalize = @import("ziglyph").Normalizer; -const Normalize = @import("Normalize"); +// const Normalize = @import("Normalize"); // const CaseFold = @import("CaseFold"); // const GenCatData = @import("GenCatData"); +const NumericData = @import("NumericData"); + pub fn main() !void { var args_iter = std.process.args(); _ = args_iter.skip(); @@ -39,9 +41,9 @@ pub fn main() !void { ); defer allocator.free(input); - var norm_data = try Normalize.NormData.init(allocator); - defer norm_data.deinit(); - var norm = Normalize{ .norm_data = &norm_data }; + // var norm_data = try Normalize.NormData.init(allocator); + // defer norm_data.deinit(); + // var norm = Normalize{ .norm_data = &norm_data }; // var norm = try Normalize.init(allocator); // defer norm.deinit(); @@ -52,10 +54,13 @@ pub fn main() !void { // defer fold_data.deinit(); // var caser = CaseFold{ .fold_data = &fold_data }; + var num_data = try NumericData.init(allocator); + defer num_data.deinit(); + // var iter = GraphemeIterator.init(input, &data); // defer iter.deinit(); - // var iter = CodePointIterator{ .bytes = input }; - var iter = std.mem.splitScalar(u8, input, '\n'); + var iter = CodePointIterator{ .bytes = input }; + // var iter = std.mem.splitScalar(u8, input, '\n'); var result: usize = 0; // var prev_line: []const u8 = ""; @@ -65,11 +70,11 @@ pub fn main() !void { // while (iter.next()) |cp| result += codePointWidth(@intCast(cp.code)); // while (iter.next()) |_| result += 1; // while (iter.next()) |line| result += strWidth(line, &data); - while (iter.next()) |line| { - const nfc = try norm.nfc(allocator, line); - result += nfc.slice.len; - // nfc.deinit(); - } + // while (iter.next()) |line| { + // const nfc = try norm.nfc(allocator, line); + // result += nfc.slice.len; + // // nfc.deinit(); + // } // while (iter.next()) |cp| { // if (cp.code == 'É') std.debug.print("`{u}` Gc: {s}\n", .{ cp.code, @tagName(gencat_data.gc(cp.code)) }); // result += 1; @@ -80,6 +85,9 @@ pub fn main() !void { // } // prev_line = line; // } + while (iter.next()) |cp| { + if (num_data.isNumberic(cp)) result += 1; + } std.debug.print("result: {}, took: {}\n", .{ result, timer.lap() / std.time.ns_per_ms }); } -- cgit v1.2.3