File: stream.go

package info (click to toggle)
golang-github-juju-utils 0.0~git20200923.4646bfe-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 1,324 kB
  • sloc: makefile: 37
file content (36 lines) | stat: -rw-r--r-- 913 bytes parent folder | download | duplicates (3)
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
36
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package ssh

import (
	"bytes"
	"io"
)

// stripCR implements an io.Reader wrapper that removes carriage return bytes.
type stripCR struct {
	reader io.Reader
}

// StripCRReader returns a new io.Reader wrapper that strips carriage returns.
func StripCRReader(reader io.Reader) io.Reader {
	if reader == nil {
		return nil
	}
	return &stripCR{reader: reader}
}

var byteEmpty = []byte{}
var byteCR = []byte{'\r'}

// Read implements io.Reader interface.
// This copies data around much more than needed so should be optimized if
// used on a performance critical path.
func (s *stripCR) Read(bufOut []byte) (int, error) {
	bufTemp := make([]byte, len(bufOut))
	n, err := s.reader.Read(bufTemp)
	bufReplaced := bytes.Replace(bufTemp[:n], byteCR, byteEmpty, -1)
	copy(bufOut, bufReplaced)
	return len(bufReplaced), err
}