File: timeout.go

package info (click to toggle)
golang-github-farsightsec-golang-framestream 0.3.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 116 kB
  • sloc: makefile: 4
file content (67 lines) | stat: -rw-r--r-- 1,240 bytes parent folder | download
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package framestream

import (
	"io"
	"net"
	"time"
)

type timeoutConn struct {
	conn                      net.Conn
	readTimeout, writeTimeout time.Duration
}

func (toc *timeoutConn) Write(b []byte) (int, error) {
	if toc.writeTimeout != 0 {
		toc.conn.SetWriteDeadline(time.Now().Add(toc.writeTimeout))
	}
	return toc.conn.Write(b)
}

func (toc *timeoutConn) Read(b []byte) (int, error) {
	if toc.readTimeout != 0 {
		toc.conn.SetReadDeadline(time.Now().Add(toc.readTimeout))
	}
	return toc.conn.Read(b)
}

func timeoutWriter(w io.Writer, opt *WriterOptions) io.Writer {
	if !opt.Bidirectional {
		return w
	}
	if opt.Timeout == 0 {
		return w
	}
	if c, ok := w.(net.Conn); ok {
		return &timeoutConn{
			conn:         c,
			readTimeout:  opt.Timeout,
			writeTimeout: opt.Timeout,
		}
	}
	return w
}

func timeoutReader(r io.Reader, opt *ReaderOptions) io.Reader {
	if !opt.Bidirectional {
		return r
	}
	if opt.Timeout == 0 {
		return r
	}
	if c, ok := r.(net.Conn); ok {
		return &timeoutConn{
			conn:         c,
			readTimeout:  opt.Timeout,
			writeTimeout: opt.Timeout,
		}
	}
	return r
}

func disableReadTimeout(r io.Reader) {
	if tc, ok := r.(*timeoutConn); ok {
		tc.readTimeout = 0
		tc.conn.SetReadDeadline(time.Time{})
	}
}