// ReaderOut wraps the reads of r with a SparkStream. The stream will
// have Bytes units and refresh every 33ms.
//
// It will stop printing when the reader returns an error.
497872
func ReaderOut(r io.Reader, out *os.File) io.Reader {
	sprk := Spark(time.Millisecond * 33)
	sprk.Out = out
	sprk.Units = Bytes
	started := false
	return reader(func(b []byte) (int, error) {
		if !started {
			sprk.Start()
			started = true
		}
		n, err := r.Read(b)
		if err == nil {
			sprk.Add(float64(n))
		} else {
			sprk.Stop()
		}
		return n, err
	})
}
858259
func (c *Connection) handleReadError(md MessageData) {
	c.log("HDRERR", "starts", md)
	c.shutdownHeartBeats() // We are done here
	// Notify any general subscriber of error
	select {
	case c.input <- md:
	default:
	}
	// Notify all individual subscribers of error
	// This is a read lock
	c.subsLock.RLock()
	if c.connected {
		for key := range c.subs {
			c.subs[key].md <- md
		}
	}
	c.subsLock.RUnlock()
	// Try to catch the writer
	close(c.wtrsdc)
	c.log("HDRERR", "ends")
	// Let further shutdown logic proceed normally.
	return
}
803501
func ReadError(statusCode int, re []byte) error {
	var e error
	switch statusCode {
	case http.StatusNotFound:
		e = &NotFoundError{Message: string(re)}
	case http.StatusBadRequest:
		e = &BadParameterError{Message: string(re)}
	case http.StatusNotImplemented:
		e = &NotImplementedError{Message: string(re)}
	case http.StatusPreconditionFailed:
		e = &CompareFailedError{Message: string(re)}
	case http.StatusForbidden:
		e = &AccessDeniedError{Message: string(re)}
	case http.StatusConflict:
		e = &AlreadyExistsError{Message: string(re)}
	case http.StatusTooManyRequests:
		e = &LimitExceededError{Message: string(re)}
	case http.StatusGatewayTimeout:
		e = &ConnectionProblemError{Message: string(re)}
	default:
		if statusCode < 200 || statusCode > 299 {
			return Errorf(string(re))
		}
		return nil
	}
	return unmarshalError(e, re)
}
178244
func (c *Client) NewStreamReader(streamName string) *StreamReader {
	return &StreamReader{
		streamName: streamName,
		client:     c,
		version:    -1,
		pageSize:   20,
	}
}
1368516
func (bi *blockImporter) readHandler() {
out:
	for {
		// Read the next block from the file and if anything goes wrong
		// notify the status handler with the error and bail.
		serializedBlock, err := bi.readBlock()
		if err != nil {
			bi.errChan <- fmt.Errorf("Error reading from input "+
				"file: %v", err.Error())
			break out
		}

		// A nil block with no error means we're done.
		if serializedBlock == nil {
			break out
		}

		// Send the block or quit if we've been signalled to exit by
		// the status handler due to an error elsewhere.
		select {
		case bi.processQueue <- serializedBlock:
		case <-bi.quit:
			break out
		}
	}

	// Close the processing channel to signal no more blocks are coming.
	close(bi.processQueue)
	bi.wg.Done()
}
416569
func readOutpoint(r io.Reader, o *wire.OutPoint) error {
	if _, err := io.ReadFull(r, o.Hash[:]); err != nil {
		return err
	}
	if err := binary.Read(r, byteOrder, &o.Index); err != nil {
		return err
	}

	return nil
}
1024136
func (c *Connection) reader() {
	for {
		res := new(rpcResponse)
		err := c.dec.Decode(res)
		if _, ok := err.(net.Error); err == io.EOF || ok {
			log.WithField(`error`, err).Error(`Reading from Kodi`)
			log.Error(`If this error persists, make sure you are using the JSON-RPC port, not the HTTP port!`)
			for err != nil {
				err = c.connect()
			}
		} else if err != nil {
			log.WithField(`error`, err).Error(`Decoding response from Kodi`)
			continue
		}
		if res.Id == nil && res.Method != nil {
			c.notificationWait.Add(1)
			// Process notifications in a separate routine so we don't delay the
			// processing of standard responses.  This does mean losing ordering
			// guarantees for notifications.
			go func() {
				if res.Params != nil {
					log.WithFields(log.Fields{
						`notification.Method`: *res.Method,
						`notification.Params`: *res.Params,
					}).Debug(`Received notification from Kodi`)
				} else {
					log.WithField(`notification.Method`, *res.Method).Debug(`Received notification from Kodi`)
				}
				n := Notification{}
				n.Method = *res.Method
				err := mapstructure.Decode(res.Params, &n.Params)
				if err != nil {
					log.WithField(`notification.Method`, *res.Method).Warn(`Decoding notifcation failed`)
					return
				}
				// Implement notification writes as a ring buffer.
				// In case the client is not processing notifications, we don't
				// want to block indefinitely here, instead drop the oldest
				// notification after 200ms, and log a warning
				select {
				case c.Notifications <- n:
				case <-time.After(200 * time.Millisecond):
					<-c.Notifications
					c.Notifications <- n
					log.Warn(`Dropped oldest notification, buffer full`)
				}
				c.notificationWait.Done()
			}()
		} else if res.Id != nil {
			if ch := c.responses[uint32(*res.Id)]; ch != nil {
				if res.Result != nil {
					log.WithField(`response.Result`, *res.Result).Debug(`Received response from Kodi`)
				}
				*ch <- res
			} else {
				log.WithField(`response.Id`, *res.Id).Warn(`Received Kodi response for unknown request`)
				log.WithField(`connection.responses`, c.responses).Debug(`Current response channels`)
			}
		} else {
			if res.Error != nil {
				log.WithField(`response.Error`, *res.Error).Warn(`Received unparseable Kodi response`)
			} else {
				log.WithField(`response`, res).Warn(`Received unparseable Kodi response`)
			}
		}
	}
}
906105
func NewReader(rd io.Reader) *Reader {
	mr := new(Reader)
	mr.Reset(rd)
	return mr
}
900815
func (c *FCGIClient) SetReadTimeout(t time.Duration) error {
	if conn, ok := c.rwc.(net.Conn); ok && t != 0 {
		return conn.SetReadDeadline(time.Now().Add(t))
	}
	return nil
}
101205
func ReaderToString(lines io.Reader) string {
	if lines == nil {
		return ""
	}
	b := bp.GetBuffer()
	defer bp.PutBuffer(b)
	b.ReadFrom(lines)
	return b.String()
}
237629
func newTimeoutReader(reader io.ReadCloser, timeout time.Duration, cancel func()) *timeoutReader {
	return &timeoutReader{
		reader:  reader,
		timeout: timeout,
		cancel:  cancel,
	}
}
698801
func (pool *ReaderPool) ReleaseReader(reader *Reader) {
	reader.Init(nil)
	reader.Reset()
	pool.Put(reader)
}
1146993
func streamOutput(src io.Reader, dst *bytes.Buffer, out io.Writer) error {
	mw := io.MultiWriter(dst, out)
	s := bufio.NewReader(src)
	for {
		var line []byte
		line, err := s.ReadSlice('\n')
		if err == io.EOF && len(line) == 0 {
			break // done
		}
		if err == io.EOF {
			return fmt.Errorf("Improper termination: %v", line)
		}
		if err != nil {
			return err
		}

		// append to the buffer and out at once
		mw.Write(line)
	}

	return nil
}
139564
func NewOut(out io.Writer) *Out {
	fd, isTerminal := term.GetFdInfo(out)
	return &Out{commonStream: commonStream{fd: fd, isTerminal: isTerminal}, out: out}
}
903522
func (r *reader) Read(b []byte) (int, error) {
	n, err := r.r.Read(b)
	r.pos += int64(n)

	if err != nil && err != io.EOF {
		return n, err
	}

	q := readerReport{
		t:    time.Now(),
		pos:  r.pos,
		size: r.size,
		bps:  &r.bps,
	}

	select {
	case r.ch <- q:
	case <-r.ctx.Done():
	}

	return n, err
}
1099087
func readTxOut(r io.Reader, pver uint32, version int32, to *TxOut) error {
	err := readElement(r, &to.Value)
	if err != nil {
		return err
	}

	to.PkScript, err = readScript(r, pver, MaxMessagePayload,
		"transaction output public key script")
	return err
}
1267832
func (r *Reader) readRune() (rune, error) {
	r1, _, err := r.r.ReadRune()

	// Handle \r\n here.  We make the simplifying assumption that
	// anytime \r is followed by \n that it can be folded to \n.
	// We will not detect files which contain both \r\n and bare \n.
	if r1 == '\r' {
		r1, _, err = r.r.ReadRune()
		if err == nil {
			if r1 != '\n' {
				r.r.UnreadRune()
				r1 = '\r'
			}
		}
	}
	r.column++
	return r1, err
}