| 1 | package framestream |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "net" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | type timeoutConn struct { |
| 10 | conn net.Conn |
| 11 | readTimeout, writeTimeout time.Duration |
| 12 | } |
| 13 | |
| 14 | func (toc *timeoutConn) Write(b []byte) (int, error) { |
| 15 | if toc.writeTimeout != 0 { |
| 16 | toc.conn.SetWriteDeadline(time.Now().Add(toc.writeTimeout)) |
| 17 | } |
| 18 | return toc.conn.Write(b) |
| 19 | } |
| 20 | |
| 21 | func (toc *timeoutConn) Read(b []byte) (int, error) { |
| 22 | if toc.readTimeout != 0 { |
| 23 | toc.conn.SetReadDeadline(time.Now().Add(toc.readTimeout)) |
| 24 | } |
| 25 | return toc.conn.Read(b) |
| 26 | } |
| 27 | |
| 28 | func timeoutWriter(w io.Writer, opt *WriterOptions) io.Writer { |
| 29 | if !opt.Bidirectional { |
| 30 | return w |
| 31 | } |
| 32 | if opt.Timeout == 0 { |
| 33 | return w |
| 34 | } |
| 35 | if c, ok := w.(net.Conn); ok { |
| 36 | return &timeoutConn{ |
| 37 | conn: c, |
| 38 | readTimeout: opt.Timeout, |
| 39 | writeTimeout: opt.Timeout, |
| 40 | } |
| 41 | } |
| 42 | return w |
| 43 | } |
| 44 | |
| 45 | func timeoutReader(r io.Reader, opt *ReaderOptions) io.Reader { |
| 46 | if !opt.Bidirectional { |
| 47 | return r |
| 48 | } |
| 49 | if opt.Timeout == 0 { |
| 50 | return r |
| 51 | } |
| 52 | if c, ok := r.(net.Conn); ok { |
| 53 | return &timeoutConn{ |
| 54 | conn: c, |
| 55 | readTimeout: opt.Timeout, |
| 56 | writeTimeout: opt.Timeout, |
| 57 | } |
| 58 | } |
| 59 | return r |
| 60 | } |
| 61 | |
| 62 | func disableReadTimeout(r io.Reader) { |
| 63 | if tc, ok := r.(*timeoutConn); ok { |
| 64 | tc.readTimeout = 0 |
| 65 | tc.conn.SetReadDeadline(time.Time{}) |
| 66 | } |
| 67 | } |