1
0
Fork
You've already forked zg-fork
0
forked from atman/zg
zg provides Unicode text processing for Zig projects.
  • HTML 78.1%
  • Zig 21.1%
  • CSS 0.8%
Find a file
2024年10月20日 12:09:34 +00:00
bench Fixed benchmark duration printing 2024年07月18日 08:04:58 -04:00
codegen FoldData: Minimize Changes_When_Casefolded data 2024年06月27日 02:33:51 -07:00
data Cleaned up directory structure 2024年02月19日 09:11:56 -04:00
src WidthData: define error set as mem.Allocator.Error 2024年10月14日 19:45:01 -05:00
unicode_license Added benchmarks; Unicode version; Removed Ziglyph dep 2024年03月31日 11:26:14 -04:00
.gitattributes zon paths update; .gitattributes 2024年03月02日 07:39:07 -04:00
.gitignore build: use b.path everywhere 2024年06月07日 06:01:27 -05:00
build.zig build: use b.path everywhere 2024年06月07日 06:01:27 -05:00
build.zig.zon Update README 2024年06月15日 11:43:31 -04:00
LICENSE Added LICENSE 2024年03月31日 10:00:25 -04:00
norm_notes.txt Replaced ccc_map with table. 20ms faster 2024年02月20日 09:13:36 -04:00
README.md README updata to v0.13.2 2024年06月28日 07:16:29 -04:00
UNICODE_VERSION.txt Added benchmarks; Unicode version; Removed Ziglyph dep 2024年03月31日 11:26:14 -04:00

zg

zg provides Unicode text processing for Zig projects.

Unicode Version

The Unicode version supported by zg is 15.1.0.

Zig Version

The minimum Zig version required is 0.13.0 stable.

Integrating zg into your Zig Project

You first need to add zg as a dependency in your build.zig.zon file. In your Zig project's root directory, run:

zig fetch --save https://codeberg.org/dude_the_builder/zg/archive/v0.13.2.tar.gz

Then instantiate the dependency in your build.zig:

constzg=b.dependency("zg",.{});

A Modular Approach

zg is a modular library. This approach minimizes binary file size and memory requirements by only including the Unicode data required for the specified module. The following sections describe the various modules and their specific use case.

Code Points

In the code_point module, you'll find a data structure representing a single code point, CodePoint, and an Iterator to iterate over the code points in a string.

In your build.zig:

exe.root_module.addImport("code_point",zg.module("code_point"));

In your code:

constcode_point=@import("code_point");test"Code point iterator"{conststr="Hi 😊";variter=code_point.Iterator{.bytes=str};vari:usize=0;while(iter.next())|cp|:(i+=1){// The `code` field is the actual code point scalar as a `u21`.if(i==0)tryexpect(cp.code=='H');if(i==1)tryexpect(cp.code=='i');if(i==2)tryexpect(cp.code==' ');if(i==3){tryexpect(cp.code=='😊');// The `offset` field is the byte offset in the// source string.tryexpect(cp.offset==3);// The `len` field is the length in bytes of the// code point in the source string.tryexpect(cp.len==4);}}}

Grapheme Clusters

Many characters are composed from more than one code point. These are known as Grapheme Clusters and the grapheme module has a data structure to represent them, Grapheme, and an Iterator to iterate over them in a string.

In your build.zig:

exe.root_module.addImport("grapheme",zg.module("grapheme"));

In your code:

constgrapheme=@import("grapheme");test"Grapheme cluster iterator"{// we need some Unicode data to process Grapheme Clusters.constgd=trygrapheme.GraphemeData.init(allocator);defergd.deinit();conststr="He\u{301}";// Hévariter=grapheme.Iterator.init(str,&gd);vari:usize=0;while(iter.next())|gc|:(i+=1){// The `len` field is the length in bytes of the// grapheme cluster in the source string.if(i==0)tryexpect(gc.len==1);if(i==1){tryexpect(gc.len==3);// The `offset` in bytes of the grapheme cluster// in the source string.tryexpect(gc.offset==1);// The `bytes` method returns the slice of bytes// that comprise this grapheme cluster in the// source string `str`.tryexpectEqualStrings("e\u{301}",gc.bytes(str));}}}

Unicode General Categories

To detect the general category for a code point, use the GenCatData module.

In your build.zig:

exe.root_module.addImport("GenCatData",zg.module("GenCatData"));

In your code:

constGenCatData=@import("GenCatData");test"General Category"{constgcd=tryGenCatData.init(allocator);defergcd.deinit();// The `gc` method returns the abbreviated General Category.// These abbreviations and descriptive comments can be found// in the source file `src/GenCatData.zig` as en enum.tryexpect(gcd.gc('A')==.Lu);// Lu: uppercase lettertryexpect(gcd.gc('3')==.Nd);// Nd: decimal number// The following are convenience methods for groups of General// Categories. For example, all letter categories start with `L`:// Lu, Ll, Lt, Lo.tryexpect(gcd.isControl(0));tryexpect(gcd.isLetter('z'));tryexpect(gcd.isMark('\u{301}'));tryexpect(gcd.isNumber('3'));tryexpect(gcd.isPunctuation('['));tryexpect(gcd.isSeparator(' '));tryexpect(gcd.isSymbol('©'));}

Unicode Properties

You can detect common properties of a code point with the PropsData module.

In your build.zig:

exe.root_module.addImport("PropsData",zg.module("PropsData"));

In your code:

constPropsData=@import("PropsData");test"Properties"{constpd=tryPropsData.init(allocator);deferpd.deinit();// Mathematical symbols and letters.tryexpect(pd.isMath('+'));// Alphabetic only code points.tryexpect(pd.isAlphabetic('Z'));// Space, tab, and other separators.tryexpect(pd.isWhitespace(' '));// Hexadecimal digits and variations thereof.tryexpect(pd.isHexDigit('f'));tryexpect(!pd.isHexDigit('z'));// Accents, dieresis, and other combining marks.tryexpect(pd.isDiacritic('\u{301}'));// Unicode has a specification for valid identifiers like // the ones used in programming and regular expressions.tryexpect(pd.isIdStart('Z'));// Identifier start charactertryexpect(!pd.isIdStart('1'));tryexpect(pd.isIdContinue('1'));// The `X` versions add some code points that can appear after// normalizing a string.tryexpect(pd.isXidStart('\u{b33}'));// Extended identifier start charactertryexpect(pd.isXidContinue('\u{e33}'));tryexpect(!pd.isXidStart('1'));// Note surprising Unicode numeric type properties!tryexpect(pd.isNumeric('\u{277f}'));tryexpect(!pd.isNumeric('3'));// 3 is not numeric!tryexpect(pd.isDigit('\u{2070}'));tryexpect(!pd.isDigit('3'));// 3 is not a digit!tryexpect(pd.isDecimal('3'));// 3 is a decimal digit}

Letter Case Detection and Conversion

To detect and convert to and from different letter cases, use the CaseData module.

In your build.zig:

exe.root_module.addImport("CaseData",zg.module("CaseData"));

In your code:

constCaseData=@import("CaseData");test"Case"{constcd=tryCaseData.init(allocator);defercd.deinit();// Upper and lower case.tryexpect(cd.isUpper('A'));tryexpect('A'==cd.toUpper('a'));tryexpect(cd.isLower('a'));tryexpect('a'==cd.toLower('A'));// Code points that have case.tryexpect(cd.isCased('É'));tryexpect(!cd.isCased('3'));// Case detection and conversion for strings.tryexpect(cd.isUpperStr("HELLO 123!"));constucased=trycd.toUpperStr(allocator,"hello 123");deferallocator.free(ucased);tryexpectEqualStrings("HELLO 123",ucased);tryexpect(cd.isLowerStr("hello 123!"));constlcased=trycd.toLowerStr(allocator,"HELLO 123");deferallocator.free(lcased);tryexpectEqualStrings("hello 123",lcased);}

Normalization

Unicode normalization is the process of converting a string into a uniform representation that can guarantee a known structure by following a strict set of rules. There are four normalization forms:

Canonical Composition (NFC)
The most compact representation obtained by first decomposing to Canonical Decomposition and then composing to NFC.
Compatibility Composition (NFKC)
The most comprehensive composition obtained by first decomposing to Compatibility Decomposition and then composing to NFKC.
Canonical Decomposition (NFD)
Only code points with canonical decompositions are decomposed. This is a more compact and faster decomposition but will not provide the most comprehensive normalization possible.
Compatibility Decomposition (NFKD)
The most comprehensive decomposition method where both canonical and compatibility decompositions are performed recursively.

zg has methods to produce all four normalization forms in the Normalize module.

In your build.zig:

exe.root_module.addImport("Normalize",zg.module("Normalize"));

In your code:

constNormalize=@import("Normalize");test"Normalization"{// We need lots of Unicode dta for normalization.varnorm_data:Normalize.NormData=undefined;tryNormalize.NormData.init(&norm_data,allocator);defernorm_data.deinit();// The `Normalize` structure takes a pointer to the data.constn=Normalize{.norm_data=&norm_data};// NFC: Canonical compositionconstnfc_result=tryn.nfc(allocator,"Complex char: \u{3D2}\u{301}");defernfc_result.deinit();tryexpectEqualStrings("Complex char: \u{3D3}",nfc_result.slice);// NFKC: Compatibility compositionconstnfkc_result=tryn.nfkc(allocator,"Complex char: \u{03A5}\u{0301}");defernfkc_result.deinit();tryexpectEqualStrings("Complex char: \u{038E}",nfkc_result.slice);// NFD: Canonical decompositionconstnfd_result=tryn.nfd(allocator,"Héllo World! \u{3d3}");defernfd_result.deinit();tryexpectEqualStrings("He\u{301}llo World! \u{3d2}\u{301}",nfd_result.slice);// NFKD: Compatibility decompositionconstnfkd_result=tryn.nfkd(allocator,"Héllo World! \u{3d3}");defernfkd_result.deinit();tryexpectEqualStrings("He\u{301}llo World! \u{3a5}\u{301}",nfkd_result.slice);// Test for equality of two strings after normalizing to NFC.tryexpect(tryn.eql(allocator,"foé","foe\u{0301}"));tryexpect(tryn.eql(allocator,"foΎ","fo\u{03D2}\u{0301}"));}

Caseless Matching via Case Folding

Unicode provides a more efficient way of comparing strings while ignoring letter case differences: case folding. When you case fold a string, it's converted into a normalized case form suitable for efficient matching. Use the CaseFold module for this.

In your build.zig:

exe.root_module.addImport("Normalize",zg.module("Normalize"));exe.root_module.addImport("CaseFold",zg.module("CaseFold"));

In your code:

constNormalize=@import("Normalize");constCaseFold=@import("CaseFold");test"Caseless matching"{// We need to normalize during the matching process.varnorm_data:Normalize.NormData=undefined;tryNormalize.NormData.init(&norm_data,allocator);defernorm_data.deinit();constn=Normalize{.norm_data=&norm_data};// We need Unicode case fold data.constcfd=tryCaseFold.FoldData.init(allocator);defercfd.deinit();// The `CaseFold` structure takes a pointer to the data.constcf=CaseFold{.fold_data=&cfd};// `compatCaselessMatch` provides the deepest level of caseless// matching because it decomposes fully to NFKD.consta="Héllo World! \u{3d3}";constb="He\u{301}llo World! \u{3a5}\u{301}";tryexpect(trycf.compatCaselessMatch(allocator,&n,a,b));constc="He\u{301}llo World! \u{3d2}\u{301}";tryexpect(trycf.compatCaselessMatch(allocator,&n,a,c));// `canonCaselessMatch` isn't as comprehensive as `compatCaselessMatch`// because it only decomposes to NFD. Naturally, it's faster because of this.tryexpect(!trycf.canonCaselessMatch(allocator,&n,a,b));tryexpect(trycf.canonCaselessMatch(allocator,&n,a,c));}

Display Width of Characters and Strings

When displaying text with a fixed-width font on a terminal screen, it's very important to know exactly how many columns or cells each character should take. Most characters will use one column, but there are many, like emoji and East- Asian ideographs that need more space. The DisplayWidth module provides methods for this purpose. It also has methods that use the display width calculation to center, padLeft, padRight, and wrap text.

In your build.zig:

exe.root_module.addImport("DisplayWidth",zg.module("DisplayWidth"));

In your code:

constDisplayWidth=@import("DisplayWidth");test"Display width"{// We need Unicode data for display width calculation.constdwd=tryDisplayWidth.DisplayWidthData.init(allocator);deferdwd.deinit();// The `DisplayWidth` structure takes a pointer to the data.constdw=DisplayWidth{.data=&dwd};// String display widthtryexpectEqual(@as(usize,5),dw.strWidth("Hello\r\n"));tryexpectEqual(@as(usize,8),dw.strWidth("Hello 😊"));tryexpectEqual(@as(usize,8),dw.strWidth("Héllo 😊"));tryexpectEqual(@as(usize,9),dw.strWidth("Ẓ̌á̲l͔̝̞̄̑͌g̖̘̘̔̔͢͞͝o̪̔T̢̙̫̈̍͞e̬͈͕͌̏͑x̺̍ṭ̓̓ͅ"));tryexpectEqual(@as(usize,17),dw.strWidth("슬라바 우크라이나"));// Centering textconstcentered=trydw.center(allocator,"w😊w",10,"-");deferallocator.free(centered);tryexpectEqualStrings("---w😊w---",centered);// Pad leftconstright_aligned=trydw.padLeft(allocator,"abc",9,"*");deferallocator.free(right_aligned);tryexpectEqualStrings("******abc",right_aligned);// Pad rightconstleft_aligned=trydw.padRight(allocator,"abc",9,"*");deferallocator.free(left_aligned);tryexpectEqualStrings("abc******",left_aligned);// Wrap textconstinput="The quick brown fox\r\njumped over the lazy dog!";constwrapped=trydw.wrap(allocator,input,10,3);deferallocator.free(wrapped);constwant=\\The quick \\brown fox \\jumped \\over the \\lazy dog!;tryexpectEqualStrings(want,wrapped);}

Scripts

Unicode categorizes code points by the Script in which they belong. A Script collects letters and other symbols that belong to a particular writing system. You can detect the Script for a code point with the ScriptsData module.

In your build.zig:

exe.root_module.addImport("ScriptsData",zg.module("ScriptsData"));

In your code:

constScriptsData=@import("ScriptsData");test"Scripts"{constsd=tryScriptsData.init(allocator);defersd.deinit();// To see the full list of Scripts, look at the// `src/ScriptsData.zig` file. They are list in an enum.tryexpect(sd.script('A')==.Latin);tryexpect(sd.script('Ω')==.Greek);tryexpect(sd.script('צ')==.Hebrew);}

Relation to Ziglyph

zg is a total re-write of some of the components of Ziglyph. The idea was to reduce binary size and improve performance. These goals were achieved by using trie-like data structures (inspired by Ghostty's implementation) instead of generated functions. Where Ziglyph uses a function call, zg uses an array lookup, which is quite faster. In addition, all these data structures in zg are loaded at runtime from compressed versions in the binary. This allows for smaller binary sizes at the expense of increased memory footprint at runtime.

Benchmarks demonstrate the above stated goals have been met:

Binary sizes =======
149K ziglyph_case
87K zg_case
275K ziglyph_caseless
168K zg_caseless
68K ziglyph_codepoint
68K zg_codepoint
101K ziglyph_grapheme
86K zg_grapheme
185K ziglyph_normalizer
152K zg_normalize
101K ziglyph_width
86K zg_width
Benchmarks ==========
Ziglyph toUpperStr/toLowerStr: result: 7911596, took: 80
Ziglyph isUpperStr/isLowerStr: result: 110959, took: 17
zg toUpperStr/toLowerStr: result: 7911596, took: 62
zg isUpperStr/isLowerStr: result: 110959, took: 7
Ziglyph Normalizer.eqlCaseless: result: 625, took: 500
zg CaseFold.canonCaselessMatch: result: 625, took: 385
zg CaseFold.compatCaselessMatch: result: 625, took: 593
Ziglyph CodePointIterator: result: 3769314, took: 2
zg CodePointIterator: result: 3769314, took: 3
Ziglyph GraphemeIterator: result: 3691806, took: 48
zg GraphemeIterator: result: 3691806, took: 16
Ziglyph Normalizer.nfkc: result: 3934162, took: 416
zg Normalize.nfkc: result: 3934162, took: 182
Ziglyph Normalizer.nfc: result: 3955798, took: 57
zg Normalize.nfc: result: 3955798, took: 28
Ziglyph Normalizer.nfkd: result: 4006398, took: 172
zg Normalize.nfkd: result: 4006398, took: 104
Ziglyph Normalizer.nfd: result: 4028034, took: 169
zg Normalize.nfd: result: 4028034, took: 104
Ziglyph Normalizer.eql: result: 625, took: 337
Zg Normalize.eql: result: 625, took: 53
Ziglyph display_width.strWidth: result: 3700914, took: 71
zg DisplayWidth.strWidth: result: 3700914, took: 24

These results were obtained on an M1 Mac with 16 GiB of RAM.

In contrast to Ziglyph, zg does not have:

  • Word segmentation
  • Sentence segmentation
  • Collation

It's possible that any missing functionality will be added in future versions, but only if enough demand is present in the community.