You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

escape.go 996B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package util
  2. import "bytes"
  3. // Markdown escape map (ASCII)
  4. // Inspired by https://github.com/golang-commonmark/markdown/blob/master/escape.go
  5. type EscapeMap [2]uint64
  6. func (e *EscapeMap) Get(index uint) bool {
  7. if index >= 128 { return false }
  8. high, low := index / 64, index % 64
  9. return e[high] & (1 << low) != 0
  10. }
  11. func (e *EscapeMap) Set(index uint, x bool) {
  12. if index >= 128 { return }
  13. high, low := index / 64, index % 64
  14. if x {
  15. e[high] = e[high] | 1 << low
  16. } else {
  17. e[high] = e[high] &^ 1 << low
  18. }
  19. }
  20. func (e EscapeMap) ToBuffer(src string, dest *bytes.Buffer) (err error) {
  21. for _, char := range src {
  22. if char < 0x80 && e.Get(uint(char)) {
  23. // Write backslash + char
  24. _, err = dest.Write([]byte{0x5c, byte(char)})
  25. } else {
  26. _, err = dest.WriteRune(char)
  27. }
  28. }
  29. return
  30. }
  31. func (e EscapeMap) ToString(src string) (string, error) {
  32. var buffer bytes.Buffer
  33. err := e.ToBuffer(src, &buffer)
  34. if err != nil {
  35. return "", err
  36. } else {
  37. return buffer.String(), nil
  38. }
  39. }