@@ -3,6 +3,7 @@ package masker
33import (
44 "bytes"
55 "io"
6+ "io/ioutil"
67 "sync"
78 "time"
89)
@@ -64,31 +65,29 @@ func (s *stream) flush(n int) error {
6465
6566 if exists {
6667 // Get any unprocessed bytes before this match to the destination.
67- beforeMatch := s .buf .upToIndex (i )
68-
69- _ , err := s .dest .Write (beforeMatch )
68+ bytesBeforeMatch , err := s .buf .writeUpToIndex (s .dest , i )
7069 if err != nil {
7170 return err
7271 }
7372
7473 // Only write the redaction text if there were bytes between this match and the previous match
7574 // or this is the first flush for the buffer.
76- if len ( beforeMatch ) > 0 || s .buf .currentIndex == 0 {
75+ if bytesBeforeMatch > 0 || s .buf .currentIndex == 0 {
7776 _ , err = s .dest .Write ([]byte ("<redacted by SecretHub>" ))
7877 if err != nil {
7978 return err
8079 }
8180 }
8281
8382 // Drop all bytes until the end of the mask.
84- _ = s .buf .upToIndex ( i + int64 (length ))
83+ _ , _ = s .buf .writeUpToIndex ( ioutil . Discard , i + int64 (length ))
8584
8685 delete (s .matches , i )
8786 }
8887 }
8988
9089 // Write all bytes after the last match.
91- _ , err := s .dest . Write (s .buf . upToIndex ( endIndex ) )
90+ _ , err := s .buf . writeUpToIndex (s .dest , endIndex )
9291 if err != nil {
9392 return err
9493 }
@@ -109,19 +108,17 @@ func (b *indexedBuffer) write(p []byte) (n int, err error) {
109108 return b .buffer .Write (p )
110109}
111110
112- // upToIndex pops and returns all bytes in the buffer up to the given index.
113- // If all bytes up to this given index have already been returned previously, an empty slice is returned.
114- func (b * indexedBuffer ) upToIndex ( index int64 ) [] byte {
111+ // writeUpToIndex pops all bytes in the buffer up to the given index and writes them to the given writer .
112+ // The number of bytes written and any errors encountered are returned
113+ func (b * indexedBuffer ) writeUpToIndex ( w io. Writer , index int64 ) ( int , error ) {
115114 b .mutex .Lock ()
116115 defer b .mutex .Unlock ()
117116
118117 if index < b .currentIndex {
119- return [] byte {}
118+ return 0 , nil
120119 }
121120 n := int (index - b .currentIndex )
122121 b .currentIndex = index
123122 bufferSlice := b .buffer .Next (n )
124- res := make ([]byte , len (bufferSlice ))
125- copy (res , bufferSlice )
126- return res
123+ return w .Write (bufferSlice )
127124}
0 commit comments