Skip to content

Commit 77dd184

Browse files
committed
FFstrbuf: add function ffStrbufAppendUtf32CodePoint
1 parent 5bb6e22 commit 77dd184

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

src/util/FFstrbuf.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,3 +682,35 @@ bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const
682682

683683
return false;
684684
}
685+
686+
int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint)
687+
{
688+
if (codepoint <= 0x7F) {
689+
ffStrbufAppendC(strbuf, (char)codepoint);
690+
return 1;
691+
} else if (codepoint <= 0x7FF) {
692+
ffStrbufAppendNS(strbuf, 2, (char[]){
693+
(char) (0xC0 | (codepoint >> 6)),
694+
(char) (0x80 | (codepoint & 0x3F))
695+
});
696+
return 2;
697+
} else if (codepoint <= 0xFFFF) {
698+
ffStrbufAppendNS(strbuf, 3, (char[]){
699+
(char) (0xE0 | (codepoint >> 12)),
700+
(char) (0x80 | ((codepoint >> 6) & 0x3F)),
701+
(char) (0x80 | (codepoint & 0x3F))
702+
});
703+
return 3;
704+
} else if (codepoint <= 0x10FFFF) {
705+
ffStrbufAppendNS(strbuf, 4, (char[]){
706+
(char) (0xF0 | (codepoint >> 18)),
707+
(char) (0x80 | ((codepoint >> 12) & 0x3F)),
708+
(char) (0x80 | ((codepoint >> 6) & 0x3F)),
709+
(char) (0x80 | (codepoint & 0x3F))
710+
});
711+
return 4;
712+
}
713+
714+
ffStrbufAppendS(strbuf, "�"); // U+FFFD REPLACEMENT CHARACTER
715+
return 1;
716+
}

src/util/FFstrbuf.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ void ffStrbufGetlineRestore(char** lineptr, size_t* n, FFstrbuf* buffer);
9696
bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf);
9797
bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
9898

99+
int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint);
100+
99101
FF_C_NODISCARD static inline FFstrbuf ffStrbufCreateA(uint32_t allocate)
100102
{
101103
FFstrbuf strbuf;

tests/strbuf.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,15 @@ int main(void)
711711
ffStrbufDestroy(&strbuf);
712712
}
713713

714+
{
715+
ffStrbufAppendUtf32CodePoint(&strbuf, 0x6587);
716+
ffStrbufAppendUtf32CodePoint(&strbuf, 0x6cc9);
717+
ffStrbufAppendUtf32CodePoint(&strbuf, 0x9a7f);
718+
VERIFY(ffStrbufEqualS(&strbuf, u8"文泉驿"));
719+
720+
ffStrbufDestroy(&strbuf);
721+
}
722+
714723
//Success
715724
puts("\e[32mAll tests passed!" FASTFETCH_TEXT_MODIFIER_RESET);
716725
}

0 commit comments

Comments
 (0)