composition.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package norm
  5. import "unicode/utf8"
  6. const (
  7. maxNonStarters = 30
  8. // The maximum number of characters needed for a buffer is
  9. // maxNonStarters + 1 for the starter + 1 for the GCJ
  10. maxBufferSize = maxNonStarters + 2
  11. maxNFCExpansion = 3 // NFC(0x1D160)
  12. maxNFKCExpansion = 18 // NFKC(0xFDFA)
  13. maxByteBufferSize = utf8.UTFMax * maxBufferSize // 128
  14. )
  15. // ssState is used for reporting the segment state after inserting a rune.
  16. // It is returned by streamSafe.next.
  17. type ssState int
  18. const (
  19. // Indicates a rune was successfully added to the segment.
  20. ssSuccess ssState = iota
  21. // Indicates a rune starts a new segment and should not be added.
  22. ssStarter
  23. // Indicates a rune caused a segment overflow and a CGJ should be inserted.
  24. ssOverflow
  25. )
  26. // streamSafe implements the policy of when a CGJ should be inserted.
  27. type streamSafe uint8
  28. // mkStreamSafe is a shorthand for declaring a streamSafe var and calling
  29. // first on it.
  30. func mkStreamSafe(p Properties) streamSafe {
  31. return streamSafe(p.nTrailingNonStarters())
  32. }
  33. // first inserts the first rune of a segment.
  34. func (ss *streamSafe) first(p Properties) {
  35. if *ss != 0 {
  36. panic("!= 0")
  37. }
  38. *ss = streamSafe(p.nTrailingNonStarters())
  39. }
  40. // insert returns a ssState value to indicate whether a rune represented by p
  41. // can be inserted.
  42. func (ss *streamSafe) next(p Properties) ssState {
  43. if *ss > maxNonStarters {
  44. panic("streamSafe was not reset")
  45. }
  46. n := p.nLeadingNonStarters()
  47. if *ss += streamSafe(n); *ss > maxNonStarters {
  48. *ss = 0
  49. return ssOverflow
  50. }
  51. // The Stream-Safe Text Processing prescribes that the counting can stop
  52. // as soon as a starter is encountered. However, there are some starters,
  53. // like Jamo V and T, that can combine with other runes, leaving their
  54. // successive non-starters appended to the previous, possibly causing an
  55. // overflow. We will therefore consider any rune with a non-zero nLead to
  56. // be a non-starter. Note that it always hold that if nLead > 0 then
  57. // nLead == nTrail.
  58. if n == 0 {
  59. *ss = 0
  60. return ssStarter
  61. }
  62. return ssSuccess
  63. }
  64. // backwards is used for checking for overflow and segment starts
  65. // when traversing a string backwards. Users do not need to call first
  66. // for the first rune. The state of the streamSafe retains the count of
  67. // the non-starters loaded.
  68. func (ss *streamSafe) backwards(p Properties) ssState {
  69. if *ss > maxNonStarters {
  70. panic("streamSafe was not reset")
  71. }
  72. c := *ss + streamSafe(p.nTrailingNonStarters())
  73. if c > maxNonStarters {
  74. return ssOverflow
  75. }
  76. *ss = c
  77. if p.nLeadingNonStarters() == 0 {
  78. return ssStarter
  79. }
  80. return ssSuccess
  81. }
  82. func (ss streamSafe) isMax() bool {
  83. return ss == maxNonStarters
  84. }
  85. // GraphemeJoiner is inserted after maxNonStarters non-starter runes.
  86. const GraphemeJoiner = "\u034F"
  87. // reorderBuffer is used to normalize a single segment. Characters inserted with
  88. // insert are decomposed and reordered based on CCC. The compose method can
  89. // be used to recombine characters. Note that the byte buffer does not hold
  90. // the UTF-8 characters in order. Only the rune array is maintained in sorted
  91. // order. flush writes the resulting segment to a byte array.
  92. type reorderBuffer struct {
  93. rune [maxBufferSize]Properties // Per character info.
  94. byte [maxByteBufferSize]byte // UTF-8 buffer. Referenced by runeInfo.pos.
  95. nbyte uint8 // Number or bytes.
  96. ss streamSafe // For limiting length of non-starter sequence.
  97. nrune int // Number of runeInfos.
  98. f formInfo
  99. src input
  100. nsrc int
  101. tmpBytes input
  102. out []byte
  103. flushF func(*reorderBuffer) bool
  104. }
  105. func (rb *reorderBuffer) init(f Form, src []byte) {
  106. rb.f = *formTable[f]
  107. rb.src.setBytes(src)
  108. rb.nsrc = len(src)
  109. rb.ss = 0
  110. }
  111. func (rb *reorderBuffer) initString(f Form, src string) {
  112. rb.f = *formTable[f]
  113. rb.src.setString(src)
  114. rb.nsrc = len(src)
  115. rb.ss = 0
  116. }
  117. func (rb *reorderBuffer) setFlusher(out []byte, f func(*reorderBuffer) bool) {
  118. rb.out = out
  119. rb.flushF = f
  120. }
  121. // reset discards all characters from the buffer.
  122. func (rb *reorderBuffer) reset() {
  123. rb.nrune = 0
  124. rb.nbyte = 0
  125. rb.ss = 0
  126. }
  127. func (rb *reorderBuffer) doFlush() bool {
  128. if rb.f.composing {
  129. rb.compose()
  130. }
  131. res := rb.flushF(rb)
  132. rb.reset()
  133. return res
  134. }
  135. // appendFlush appends the normalized segment to rb.out.
  136. func appendFlush(rb *reorderBuffer) bool {
  137. for i := 0; i < rb.nrune; i++ {
  138. start := rb.rune[i].pos
  139. end := start + rb.rune[i].size
  140. rb.out = append(rb.out, rb.byte[start:end]...)
  141. }
  142. return true
  143. }
  144. // flush appends the normalized segment to out and resets rb.
  145. func (rb *reorderBuffer) flush(out []byte) []byte {
  146. for i := 0; i < rb.nrune; i++ {
  147. start := rb.rune[i].pos
  148. end := start + rb.rune[i].size
  149. out = append(out, rb.byte[start:end]...)
  150. }
  151. rb.reset()
  152. return out
  153. }
  154. // flushCopy copies the normalized segment to buf and resets rb.
  155. // It returns the number of bytes written to buf.
  156. func (rb *reorderBuffer) flushCopy(buf []byte) int {
  157. p := 0
  158. for i := 0; i < rb.nrune; i++ {
  159. runep := rb.rune[i]
  160. p += copy(buf[p:], rb.byte[runep.pos:runep.pos+runep.size])
  161. }
  162. rb.reset()
  163. return p
  164. }
  165. // insertOrdered inserts a rune in the buffer, ordered by Canonical Combining Class.
  166. // It returns false if the buffer is not large enough to hold the rune.
  167. // It is used internally by insert and insertString only.
  168. func (rb *reorderBuffer) insertOrdered(info Properties) {
  169. n := rb.nrune
  170. b := rb.rune[:]
  171. cc := info.ccc
  172. if cc > 0 {
  173. // Find insertion position + move elements to make room.
  174. for ; n > 0; n-- {
  175. if b[n-1].ccc <= cc {
  176. break
  177. }
  178. b[n] = b[n-1]
  179. }
  180. }
  181. rb.nrune += 1
  182. pos := uint8(rb.nbyte)
  183. rb.nbyte += utf8.UTFMax
  184. info.pos = pos
  185. b[n] = info
  186. }
  187. // insertErr is an error code returned by insert. Using this type instead
  188. // of error improves performance up to 20% for many of the benchmarks.
  189. type insertErr int
  190. const (
  191. iSuccess insertErr = -iota
  192. iShortDst
  193. iShortSrc
  194. )
  195. // insertFlush inserts the given rune in the buffer ordered by CCC.
  196. // If a decomposition with multiple segments are encountered, they leading
  197. // ones are flushed.
  198. // It returns a non-zero error code if the rune was not inserted.
  199. func (rb *reorderBuffer) insertFlush(src input, i int, info Properties) insertErr {
  200. if rune := src.hangul(i); rune != 0 {
  201. rb.decomposeHangul(rune)
  202. return iSuccess
  203. }
  204. if info.hasDecomposition() {
  205. return rb.insertDecomposed(info.Decomposition())
  206. }
  207. rb.insertSingle(src, i, info)
  208. return iSuccess
  209. }
  210. // insertUnsafe inserts the given rune in the buffer ordered by CCC.
  211. // It is assumed there is sufficient space to hold the runes. It is the
  212. // responsibility of the caller to ensure this. This can be done by checking
  213. // the state returned by the streamSafe type.
  214. func (rb *reorderBuffer) insertUnsafe(src input, i int, info Properties) {
  215. if rune := src.hangul(i); rune != 0 {
  216. rb.decomposeHangul(rune)
  217. }
  218. if info.hasDecomposition() {
  219. // TODO: inline.
  220. rb.insertDecomposed(info.Decomposition())
  221. } else {
  222. rb.insertSingle(src, i, info)
  223. }
  224. }
  225. // insertDecomposed inserts an entry in to the reorderBuffer for each rune
  226. // in dcomp. dcomp must be a sequence of decomposed UTF-8-encoded runes.
  227. // It flushes the buffer on each new segment start.
  228. func (rb *reorderBuffer) insertDecomposed(dcomp []byte) insertErr {
  229. rb.tmpBytes.setBytes(dcomp)
  230. for i := 0; i < len(dcomp); {
  231. info := rb.f.info(rb.tmpBytes, i)
  232. if info.BoundaryBefore() && rb.nrune > 0 && !rb.doFlush() {
  233. return iShortDst
  234. }
  235. i += copy(rb.byte[rb.nbyte:], dcomp[i:i+int(info.size)])
  236. rb.insertOrdered(info)
  237. }
  238. return iSuccess
  239. }
  240. // insertSingle inserts an entry in the reorderBuffer for the rune at
  241. // position i. info is the runeInfo for the rune at position i.
  242. func (rb *reorderBuffer) insertSingle(src input, i int, info Properties) {
  243. src.copySlice(rb.byte[rb.nbyte:], i, i+int(info.size))
  244. rb.insertOrdered(info)
  245. }
  246. // insertCGJ inserts a Combining Grapheme Joiner (0x034f) into rb.
  247. func (rb *reorderBuffer) insertCGJ() {
  248. rb.insertSingle(input{str: GraphemeJoiner}, 0, Properties{size: uint8(len(GraphemeJoiner))})
  249. }
  250. // appendRune inserts a rune at the end of the buffer. It is used for Hangul.
  251. func (rb *reorderBuffer) appendRune(r rune) {
  252. bn := rb.nbyte
  253. sz := utf8.EncodeRune(rb.byte[bn:], rune(r))
  254. rb.nbyte += utf8.UTFMax
  255. rb.rune[rb.nrune] = Properties{pos: bn, size: uint8(sz)}
  256. rb.nrune++
  257. }
  258. // assignRune sets a rune at position pos. It is used for Hangul and recomposition.
  259. func (rb *reorderBuffer) assignRune(pos int, r rune) {
  260. bn := rb.rune[pos].pos
  261. sz := utf8.EncodeRune(rb.byte[bn:], rune(r))
  262. rb.rune[pos] = Properties{pos: bn, size: uint8(sz)}
  263. }
  264. // runeAt returns the rune at position n. It is used for Hangul and recomposition.
  265. func (rb *reorderBuffer) runeAt(n int) rune {
  266. inf := rb.rune[n]
  267. r, _ := utf8.DecodeRune(rb.byte[inf.pos : inf.pos+inf.size])
  268. return r
  269. }
  270. // bytesAt returns the UTF-8 encoding of the rune at position n.
  271. // It is used for Hangul and recomposition.
  272. func (rb *reorderBuffer) bytesAt(n int) []byte {
  273. inf := rb.rune[n]
  274. return rb.byte[inf.pos : int(inf.pos)+int(inf.size)]
  275. }
  276. // For Hangul we combine algorithmically, instead of using tables.
  277. const (
  278. hangulBase = 0xAC00 // UTF-8(hangulBase) -> EA B0 80
  279. hangulBase0 = 0xEA
  280. hangulBase1 = 0xB0
  281. hangulBase2 = 0x80
  282. hangulEnd = hangulBase + jamoLVTCount // UTF-8(0xD7A4) -> ED 9E A4
  283. hangulEnd0 = 0xED
  284. hangulEnd1 = 0x9E
  285. hangulEnd2 = 0xA4
  286. jamoLBase = 0x1100 // UTF-8(jamoLBase) -> E1 84 00
  287. jamoLBase0 = 0xE1
  288. jamoLBase1 = 0x84
  289. jamoLEnd = 0x1113
  290. jamoVBase = 0x1161
  291. jamoVEnd = 0x1176
  292. jamoTBase = 0x11A7
  293. jamoTEnd = 0x11C3
  294. jamoTCount = 28
  295. jamoVCount = 21
  296. jamoVTCount = 21 * 28
  297. jamoLVTCount = 19 * 21 * 28
  298. )
  299. const hangulUTF8Size = 3
  300. func isHangul(b []byte) bool {
  301. if len(b) < hangulUTF8Size {
  302. return false
  303. }
  304. b0 := b[0]
  305. if b0 < hangulBase0 {
  306. return false
  307. }
  308. b1 := b[1]
  309. switch {
  310. case b0 == hangulBase0:
  311. return b1 >= hangulBase1
  312. case b0 < hangulEnd0:
  313. return true
  314. case b0 > hangulEnd0:
  315. return false
  316. case b1 < hangulEnd1:
  317. return true
  318. }
  319. return b1 == hangulEnd1 && b[2] < hangulEnd2
  320. }
  321. func isHangulString(b string) bool {
  322. if len(b) < hangulUTF8Size {
  323. return false
  324. }
  325. b0 := b[0]
  326. if b0 < hangulBase0 {
  327. return false
  328. }
  329. b1 := b[1]
  330. switch {
  331. case b0 == hangulBase0:
  332. return b1 >= hangulBase1
  333. case b0 < hangulEnd0:
  334. return true
  335. case b0 > hangulEnd0:
  336. return false
  337. case b1 < hangulEnd1:
  338. return true
  339. }
  340. return b1 == hangulEnd1 && b[2] < hangulEnd2
  341. }
  342. // Caller must ensure len(b) >= 2.
  343. func isJamoVT(b []byte) bool {
  344. // True if (rune & 0xff00) == jamoLBase
  345. return b[0] == jamoLBase0 && (b[1]&0xFC) == jamoLBase1
  346. }
  347. func isHangulWithoutJamoT(b []byte) bool {
  348. c, _ := utf8.DecodeRune(b)
  349. c -= hangulBase
  350. return c < jamoLVTCount && c%jamoTCount == 0
  351. }
  352. // decomposeHangul writes the decomposed Hangul to buf and returns the number
  353. // of bytes written. len(buf) should be at least 9.
  354. func decomposeHangul(buf []byte, r rune) int {
  355. const JamoUTF8Len = 3
  356. r -= hangulBase
  357. x := r % jamoTCount
  358. r /= jamoTCount
  359. utf8.EncodeRune(buf, jamoLBase+r/jamoVCount)
  360. utf8.EncodeRune(buf[JamoUTF8Len:], jamoVBase+r%jamoVCount)
  361. if x != 0 {
  362. utf8.EncodeRune(buf[2*JamoUTF8Len:], jamoTBase+x)
  363. return 3 * JamoUTF8Len
  364. }
  365. return 2 * JamoUTF8Len
  366. }
  367. // decomposeHangul algorithmically decomposes a Hangul rune into
  368. // its Jamo components.
  369. // See http://unicode.org/reports/tr15/#Hangul for details on decomposing Hangul.
  370. func (rb *reorderBuffer) decomposeHangul(r rune) {
  371. r -= hangulBase
  372. x := r % jamoTCount
  373. r /= jamoTCount
  374. rb.appendRune(jamoLBase + r/jamoVCount)
  375. rb.appendRune(jamoVBase + r%jamoVCount)
  376. if x != 0 {
  377. rb.appendRune(jamoTBase + x)
  378. }
  379. }
  380. // combineHangul algorithmically combines Jamo character components into Hangul.
  381. // See http://unicode.org/reports/tr15/#Hangul for details on combining Hangul.
  382. func (rb *reorderBuffer) combineHangul(s, i, k int) {
  383. b := rb.rune[:]
  384. bn := rb.nrune
  385. for ; i < bn; i++ {
  386. cccB := b[k-1].ccc
  387. cccC := b[i].ccc
  388. if cccB == 0 {
  389. s = k - 1
  390. }
  391. if s != k-1 && cccB >= cccC {
  392. // b[i] is blocked by greater-equal cccX below it
  393. b[k] = b[i]
  394. k++
  395. } else {
  396. l := rb.runeAt(s) // also used to compare to hangulBase
  397. v := rb.runeAt(i) // also used to compare to jamoT
  398. switch {
  399. case jamoLBase <= l && l < jamoLEnd &&
  400. jamoVBase <= v && v < jamoVEnd:
  401. // 11xx plus 116x to LV
  402. rb.assignRune(s, hangulBase+
  403. (l-jamoLBase)*jamoVTCount+(v-jamoVBase)*jamoTCount)
  404. case hangulBase <= l && l < hangulEnd &&
  405. jamoTBase < v && v < jamoTEnd &&
  406. ((l-hangulBase)%jamoTCount) == 0:
  407. // ACxx plus 11Ax to LVT
  408. rb.assignRune(s, l+v-jamoTBase)
  409. default:
  410. b[k] = b[i]
  411. k++
  412. }
  413. }
  414. }
  415. rb.nrune = k
  416. }
  417. // compose recombines the runes in the buffer.
  418. // It should only be used to recompose a single segment, as it will not
  419. // handle alternations between Hangul and non-Hangul characters correctly.
  420. func (rb *reorderBuffer) compose() {
  421. // UAX #15, section X5 , including Corrigendum #5
  422. // "In any character sequence beginning with starter S, a character C is
  423. // blocked from S if and only if there is some character B between S
  424. // and C, and either B is a starter or it has the same or higher
  425. // combining class as C."
  426. bn := rb.nrune
  427. if bn == 0 {
  428. return
  429. }
  430. k := 1
  431. b := rb.rune[:]
  432. for s, i := 0, 1; i < bn; i++ {
  433. if isJamoVT(rb.bytesAt(i)) {
  434. // Redo from start in Hangul mode. Necessary to support
  435. // U+320E..U+321E in NFKC mode.
  436. rb.combineHangul(s, i, k)
  437. return
  438. }
  439. ii := b[i]
  440. // We can only use combineForward as a filter if we later
  441. // get the info for the combined character. This is more
  442. // expensive than using the filter. Using combinesBackward()
  443. // is safe.
  444. if ii.combinesBackward() {
  445. cccB := b[k-1].ccc
  446. cccC := ii.ccc
  447. blocked := false // b[i] blocked by starter or greater or equal CCC?
  448. if cccB == 0 {
  449. s = k - 1
  450. } else {
  451. blocked = s != k-1 && cccB >= cccC
  452. }
  453. if !blocked {
  454. combined := combine(rb.runeAt(s), rb.runeAt(i))
  455. if combined != 0 {
  456. rb.assignRune(s, combined)
  457. continue
  458. }
  459. }
  460. }
  461. b[k] = b[i]
  462. k++
  463. }
  464. rb.nrune = k
  465. }