about summary refs log tree commit diff stats
path: root/src/io/teestream.nim
blob: 81c9e2f07afba9daa5fe9c3db97ca2f5242a5ed5 (plain) (blame)
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
37
38
39
40
41
42
43
44
import streams

type TeeStream = ref object of Stream
  source: Stream
  dest: Stream
  closedest: bool

proc tsClose(s: Stream) =
  let s = cast[TeeStream](s)
  s.source.close()
  if s.closedest:
    s.dest.close()

proc tsReadData(s: Stream, buffer: pointer, bufLen: int): int =
  let s = cast[TeeStream](s)
  result = s.source.readData(buffer, bufLen)
  s.dest.writeData(buffer, result)

proc tsReadDataStr(s: Stream, buffer: var string, slice: Slice[int]): int =
  let s = cast[TeeStream](s)
  result = s.source.readDataStr(buffer, slice)
  if result <= 0: return
  s.dest.writeData(addr buffer[0], result)

proc tsAtEnd(s: Stream): bool =
  let s = cast[TeeStream](s)
  return s.source.atEnd

proc newTeeStream*(source, dest: Stream, closedest = true): TeeStream =
  return TeeStream(
    source: source,
    dest: dest,
    closedest: closedest,
    closeImpl: tsClose,
    readDataImpl:
      cast[proc(s: Stream, buffer: pointer, len: int): int
      {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
      ](tsReadData),
    readDataStrImpl:
      cast[proc(s: Stream, buffer: var string, slice: Slice[int]): int
      {.nimcall, raises: [Defect, IOError, OSError], tags: [ReadIOEffect], gcsafe.}
      ](tsReadDataStr),
    atEndImpl: tsAtEnd
  )