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.

breakwriter.go 852B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package charset
  5. import (
  6. "bytes"
  7. "io"
  8. )
  9. // BreakWriter wraps an io.Writer to always write '\n' as '<br>'
  10. type BreakWriter struct {
  11. io.Writer
  12. }
  13. // Write writes the provided byte slice transparently replacing '\n' with '<br>'
  14. func (b *BreakWriter) Write(bs []byte) (n int, err error) {
  15. pos := 0
  16. for pos < len(bs) {
  17. idx := bytes.IndexByte(bs[pos:], '\n')
  18. if idx < 0 {
  19. wn, err := b.Writer.Write(bs[pos:])
  20. return n + wn, err
  21. }
  22. if idx > 0 {
  23. wn, err := b.Writer.Write(bs[pos : pos+idx])
  24. n += wn
  25. if err != nil {
  26. return n, err
  27. }
  28. }
  29. if _, err = b.Writer.Write([]byte("<br>")); err != nil {
  30. return n, err
  31. }
  32. pos += idx + 1
  33. n++
  34. }
  35. return n, err
  36. }