Spool spools the contents from 'from' to 'to' by buffering the entire contents of 'from' into a temporary file created in the directory "dir". That buffer is held in memory until the file grows to larger than 'memoryBufferLimit`, then the remaining contents are spooled to disk. The temporary file i
(to io.Writer, from io.Reader, dir string)
| 109 | // The number of bytes written to "to", as well as any error encountered are |
| 110 | // returned. |
| 111 | func Spool(to io.Writer, from io.Reader, dir string) (n int64, err error) { |
| 112 | // First, buffer up to `memoryBufferLimit` in memory. |
| 113 | buf := make([]byte, memoryBufferLimit) |
| 114 | if bn, err := from.Read(buf); err != nil && err != io.EOF { |
| 115 | return int64(bn), err |
| 116 | } else { |
| 117 | buf = buf[:bn] |
| 118 | } |
| 119 | |
| 120 | var spool io.Reader = bytes.NewReader(buf) |
| 121 | if err != io.EOF { |
| 122 | // If we weren't at the end of the stream, create a temporary |
| 123 | // file, and spool the remaining contents there. |
| 124 | tmp, err := os.CreateTemp(dir, "") |
| 125 | if err != nil { |
| 126 | return 0, errors.Wrap(err, tr.Tr.Get("Unable to create temporary file for spooling")) |
| 127 | } |
| 128 | defer func() { |
| 129 | tmp.Close() |
| 130 | os.Remove(tmp.Name()) |
| 131 | }() |
| 132 | |
| 133 | if n, err = io.Copy(tmp, from); err != nil { |
| 134 | return n, errors.Wrap(err, tr.Tr.Get("unable to spool")) |
| 135 | } |
| 136 | |
| 137 | if _, err = tmp.Seek(0, io.SeekStart); err != nil { |
| 138 | return 0, errors.Wrap(err, tr.Tr.Get("unable to seek")) |
| 139 | } |
| 140 | |
| 141 | // The spooled contents will now be the concatenation of the |
| 142 | // contents we stored in memory, then the remainder of the |
| 143 | // contents on disk. |
| 144 | spool = io.MultiReader(spool, tmp) |
| 145 | } |
| 146 | |
| 147 | return io.Copy(to, spool) |
| 148 | } |
| 149 | |
| 150 | // Split the input on the NUL character. Usable with bufio.Scanner. |
| 151 | func SplitOnNul(data []byte, atEOF bool) (advance int, token []byte, err error) { |