// Reads the ebml and Segment header portions of the webm stream so that they
// are available immediately, then returns a WebmKeeper ready for reading and
// writing
16635
func New(r io.Reader) (*WebmKeeper, error) {
	p := webmEdtd.NewParser(r)
	header := bytes.NewBuffer(make([]byte, 0, 4096))
	body := bytes.NewBuffer(make([]byte, 0, 4096))

	for {
		el, err := next(p)
		if err != nil {
			return nil, err
		}

		if el.Name == "Cluster" {
			el.WriteTo(body)
			break
		}
		el.WriteTo(header)
	}

	return &WebmKeeper{
		p:       p,
		header:  header,
		body:    body,
		elemBuf: bytes.NewBuffer(make([]byte, 0, 1024)),
	}, nil
}
909214
func readFromStream(
	ctx context.Context,
	stream transport.Stream,
	newMessage func() proto.Message,
) (proto.Message, error) {
	streamMsg, err := stream.ReceiveMessage(ctx)
	if err != nil {
		return nil, err
	}
	message := newMessage()
	if err := unmarshal(stream.Request().Meta.Encoding, streamMsg.Body, message); err != nil {
		streamMsg.Body.Close()
		return nil, err
	}
	if streamMsg.Body != nil {
		streamMsg.Body.Close()
	}
	return message, nil
}
429741
func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
	var buf [4]byte
	_, err = io.ReadFull(r, buf[:1])
	if err != nil {
		return
	}
	if buf[0]&0x80 == 0 {
		err = errors.StructuralError("tag byte does not have MSB set")
		return
	}
	if buf[0]&0x40 == 0 {
		// Old format packet
		tag = packetType((buf[0] & 0x3f) >> 2)
		lengthType := buf[0] & 3
		if lengthType == 3 {
			length = -1
			contents = r
			return
		}
		lengthBytes := 1 << lengthType
		_, err = readFull(r, buf[0:lengthBytes])
		if err != nil {
			return
		}
		for i := 0; i < lengthBytes; i++ {
			length <<= 8
			length |= int64(buf[i])
		}
		contents = &spanReader{r, length}
		return
	}

	// New format packet
	tag = packetType(buf[0] & 0x3f)
	length, isPartial, err := readLength(r)
	if err != nil {
		return
	}
	if isPartial {
		contents = &partialLengthReader{
			remaining: length,
			isPartial: true,
			r:         r,
		}
		length = -1
	} else {
		contents = &spanReader{r, length}
	}
	return
}
521534
func (m MeterBands) ReadFrom(r io.Reader) (int64, error) {
	var meterBandType MeterBandType

	rm := func() (io.ReaderFrom, error) {
		if rm, ok := meterBandMap[meterBandType]; ok {
			rd, err := rm.MakeReader()
			m = append(m, rd.(MeterBand))
			return rd, err
		}

		format := "ofp: unknown meter band type: '%x'"
		return nil, fmt.Errorf(format, meterBandType)
	}

	return encoding.ScanFrom(r, &meterBandType,
		encoding.ReaderMakerFunc(rm))
}
1195161
func ReadHeader(r io.Reader) (h Header, err error) {
	// Make slice of bytes with capacity 12 that could hold any header.
	//
	// The maximum header size is 14, but due to the 2 hop reads,
	// after first hop that reads first 2 constant bytes, we could reuse 2 bytes.
	// So 14 - 2 = 12.
	//
	// We use unsafe to stick bts to stack and avoid allocations.
	//
	// Using stack based slice is safe here, cause golang docs for io.Reader
	// says that "Implementations must not retain p".
	// See https://golang.org/pkg/io/#Reader
	var b [MaxHeaderSize - 2]byte
	bp := uintptr(unsafe.Pointer(&b))
	bh := &reflect.SliceHeader{Data: bp, Len: 2, Cap: MaxHeaderSize - 2}
	bts := *(*[]byte)(unsafe.Pointer(bh))

	// Prepare to hold first 2 bytes to choose size of next read.
	_, err = io.ReadFull(r, bts)
	if err != nil {
		return
	}

	h.Fin = bts[0]&bit0 != 0
	h.Rsv = (bts[0] & 0x70) >> 4
	h.OpCode = OpCode(bts[0] & 0x0f)

	var extra int

	if bts[1]&bit0 != 0 {
		h.Masked = true
		extra += 4
	}

	length := bts[1] & 0x7f
	switch {
	case length < 126:
		h.Length = int64(length)

	case length == 126:
		extra += 2

	case length == 127:
		extra += 8

	default:
		err = ErrHeaderLengthUnexpected
		return
	}

	if extra == 0 {
		return
	}

	// Increase len of bts to extra bytes need to read.
	// Overwrite frist 2 bytes read before.
	bts = bts[:extra]
	_, err = io.ReadFull(r, bts)
	if err != nil {
		return
	}

	switch {
	case length == 126:
		h.Length = int64(binary.BigEndian.Uint16(bts[:2]))
		bts = bts[2:]

	case length == 127:
		if bts[0]&0x80 != 0 {
			err = ErrHeaderLengthMSB
			return
		}
		h.Length = int64(binary.BigEndian.Uint64(bts[:8]))
		bts = bts[8:]
	}

	if h.Masked {
		copy(h.Mask[:], bts)
	}

	return
}
524182
func (a *AuthClientCodec) ReadResponseHeader(r *rpc.Response) error {

	// No need for synchronization here, Go's RPC Client makes sure only
	//  One response is read at a time.

	a.buff.ReadBuff.Reset()

	// Read the response from the connection
	response, err := auth.ReadLengthAndBytes(a.conn)
	if err != nil {
		// It is common to get harmless errors here whenever the client is closed
		return err
	}

	// Write the response to the buffer
	if _, err = a.buff.ReadBuff.Write(response); err != nil {
		return err
	}

	// Let the underlying codec read and parse the response from the buffer
	if err = a.wrappedcodec.ReadResponseHeader(r); err != nil {
		return err
	}

	log.WithField("ServiceMethod", r.ServiceMethod).Debug("Successfully read RPC response")

	return nil
}
836487
func (p *TCompactProtocol) ReadStructEnd() error {
	// consume the last field we read off the wire.
	p.lastFieldId = p.lastField[len(p.lastField)-1]
	p.lastField = p.lastField[:len(p.lastField)-1]
	return nil
}
1116985
func readValueHeader(fpr io.Reader) ([]byte, uint32, error) {
	return _readValueHeader(fpr, false)
}
1036966
func contentReader(headers Header, bodyReader io.Reader) *bufio.Reader {
	if headers.Get("Content-Transfer-Encoding") == "quoted-printable" {
		headers.Del("Content-Transfer-Encoding")
		return bufioReader(quotedprintable.NewReader(bodyReader))
	}
	if headers.Get("Content-Transfer-Encoding") == "base64" {
		headers.Del("Content-Transfer-Encoding")
		return bufioReader(base64.NewDecoder(base64.StdEncoding, bodyReader))
	}
	return bufioReader(bodyReader)
}
1195110
func (h HelloElems) ReadFrom(r io.Reader) (int64, error) {
	var helloElemType HelloElemType

	rm := func() (io.ReaderFrom, error) {
		if rm, ok := helloElemMap[helloElemType]; ok {
			rd, err := rm.MakeReader()
			h = append(h, rd.(HelloElem))
			return rd, err
		}

		format := "ofp: unknown hello element type: '%x'"
		return nil, fmt.Errorf(format, helloElemType)
	}

	return encoding.ScanFrom(r, &helloElemType,
		encoding.ReaderMakerFunc(rm))
}
291498
func ReadHeader(r *bufio.Reader) (Header, error) {
	var fs []headerField

	// The first line cannot start with a leading space.
	if buf, err := r.Peek(1); err == nil && isSpace(buf[0]) {
		line, err := readLineSlice(r, nil)
		if err != nil {
			return newHeader(fs), err
		}

		return newHeader(fs), fmt.Errorf("message: malformed MIME header initial line: %v", string(line))
	}

	for {
		kv, err := readContinuedLineSlice(r)
		if len(kv) == 0 {
			return newHeader(fs), err
		}

		// Key ends at first colon; should not have trailing spaces but they
		// appear in the wild, violating specs, so we remove them if present.
		i := bytes.IndexByte(kv, ':')
		if i < 0 {
			return newHeader(fs), fmt.Errorf("message: malformed MIME header line: %v", string(kv))
		}

		key := textproto.CanonicalMIMEHeaderKey(string(trim(kv[:i])))

		// As per RFC 7230 field-name is a token, tokens consist of one or more
		// chars. We could return a an error here, but better to be liberal in
		// what we accept, so if we get an empty key, skip it.
		if key == "" {
			continue
		}

		i++ // skip colon
		v := kv[i:]

		value := trimAroundNewlines(v)
		fs = append(fs, newHeaderField(key, value, kv))

		if err != nil {
			return newHeader(fs), err
		}
	}
}
1175252
func (d *Decoder) readHeaders() error {
	if d == nil || d.NumChans > 0 {
		return nil
	}

	id, size, err := d.parser.IDnSize()
	if err != nil {
		return err
	}
	d.parser.ID = id
	if d.parser.ID != riff.RiffID {
		return fmt.Errorf("%s - %s", d.parser.ID, riff.ErrFmtNotSupported)
	}
	d.parser.Size = size
	if err := binary.Read(d.r, binary.BigEndian, &d.parser.Format); err != nil {
		return err
	}

	var chunk *riff.Chunk
	var rewindBytes int64

	for err == nil {
		chunk, err = d.parser.NextChunk()
		if err != nil {
			break
		}

		if chunk.ID == riff.FmtID {
			chunk.DecodeWavHeader(d.parser)
			d.NumChans = d.parser.NumChannels
			d.BitDepth = d.parser.BitsPerSample
			d.SampleRate = d.parser.SampleRate
			d.WavAudioFormat = d.parser.WavAudioFormat
			d.AvgBytesPerSec = d.parser.AvgBytesPerSec

			if rewindBytes > 0 {
				d.r.Seek(-(rewindBytes + int64(chunk.Size) + 8), 1)
			}
			break
		} else if chunk.ID == CIDList {
			// The list chunk can be in the header or footer
			// because so many players don't support that chunk properly
			// it is recommended to have it at the end of the file.
			DecodeListChunk(d, chunk)
			// unexpected chunk order, might be a bext chunk
			rewindBytes += int64(chunk.Size) + 8
		} else if chunk.ID == CIDSmpl {
			DecodeSamplerChunk(d, chunk)
			rewindBytes += int64(chunk.Size) + 8
		} else {
			// unexpected chunk order, might be a bext chunk
			rewindBytes += int64(chunk.Size) + 8
			// drain the chunk
			io.CopyN(ioutil.Discard, d.r, int64(chunk.Size))
		}
	}

	return d.err
}
182417
func readRequestHeaders(
	ctx context.Context,
	format tchannel.Format,
	getReader func() (tchannel.ArgReader, error),
) (context.Context, transport.Headers, error) {
	headers, err := readHeaders(format, getReader)
	if err != nil {
		return ctx, headers, err
	}
	return ctx, headers, nil
}
570310
func (b *ByteBuf) ReadAll() (int, []byte, error) {
	return b.ReadBytes(b.Readable())
}
92583
func (s *Stream) Read(b []byte) (n int, err error) {
	if len(b) == 0 {
		select {
		case <-s.die:
			return 0, errors.New(errBrokenPipe)
		default:
			return 0, nil
		}
	}

	var deadline <-chan time.Time
	if d, ok := s.readDeadline.Load().(time.Time); ok && !d.IsZero() {
		timer := time.NewTimer(time.Until(d))
		defer timer.Stop()
		deadline = timer.C
	}

READ:
	s.bufferLock.Lock()
	if len(s.buffers) > 0 {
		n = copy(b, s.buffers[0])
		s.buffers[0] = s.buffers[0][n:]
		if len(s.buffers[0]) == 0 {
			s.buffers[0] = nil
			s.buffers = s.buffers[1:]
		}
	}
	s.bufferLock.Unlock()

	if n > 0 {
		s.sess.returnTokens(n)
		return n, nil
	} else if atomic.LoadInt32(&s.rstflag) == 1 {
		_ = s.Close()
		return 0, io.EOF
	}

	select {
	case <-s.chReadEvent:
		goto READ
	case <-deadline:
		return n, errTimeout
	case <-s.die:
		return 0, errors.New(errBrokenPipe)
	}
}
379541
func (t TokenMap) LoadBytes(data []byte) error {
	bytesReader := bytes.NewReader(data)
	bufioReader := bufio.NewReader(bytesReader)
	line, err := bufioReader.ReadString('\n')
	for err == nil {
		t.LoadLine(line)
		line, err = bufioReader.ReadString('\n')
	}
	// if the err was EOF we still need to process the last value
	if err == io.EOF {
		t.LoadLine(line)
		return nil
	}
	return err
}
297947
func (c *ChanReader) Read(out []byte) (int, error) {
	if c.buffer == nil {
		return 0, io.EOF
	}
	n := copy(out, c.buffer)
	c.buffer = c.buffer[n:]
	if len(out) <= len(c.buffer) {
		return n, nil
	} else if n > 0 {
		// We have some data to return, so make the channel read optional
		select {
		case p := <-c.input:
			if p == nil { // Stream was closed
				c.buffer = nil
				if n > 0 {
					return n, nil
				}
				return 0, io.EOF
			}
			n2 := copy(out[n:], p.Data)
			c.buffer = p.Data[n2:]
			return n + n2, nil
		default:
			return n, nil
		}
	}
	var p *StreamChunk
	select {
	case p = <-c.input:
	case <-c.interrupt:
		c.buffer = c.buffer[:0]
		return n, ErrInterrupted
	}
	if p == nil { // Stream was closed
		c.buffer = nil
		return 0, io.EOF
	}
	n2 := copy(out[n:], p.Data)
	c.buffer = p.Data[n2:]
	return n + n2, nil
}