string_unicode.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. package goja
  2. import (
  3. "errors"
  4. "fmt"
  5. "hash/maphash"
  6. "io"
  7. "math"
  8. "reflect"
  9. "strings"
  10. "unicode/utf16"
  11. "unicode/utf8"
  12. "github.com/dop251/goja/parser"
  13. "github.com/dop251/goja/unistring"
  14. "golang.org/x/text/cases"
  15. "golang.org/x/text/language"
  16. )
  17. type unicodeString []uint16
  18. type unicodeRuneReader struct {
  19. s unicodeString
  20. pos int
  21. }
  22. type runeReaderReplace struct {
  23. wrapped io.RuneReader
  24. }
  25. type unicodeStringBuilder struct {
  26. buf []uint16
  27. unicode bool
  28. }
  29. var (
  30. InvalidRuneError = errors.New("Invalid rune")
  31. )
  32. func (rr runeReaderReplace) ReadRune() (r rune, size int, err error) {
  33. r, size, err = rr.wrapped.ReadRune()
  34. if err == InvalidRuneError {
  35. err = nil
  36. r = utf8.RuneError
  37. }
  38. return
  39. }
  40. func (rr *unicodeRuneReader) ReadRune() (r rune, size int, err error) {
  41. if rr.pos < len(rr.s) {
  42. r = rune(rr.s[rr.pos])
  43. size++
  44. rr.pos++
  45. if isUTF16FirstSurrogate(r) {
  46. if rr.pos < len(rr.s) {
  47. second := rune(rr.s[rr.pos])
  48. if isUTF16SecondSurrogate(second) {
  49. r = utf16.DecodeRune(r, second)
  50. size++
  51. rr.pos++
  52. } else {
  53. err = InvalidRuneError
  54. }
  55. } else {
  56. err = InvalidRuneError
  57. }
  58. } else if isUTF16SecondSurrogate(r) {
  59. err = InvalidRuneError
  60. }
  61. } else {
  62. err = io.EOF
  63. }
  64. return
  65. }
  66. func (b *unicodeStringBuilder) grow(n int) {
  67. if cap(b.buf)-len(b.buf) < n {
  68. buf := make([]uint16, len(b.buf), 2*cap(b.buf)+n)
  69. copy(buf, b.buf)
  70. b.buf = buf
  71. }
  72. }
  73. func (b *unicodeStringBuilder) Grow(n int) {
  74. b.grow(n + 1)
  75. }
  76. func (b *unicodeStringBuilder) ensureStarted(initialSize int) {
  77. b.grow(len(b.buf) + initialSize + 1)
  78. if len(b.buf) == 0 {
  79. b.buf = append(b.buf, unistring.BOM)
  80. }
  81. }
  82. func (b *unicodeStringBuilder) writeString(s valueString) {
  83. b.ensureStarted(int(s.length()))
  84. switch s := s.(type) {
  85. case unicodeString:
  86. b.buf = append(b.buf, s[1:]...)
  87. b.unicode = true
  88. case asciiString:
  89. for i := 0; i < len(s); i++ {
  90. b.buf = append(b.buf, uint16(s[i]))
  91. }
  92. default:
  93. panic(fmt.Errorf("unsupported string type: %T", s))
  94. }
  95. }
  96. func (b *unicodeStringBuilder) string() valueString {
  97. if b.unicode {
  98. return unicodeString(b.buf)
  99. }
  100. if len(b.buf) == 0 {
  101. return stringEmpty
  102. }
  103. buf := make([]byte, 0, len(b.buf)-1)
  104. for _, c := range b.buf[1:] {
  105. buf = append(buf, byte(c))
  106. }
  107. return asciiString(buf)
  108. }
  109. func (b *unicodeStringBuilder) writeRune(r rune) {
  110. if r <= 0xFFFF {
  111. b.ensureStarted(1)
  112. b.buf = append(b.buf, uint16(r))
  113. b.unicode = r >= utf8.RuneSelf
  114. } else {
  115. b.ensureStarted(2)
  116. first, second := utf16.EncodeRune(r)
  117. b.buf = append(b.buf, uint16(first), uint16(second))
  118. b.unicode = true
  119. }
  120. }
  121. func (b *unicodeStringBuilder) writeASCII(bytes []byte) {
  122. b.ensureStarted(len(bytes))
  123. for _, c := range bytes {
  124. b.buf = append(b.buf, uint16(c))
  125. }
  126. }
  127. func (s unicodeString) reader(start int) io.RuneReader {
  128. return &unicodeRuneReader{
  129. s: s[start+1:],
  130. }
  131. }
  132. func (s unicodeString) ToInteger() int64 {
  133. return 0
  134. }
  135. func (s unicodeString) toString() valueString {
  136. return s
  137. }
  138. func (s unicodeString) ToString() Value {
  139. return s
  140. }
  141. func (s unicodeString) ToFloat() float64 {
  142. return math.NaN()
  143. }
  144. func (s unicodeString) ToBoolean() bool {
  145. return len(s) > 0
  146. }
  147. func (s unicodeString) toTrimmedUTF8() string {
  148. if len(s) == 0 {
  149. return ""
  150. }
  151. return strings.Trim(s.String(), parser.WhitespaceChars)
  152. }
  153. func (s unicodeString) ToNumber() Value {
  154. return asciiString(s.toTrimmedUTF8()).ToNumber()
  155. }
  156. func (s unicodeString) ToObject(r *Runtime) *Object {
  157. return r._newString(s, r.global.StringPrototype)
  158. }
  159. func (s unicodeString) equals(other unicodeString) bool {
  160. if len(s) != len(other) {
  161. return false
  162. }
  163. for i, r := range s {
  164. if r != other[i] {
  165. return false
  166. }
  167. }
  168. return true
  169. }
  170. func (s unicodeString) SameAs(other Value) bool {
  171. if otherStr, ok := other.(unicodeString); ok {
  172. return s.equals(otherStr)
  173. }
  174. return false
  175. }
  176. func (s unicodeString) Equals(other Value) bool {
  177. if s.SameAs(other) {
  178. return true
  179. }
  180. if o, ok := other.(*Object); ok {
  181. return s.Equals(o.toPrimitive())
  182. }
  183. return false
  184. }
  185. func (s unicodeString) StrictEquals(other Value) bool {
  186. return s.SameAs(other)
  187. }
  188. func (s unicodeString) baseObject(r *Runtime) *Object {
  189. ss := r.stringSingleton
  190. ss.value = s
  191. ss.setLength()
  192. return ss.val
  193. }
  194. func (s unicodeString) charAt(idx int) rune {
  195. return rune(s[idx+1])
  196. }
  197. func (s unicodeString) length() int {
  198. return len(s) - 1
  199. }
  200. func (s unicodeString) concat(other valueString) valueString {
  201. switch other := other.(type) {
  202. case unicodeString:
  203. b := make(unicodeString, len(s)+len(other)-1)
  204. copy(b, s)
  205. copy(b[len(s):], other[1:])
  206. return b
  207. case asciiString:
  208. b := make([]uint16, len(s)+len(other))
  209. copy(b, s)
  210. b1 := b[len(s):]
  211. for i := 0; i < len(other); i++ {
  212. b1[i] = uint16(other[i])
  213. }
  214. return unicodeString(b)
  215. default:
  216. panic(fmt.Errorf("Unknown string type: %T", other))
  217. }
  218. }
  219. func (s unicodeString) substring(start, end int) valueString {
  220. ss := s[start+1 : end+1]
  221. for _, c := range ss {
  222. if c >= utf8.RuneSelf {
  223. b := make(unicodeString, end-start+1)
  224. b[0] = unistring.BOM
  225. copy(b[1:], ss)
  226. return b
  227. }
  228. }
  229. as := make([]byte, end-start)
  230. for i, c := range ss {
  231. as[i] = byte(c)
  232. }
  233. return asciiString(as)
  234. }
  235. func (s unicodeString) String() string {
  236. return string(utf16.Decode(s[1:]))
  237. }
  238. func (s unicodeString) compareTo(other valueString) int {
  239. return strings.Compare(s.String(), other.String())
  240. }
  241. func (s unicodeString) index(substr valueString, start int) int {
  242. var ss []uint16
  243. switch substr := substr.(type) {
  244. case unicodeString:
  245. ss = substr[1:]
  246. case asciiString:
  247. ss = make([]uint16, len(substr))
  248. for i := 0; i < len(substr); i++ {
  249. ss[i] = uint16(substr[i])
  250. }
  251. default:
  252. panic(fmt.Errorf("unknown string type: %T", substr))
  253. }
  254. s1 := s[1:]
  255. // TODO: optimise
  256. end := len(s1) - len(ss)
  257. for start <= end {
  258. for i := 0; i < len(ss); i++ {
  259. if s1[start+i] != ss[i] {
  260. goto nomatch
  261. }
  262. }
  263. return start
  264. nomatch:
  265. start++
  266. }
  267. return -1
  268. }
  269. func (s unicodeString) lastIndex(substr valueString, start int) int {
  270. var ss []uint16
  271. switch substr := substr.(type) {
  272. case unicodeString:
  273. ss = substr[1:]
  274. case asciiString:
  275. ss = make([]uint16, len(substr))
  276. for i := 0; i < len(substr); i++ {
  277. ss[i] = uint16(substr[i])
  278. }
  279. default:
  280. panic(fmt.Errorf("Unknown string type: %T", substr))
  281. }
  282. s1 := s[1:]
  283. if maxStart := len(s1) - len(ss); start > maxStart {
  284. start = maxStart
  285. }
  286. // TODO: optimise
  287. for start >= 0 {
  288. for i := 0; i < len(ss); i++ {
  289. if s1[start+i] != ss[i] {
  290. goto nomatch
  291. }
  292. }
  293. return start
  294. nomatch:
  295. start--
  296. }
  297. return -1
  298. }
  299. func unicodeStringFromRunes(r []rune) unicodeString {
  300. return unistring.NewFromRunes(r).AsUtf16()
  301. }
  302. func (s unicodeString) toLower() valueString {
  303. caser := cases.Lower(language.Und)
  304. r := []rune(caser.String(s.String()))
  305. // Workaround
  306. ascii := true
  307. for i := 0; i < len(r)-1; i++ {
  308. if (i == 0 || r[i-1] != 0x3b1) && r[i] == 0x345 && r[i+1] == 0x3c2 {
  309. i++
  310. r[i] = 0x3c3
  311. }
  312. if r[i] >= utf8.RuneSelf {
  313. ascii = false
  314. }
  315. }
  316. if ascii {
  317. ascii = r[len(r)-1] < utf8.RuneSelf
  318. }
  319. if ascii {
  320. return asciiString(r)
  321. }
  322. return unicodeStringFromRunes(r)
  323. }
  324. func (s unicodeString) toUpper() valueString {
  325. caser := cases.Upper(language.Und)
  326. return newStringValue(caser.String(s.String()))
  327. }
  328. func (s unicodeString) Export() interface{} {
  329. return s.String()
  330. }
  331. func (s unicodeString) ExportType() reflect.Type {
  332. return reflectTypeString
  333. }
  334. func (s unicodeString) hash(hash *maphash.Hash) uint64 {
  335. _, _ = hash.WriteString(string(unistring.FromUtf16(s)))
  336. h := hash.Sum64()
  337. hash.Reset()
  338. return h
  339. }
  340. func (s unicodeString) string() unistring.String {
  341. return unistring.FromUtf16(s)
  342. }