1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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); }
|