aboutsummaryrefslogtreecommitdiff
path: root/langs/pinyin.c
diff options
context:
space:
mode:
Diffstat (limited to 'langs/pinyin.c')
-rw-r--r--langs/pinyin.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/langs/pinyin.c b/langs/pinyin.c
new file mode 100644
index 0000000..c6d7f29
--- /dev/null
+++ b/langs/pinyin.c
@@ -0,0 +1,74 @@
+#include <ctype.h>
+#include "lang.h"
+
+/* Longest first, so "zh" is tried before "z". */
+static const char *INITIALS[] = {
+ "zh", "ch", "sh",
+ "b", "p", "m", "f", "d", "t", "n", "l", "g", "k", "h",
+ "j", "q", "x", "r", "z", "c", "s", "y", "w",
+ NULL
+};
+
+static int is_digit(char c) { return c >= '0' && c <= '9'; }
+
+/* Length of the initial consonant at the start of the syllable, 0 if none. */
+static size_t initial_len(Span w) {
+ for (size_t i = 0; INITIALS[i]; i++) {
+ size_t n = strlen(INITIALS[i]);
+ if (w.len < n) continue;
+ size_t k = 0;
+ while (k < n && tolower((unsigned char)w.ptr[k]) == INITIALS[i][k]) k++;
+ if (k == n) return n;
+ }
+ return 0;
+}
+
+static size_t find_digit(Span w) {
+ for (size_t i = 0; i < w.len; i++)
+ if (is_digit(w.ptr[i])) return i;
+ return w.len; /* w.len means "none" */
+}
+
+/* "chu1" -> "u1ch", "yao4" -> "ao4y". Syllables with no initial ("an4") or no
+ tone digit ("de") pass through, because decrypt couldn't find the split. */
+static int encrypt_word(SB *sb, Span w) {
+ size_t p = initial_len(w);
+ if (p == 0 || find_digit(w) == w.len)
+ return sb_append_n(sb, w.ptr, w.len);
+
+ if (sb_append_n(sb, w.ptr + p, w.len - p) != 0) return -1;
+ return sb_append_n(sb, w.ptr, p);
+}
+
+/* "u1ch" -> "chu1": everything after the first digit moves back to the front. */
+static int decrypt_word(SB *sb, Span t) {
+ size_t d = find_digit(t);
+ if (d == t.len)
+ return sb_append_n(sb, t.ptr, t.len);
+
+ if (sb_append_n(sb, t.ptr + d + 1, t.len - d - 1) != 0) return -1;
+ return sb_append_n(sb, t.ptr, d + 1);
+}
+
+/* Split on `from`, run `fn` on each piece, join with `to`. */
+static char *translate(const char *input, char from, char to,
+ int (*fn)(SB *, Span)) {
+ Span *parts = NULL;
+ size_t n = split_spans(input, from, &parts);
+ if (n == 0) return NULL;
+
+ SB sb;
+ sb_init(&sb);
+ for (size_t i = 0; i < n; i++) {
+ if ((i > 0 && sb_push(&sb, to) != 0) || fn(&sb, parts[i]) != 0) {
+ sb_free(&sb);
+ free(parts);
+ return NULL;
+ }
+ }
+ free(parts);
+ return sb_take(&sb);
+}
+
+char *lang_encrypt(const char *input) { return translate(input, ' ', '.', encrypt_word); }
+char *lang_decrypt(const char *input) { return translate(input, '.', ' ', decrypt_word); }