File: readstring_context.go

package info (click to toggle)
receptor 1.5.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,772 kB
  • sloc: python: 1,643; makefile: 305; sh: 174
file content (32 lines) | stat: -rw-r--r-- 815 bytes parent folder | download | duplicates (2)
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
package utils

import (
	"bufio"
	"context"
)

type readStringResult = struct {
	str string
	err error
}

// ReadStringContext calls bufio.Reader.ReadString() but uses a context.  Note that if the
// ctx.Done() fires, the ReadString() call is still active, and bufio is not re-entrant, so it is
// important for callers to error out of further use of the bufio.  Also, the goroutine will not
// exit until the bufio's underlying connection is closed.
func ReadStringContext(ctx context.Context, reader *bufio.Reader, delim byte) (string, error) {
	result := make(chan *readStringResult, 1)
	go func() {
		str, err := reader.ReadString(delim)
		result <- &readStringResult{
			str: str,
			err: err,
		}
	}()
	select {
	case res := <-result:
		return res.str, res.err
	case <-ctx.Done():
		return "", ctx.Err()
	}
}