nickname.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2015 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 precis
  5. import (
  6. "unicode"
  7. "unicode/utf8"
  8. "golang.org/x/text/transform"
  9. )
  10. type nickAdditionalMapping struct {
  11. // TODO: This transformer needs to be stateless somehow…
  12. notStart bool
  13. prevSpace bool
  14. }
  15. func (t *nickAdditionalMapping) Reset() {
  16. t.prevSpace = false
  17. t.notStart = false
  18. }
  19. func (t *nickAdditionalMapping) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
  20. // RFC 7700 §2.1. Rules
  21. //
  22. // 2. Additional Mapping Rule: The additional mapping rule consists of
  23. // the following sub-rules.
  24. //
  25. // 1. Any instances of non-ASCII space MUST be mapped to ASCII
  26. // space (U+0020); a non-ASCII space is any Unicode code point
  27. // having a general category of "Zs", naturally with the
  28. // exception of U+0020.
  29. //
  30. // 2. Any instances of the ASCII space character at the beginning
  31. // or end of a nickname MUST be removed (e.g., "stpeter " is
  32. // mapped to "stpeter").
  33. //
  34. // 3. Interior sequences of more than one ASCII space character
  35. // MUST be mapped to a single ASCII space character (e.g.,
  36. // "St Peter" is mapped to "St Peter").
  37. for nSrc < len(src) {
  38. r, size := utf8.DecodeRune(src[nSrc:])
  39. if size == 0 { // Incomplete UTF-8 encoding
  40. if !atEOF {
  41. return nDst, nSrc, transform.ErrShortSrc
  42. }
  43. size = 1
  44. }
  45. if unicode.Is(unicode.Zs, r) {
  46. t.prevSpace = true
  47. } else {
  48. if t.prevSpace && t.notStart {
  49. dst[nDst] = ' '
  50. nDst += 1
  51. }
  52. if size != copy(dst[nDst:], src[nSrc:nSrc+size]) {
  53. nDst += size
  54. return nDst, nSrc, transform.ErrShortDst
  55. }
  56. nDst += size
  57. t.prevSpace = false
  58. t.notStart = true
  59. }
  60. nSrc += size
  61. }
  62. return nDst, nSrc, nil
  63. }