File: normalise.go

package info (click to toggle)
golang-github-donovanhide-eventsource 0.0~git20210830.c590279-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, experimental, forky, sid, trixie
  • size: 132 kB
  • sloc: makefile: 2
file content (35 lines) | stat: -rw-r--r-- 603 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package eventsource

import (
	"io"
)

// A reader which normalises line endings
// "/r" and "/r/n" are converted to "/n"
type normaliser struct {
	r        io.Reader
	lastChar byte
}

func newNormaliser(r io.Reader) *normaliser {
	return &normaliser{r: r}
}

func (norm *normaliser) Read(p []byte) (n int, err error) {
	n, err = norm.r.Read(p)
	for i := 0; i < n; i++ {
		switch {
		case p[i] == '\n' && norm.lastChar == '\r':
			copy(p[i:n], p[i+1:])
			norm.lastChar = p[i]
			n--
			i--
		case p[i] == '\r':
			norm.lastChar = p[i]
			p[i] = '\n'
		default:
			norm.lastChar = p[i]
		}
	}
	return
}