// Read from a framedDeecoderStream. The frame is the "BEGIN FOO." block
// at the beginning, and the "END FOO." block at the end.
2598
func (s *framedDecoderStream) Read(p []byte) (n int, err error) {

	if s.state == fdsHeader {
		err = s.loadHeader()
		if err != nil {
			return 0, err
		}
	}

	if s.state == fdsBody {
		n, err = s.r.Read(p)
		if err == ErrPunctuated {
			err = nil
			s.state = fdsFooter
		}
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		if err != nil {
			return 0, err
		}
	}

	if s.state == fdsFooter {
		s.footer, err = s.r.ReadUntilPunctuation(s.frameLim)
		if err != nil {
			return 0, err
		}
		if s.frameChecker != nil {
			headerStr, err := s.toASCII(s.header)
			if err != nil {
				return 0, err
			}
			footerStr, err := s.toASCII(s.footer)
			if err != nil {
				return 0, err
			}
			if _, err = s.frameChecker(headerStr, footerStr); err != nil {
				return 0, err
			}
		}
		s.state = fdsEndOfStream
	}

	if s.state == fdsEndOfStream {
		err = s.consumeUntilEOF()
		if err == io.EOF && n > 0 {
			err = nil
		}
	}

	return n, err
}
665560
func (s *Server) ReadSSFStreamSocket(serverConn net.Conn) {
	defer func() {
		serverConn.Close()
	}()

	// initialize the capacity to the max size
	// based on the number of tags we add later
	tags := make([]string, 1, 3)
	tags[0] = "ssf_format:framed"

	for {
		msg, err := protocol.ReadSSF(serverConn)
		if err != nil {
			if err == io.EOF {
				// Client hangup, close this
				s.Statsd.Count("frames.disconnects", 1, nil, 1.0)
				return
			}
			if protocol.IsFramingError(err) {
				log.WithError(err).
					WithField("remote", serverConn.RemoteAddr()).
					Info("Frame error reading from SSF connection. Closing.")
				tags = append(tags, []string{"packet_type:unknown", "reason:framing"}...)
				s.Statsd.Incr("ssf.error_total", tags, 1.0)
				return
			}
			// Non-frame errors means we can continue reading:
			log.WithError(err).
				WithField("remote", serverConn.RemoteAddr()).
				Error("Error processing an SSF frame")
			tags = append(tags, []string{"packet_type:unknown", "reason:processing"}...)
			s.Statsd.Incr("ssf.error_total", tags, 1.0)
			tags = tags[:1]
			continue
		}
		s.handleSSF(msg, "framed")
	}
}
279089
func (br *Reader) readBlockHeader() {
	if br.last {
		if br.rd.ReadPads() > 0 {
			errors.Panic(errCorrupted)
		}
		errors.Panic(io.EOF)
	}

	// Read ISLAST and ISLASTEMPTY.
	if br.last = br.rd.ReadBits(1) == 1; br.last {
		if empty := br.rd.ReadBits(1) == 1; empty {
			br.readBlockHeader() // Next call will terminate stream
			return
		}
	}

	// Read MLEN and MNIBBLES and process meta data.
	var blkLen int // 1..1<<24
	nibbles := br.rd.ReadBits(2) + 4
	if nibbles == 7 {
		if reserved := br.rd.ReadBits(1) == 1; reserved {
			errors.Panic(errCorrupted)
		}

		var skipLen int // 0..1<<24
		if skipBytes := br.rd.ReadBits(2); skipBytes > 0 {
			skipLen = int(br.rd.ReadBits(skipBytes * 8))
			if skipBytes > 1 && skipLen>>((skipBytes-1)*8) == 0 {
				errors.Panic(errCorrupted) // Shortest representation not used
			}
			skipLen++
		}

		if br.rd.ReadPads() > 0 {
			errors.Panic(errCorrupted)
		}
		br.blkLen = skipLen // Use blkLen to track metadata number of bytes
		br.readMetaData()
		return
	}
	blkLen = int(br.rd.ReadBits(nibbles * 4))
	if nibbles > 4 && blkLen>>((nibbles-1)*4) == 0 {
		errors.Panic(errCorrupted) // Shortest representation not used
	}
	br.blkLen = blkLen + 1

	// Read ISUNCOMPRESSED and process uncompressed data.
	if !br.last {
		if uncompressed := br.rd.ReadBits(1) == 1; uncompressed {
			if br.rd.ReadPads() > 0 {
				errors.Panic(errCorrupted)
			}
			br.readRawData()
			return
		}
	}
	br.readPrefixCodes()
}
213027
func (lengthDelimitedFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
	return framer.NewLengthDelimitedFrameReader(r)
}
1115855
func (e *StringDecoder) Read() string {
	// Read the length of the string
	length, n := binary.Uvarint(e.b[e.i:])
	if n <= 0 {
		e.err = fmt.Errorf("stringDecoder: invalid encoded string length")
		return ""
	}

	// The length of this string plus the length of the variable byte encoded length
	e.l = int(length) + n

	lower := e.i + n
	upper := lower + int(length)
	if upper < lower {
		e.err = fmt.Errorf("stringDecoder: length overflow")
		return ""
	}
	if upper > len(e.b) {
		e.err = fmt.Errorf("stringDecoder: not enough data to represent encoded string")
		return ""
	}

	return string(e.b[lower:upper])
}
272682
func (r *recvBufferReader) Read(p []byte) (n int, err error) {
	if r.err != nil {
		return 0, r.err
	}
	if r.last != nil && len(r.last) > 0 {
		// Read remaining data left in last call.
		copied := copy(p, r.last)
		r.last = r.last[copied:]
		return copied, nil
	}
	if r.closeStream != nil {
		n, r.err = r.readClient(p)
	} else {
		n, r.err = r.read(p)
	}
	return n, r.err
}
977709
func (mr *Reader) Read(buf []byte) (int, error) {
	if mr.err != nil {
		return 0, mr.err
	}

	var rdCnt int
	for len(buf) > 0 {
		if len(mr.buf) > 0 {
			cpCnt := copy(buf, mr.buf)
			mr.buf = mr.buf[cpCnt:]
			rdCnt += cpCnt
			break
		}

		if mr.final != FinalNil {
			mr.FinalMode = mr.final
			mr.err = io.EOF
			break
		}

		mr.err = mr.decodeBlock()
		if mr.err != nil {
			break
		}
	}

	mr.OutputOffset += int64(rdCnt)
	return rdCnt, mr.err
}
442354
func (r *Reader) Read(p []byte) (n int, err error) {
	// Deviations from RFC 2045:
	// 1. in addition to "=\r\n", "=\n" is also treated as soft line break.
	// 2. it will pass through a '\r' or '\n' not preceded by '=', consistent
	//    with other broken QP encoders & decoders.
	for len(p) > 0 {
		if len(r.line) == 0 {
			if r.rerr != nil {
				return n, r.rerr
			}
			r.line, r.rerr = r.br.ReadSlice('\n')

			// Does the line end in CRLF instead of just LF?
			hasLF := bytes.HasSuffix(r.line, lf)
			hasCR := bytes.HasSuffix(r.line, crlf)
			wholeLine := r.line
			r.line = bytes.TrimRightFunc(wholeLine, isQPDiscardWhitespace)
			if bytes.HasSuffix(r.line, softSuffix) {
				rightStripped := wholeLine[len(r.line):]
				r.line = r.line[:len(r.line)-1]
				if !bytes.HasPrefix(rightStripped, lf) && !bytes.HasPrefix(rightStripped, crlf) {
					r.rerr = fmt.Errorf("quotedprintable: invalid bytes after =: %q", rightStripped)
				}
			} else if hasLF {
				if hasCR {
					r.line = append(r.line, '\r', '\n')
				} else {
					r.line = append(r.line, '\n')
				}
			}
			continue
		}
		b := r.line[0]

		switch {
		case b == '=':
			if len(r.line[1:]) < 2 {
				return n, io.ErrUnexpectedEOF
			}
			b, err = readHexByte(r.line[1], r.line[2])
			if err != nil {
				return n, err
			}
			r.line = r.line[2:] // 2 of the 3; other 1 is done below
		case b == '\t' || b == '\r' || b == '\n':
			break
		case b < ' ' || b > '~':
			return n, fmt.Errorf("quotedprintable: invalid unescaped byte 0x%02x in body", b)
		}
		p[0] = b
		p = p[1:]
		r.line = r.line[1:]
		n++
	}
	return n, nil
}
1040894
func NewJSONFramedReader(r io.ReadCloser) io.ReadCloser {
	return &jsonFrameReader{
		r:       r,
		decoder: json.NewDecoder(r),
	}
}
434153
func (sfr *sparseFileReader) Read(b []byte) (n int, err error) {
	// Skip past all empty fragments.
	for len(sfr.sp) > 0 && sfr.sp[0].numBytes == 0 {
		sfr.sp = sfr.sp[1:]
	}

	// If there are no more fragments, then it is possible that there
	// is one last sparse hole.
	if len(sfr.sp) == 0 {
		// This behavior matches the BSD tar utility.
		// However, GNU tar stops returning data even if sfr.total is unmet.
		if sfr.pos < sfr.total {
			return sfr.readHole(b, sfr.total), nil
		}
		return 0, io.EOF
	}

	// In front of a data fragment, so read a hole.
	if sfr.pos < sfr.sp[0].offset {
		return sfr.readHole(b, sfr.sp[0].offset), nil
	}

	// In a data fragment, so read from it.
	// This math is overflow free since we verify that offset and numBytes can
	// be safely added when creating the sparseFileReader.
	endPos := sfr.sp[0].offset + sfr.sp[0].numBytes // End offset of fragment
	bytesLeft := endPos - sfr.pos                   // Bytes left in fragment
	if int64(len(b)) > bytesLeft {
		b = b[:bytesLeft]
	}

	n, err = sfr.rfr.Read(b)
	sfr.pos += int64(n)
	if err == io.EOF {
		if sfr.pos < endPos {
			err = io.ErrUnexpectedEOF // There was supposed to be more data
		} else if sfr.pos < sfr.total {
			err = nil // There is still an implicit sparse hole at the end
		}
	}

	if sfr.pos == endPos {
		sfr.sp = sfr.sp[1:] // We are done with this fragment, so pop it
	}
	return n, err
}
397195
func (c *Conn) Read(sdu []byte) (n int, err error) {
	p, ok := <-c.chInPDU
	if !ok {
		return 0, errors.Wrap(io.ErrClosedPipe, "input channel closed")
	}
	if len(p) == 0 {
		return 0, errors.Wrap(io.ErrUnexpectedEOF, "recieved empty packet")
	}

	// Assume it's a B-Frame.
	slen := p.dlen()
	data := p.payload()
	if c.leFrame {
		// LE-Frame.
		slen = leFrameHdr(p).slen()
		data = leFrameHdr(p).payload()
	}
	if cap(sdu) < slen {
		return 0, errors.Wrapf(io.ErrShortBuffer, "payload recieved exceeds sdu buffer")
	}
	buf := bytes.NewBuffer(sdu)
	buf.Reset()
	buf.Write(data)
	for buf.Len() < slen {
		p := <-c.chInPDU
		buf.Write(pdu(p).payload())
	}
	return slen, nil
}
889979
func NewBlockFromReader(r io.Reader) (*Block, error) {
	// Deserialize the bytes into a MsgBlock.
	var msgBlock wire.MsgBlock
	err := msgBlock.Deserialize(r)
	if err != nil {
		return nil, err
	}

	b := Block{
		msgBlock:    &msgBlock,
		blockHeight: BlockHeightUnknown,
	}
	return &b, nil
}
540623
func MustReadFrame(r io.Reader) Frame {
	f, err := ReadFrame(r)
	if err != nil {
		panic(err)
	}
	return f
}
616002
func (d *frameDec) next(block *blockDec) error {
	println("decoding new block")
	err := block.reset(d.rawInput, d.WindowSize)
	if err != nil {
		println("block error:", err)
		// Signal the frame decoder we have a problem.
		d.sendErr(block, err)
		return err
	}
	block.input <- struct{}{}
	if debug {
		println("next block:", block)
	}
	d.asyncRunningMu.Lock()
	defer d.asyncRunningMu.Unlock()
	if !d.asyncRunning {
		return nil
	}
	if block.Last {
		// We indicate the frame is done by sending io.EOF
		d.decoding <- block
		return io.EOF
	}
	d.decoding <- block
	return nil
}
956194
func (c *Connection) reader(r io.Reader) {
	buf := bufio.NewReader(r)
	frames := &reader{buf}
	conn, haveDeadliner := r.(readDeadliner)

	for {
		frame, err := frames.ReadFrame()

		if err != nil {
			c.shutdown(&Error{Code: FrameError, Reason: err.Error()})
			return
		}

		c.demux(frame)

		if haveDeadliner {
			c.deadlines <- conn
		}
	}
}
598846
func (e *EncodeSession) ReadFrame() (frame []byte, err error) {
	f := <-e.frameChannel
	if f == nil {
		return nil, io.EOF
	}

	return f.data, nil
}
982233
func (w *Webcam) ReadFrame() ([]byte, error) {
	result, index, err := w.GetFrame()
	if err == nil {
		w.ReleaseFrame(index)
	}
	return result, err
}