@@ -3,6 +3,7 @@ package masker
33import (
44 "bytes"
55 "io"
6+ "io/ioutil"
67 "sync"
78 "time"
89)
@@ -64,31 +65,32 @@ 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+ _ , err = s .buf .writeUpToIndex (ioutil .Discard , i + int64 (length ))
84+ if err != nil {
85+ return err
86+ }
8587
8688 delete (s .matches , i )
8789 }
8890 }
8991
9092 // Write all bytes after the last match.
91- _ , err := s .dest . Write (s .buf . upToIndex ( endIndex ) )
93+ _ , err := s .buf . writeUpToIndex (s .dest , endIndex )
9294 if err != nil {
9395 return err
9496 }
@@ -109,16 +111,17 @@ func (b *indexedBuffer) write(p []byte) (n int, err error) {
109111 return b .buffer .Write (p )
110112}
111113
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 {
114+ // writeUpToIndex pops all bytes in the buffer up to the given index and writes them to the given writer .
115+ // The number of bytes written and any errors encountered are returned
116+ func (b * indexedBuffer ) writeUpToIndex ( w io. Writer , index int64 ) ( int , error ) {
115117 b .mutex .Lock ()
116118 defer b .mutex .Unlock ()
117119
118120 if index < b .currentIndex {
119- return [] byte {}
121+ return 0 , nil
120122 }
121123 n := int (index - b .currentIndex )
122124 b .currentIndex = index
123- return b .buffer .Next (n )
125+ bufferSlice := b .buffer .Next (n )
126+ return w .Write (bufferSlice )
124127}
0 commit comments