// ReadFrame decodes the next JSON object in the stream, or returns an error. The returned
// byte slice will be modified the next time ReadFrame is invoked and should not be altered.
176998
func (r *jsonFrameReader) Read(data []byte) (int, error) {
	// Return whatever remaining data exists from an in progress frame
	if n := len(r.remaining); n > 0 {
		if n <= len(data) {
			data = append(data[0:0], r.remaining...)
			r.remaining = nil
			return n, nil
		}

		n = len(data)
		data = append(data[0:0], r.remaining[:n]...)
		r.remaining = r.remaining[n:]
		return n, io.ErrShortBuffer
	}

	// RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see
	// data written to data, or be larger than data and a different array.
	n := len(data)
	m := json.RawMessage(data[:0])
	if err := r.decoder.Decode(&m); err != nil {
		return 0, err
	}

	// If capacity of data is less than length of the message, decoder will allocate a new slice
	// and set m to it, which means we need to copy the partial result back into data and preserve
	// the remaining result for subsequent reads.
	if len(m) > n {
		data = append(data[0:0], m[:n]...)
		r.remaining = m[n:]
		return n, io.ErrShortBuffer
	}
	return len(m), nil
}
481131
func (m *Memberlist) readStream(conn net.Conn) (messageType, io.Reader, *codec.Decoder, error) {
	// Created a buffered reader
	var bufConn io.Reader = bufio.NewReader(conn)

	// Read the message type
	buf := [1]byte{0}
	if _, err := bufConn.Read(buf[:]); err != nil {
		return 0, nil, nil, err
	}
	msgType := messageType(buf[0])

	// Check if the message is encrypted
	if msgType == encryptMsg {
		if !m.config.EncryptionEnabled() {
			return 0, nil, nil,
				fmt.Errorf("Remote state is encrypted and encryption is not configured")
		}

		plain, err := m.decryptRemoteState(bufConn)
		if err != nil {
			return 0, nil, nil, err
		}

		// Reset message type and bufConn
		msgType = messageType(plain[0])
		bufConn = bytes.NewReader(plain[1:])
	} else if m.config.EncryptionEnabled() && m.config.GossipVerifyIncoming {
		return 0, nil, nil,
			fmt.Errorf("Encryption is configured but remote state is not encrypted")
	}

	// Get the msgPack decoders
	hd := codec.MsgpackHandle{}
	dec := codec.NewDecoder(bufConn, &hd)

	// Check if we have a compressed message
	if msgType == compressMsg {
		var c compress
		if err := dec.Decode(&c); err != nil {
			return 0, nil, nil, err
		}
		decomp, err := decompressBuffer(&c)
		if err != nil {
			return 0, nil, nil, err
		}

		// Reset the message type
		msgType = messageType(decomp[0])

		// Create a new bufConn
		bufConn = bytes.NewReader(decomp[1:])

		// Create a new decoder
		dec = codec.NewDecoder(bufConn, &hd)
	}

	return msgType, bufConn, dec, nil
}
242198
func (s *Socket) ReadJSON(v interface{}) (err error) {
	_, r, err := s.NextReader()
	if err != nil {
		return err
	}
	return codec.NewDecoder(r, &jh).Decode(v)
}
1056434
func (b *Buffer) ReadBytes(p []byte) {
	copy(p, b.Consume(len(p)))
}
1234565
func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) {
	if r.remaining <= 0 {
		header := [4]byte{}
		n, err := io.ReadAtLeast(r.r, header[:4], 4)
		if err != nil {
			return 0, err
		}
		if n != 4 {
			return 0, io.ErrUnexpectedEOF
		}
		frameLength := int(binary.BigEndian.Uint32(header[:]))
		r.remaining = frameLength
	}

	expect := r.remaining
	max := expect
	if max > len(data) {
		max = len(data)
	}
	n, err := io.ReadAtLeast(r.r, data[:max], int(max))
	r.remaining -= n
	if err == io.ErrShortBuffer || r.remaining > 0 {
		return n, io.ErrShortBuffer
	}
	if err != nil {
		return n, err
	}
	if n != expect {
		return n, io.ErrUnexpectedEOF
	}

	return n, nil
}
1181010
func (jl *jsonLedger) readBlock(number uint64) (*cb.Block, bool) {
	name := jl.blockFilename(number)

	// In case of ongoing write, reading the block file may result in `unexpected EOF` error.
	// Therefore, we use file mutex here to prevent this race condition.
	fileLock.Lock()
	defer fileLock.Unlock()

	file, err := os.Open(name)
	if err == nil {
		defer file.Close()
		block := &cb.Block{}
		err = jsonpb.Unmarshal(file, block)
		if err != nil {
			return nil, true
		}
		logger.Debugf("Read block %d", block.Header.Number)
		return block, true
	}
	return nil, false
}
924453
func (r *Reader) NextFrame() (hdr ws.Header, err error) {
	hdr, err = ws.ReadHeader(r.Source)
	if err == io.EOF && r.fragmented() {
		// If we are in fragmented state EOF means that is was totally
		// unexpected.
		//
		// NOTE: This is necessary to prevent callers such that
		// ioutil.ReadAll to receive some amount of bytes without an error.
		// ReadAll() ignores an io.EOF error, thus caller may think that
		// whole message fetched, but actually only part of it.
		err = io.ErrUnexpectedEOF
	}
	if err == nil && !r.SkipHeaderCheck {
		err = ws.CheckHeader(hdr, r.State)
	}
	if err != nil {
		return hdr, err
	}

	// Save raw reader to use it on discarding frame without ciphering and
	// other streaming checks.
	r.raw = io.LimitedReader{r.Source, hdr.Length}

	frame := io.Reader(&r.raw)
	if hdr.Masked {
		frame = NewCipherReader(frame, hdr.Mask)
	}
	if r.fragmented() {
		if hdr.OpCode.IsControl() {
			if cb := r.OnIntermediate; cb != nil {
				err = cb(hdr, frame)
			}
			if err == nil {
				// Ensure that src is empty.
				_, err = io.Copy(ioutil.Discard, &r.raw)
			}
			return
		}
	} else {
		r.opCode = hdr.OpCode
	}
	if r.CheckUTF8 && (hdr.OpCode == ws.OpText || (r.fragmented() && r.opCode == ws.OpText)) {
		r.utf8.Source = frame
		frame = &r.utf8
	}

	// Save reader with ciphering and other streaming checks.
	r.frame = frame

	if hdr.OpCode == ws.OpContinuation {
		if cb := r.OnContinuation; cb != nil {
			err = cb(hdr, frame)
		}
	}

	if hdr.Fin {
		r.State = r.State.Clear(ws.StateFragmented)
	} else {
		r.State = r.State.Set(ws.StateFragmented)
	}

	return
}
52326
func DecodeFrame(r io.Reader) (frame []byte, err error) {
	var size int16
	err = binary.Read(r, binary.LittleEndian, &size)
	if err != nil {
		return
	}

	if size < 0 {
		return nil, ErrNegativeFrameSize
	}

	frame = make([]byte, size)
	err = binary.Read(r, binary.LittleEndian, &frame)
	return
}
1318893
func (r *streamResponseBodyReader) readNext() ([]byte, error) {
	// Discard all the bytes from buf and continue to use the allocated memory
	// space for reading the next message.
	r.buf.Truncate(0)
	for {
		// Twitter stream messages are separated with "\r\n", and a valid
		// message may sometimes contain '\n' in the middle.
		// bufio.Reader.Read() can accept one byte delimiter only, so we need to
		// first break out each line on '\n' and then check whether the line ends
		// with "\r\n" to find message boundaries.
		// https://dev.twitter.com/streaming/overview/processing
		line, err := r.reader.ReadBytes('\n')
		// Non-EOF error should be propagated to callers immediately.
		if err != nil && err != io.EOF {
			return nil, err
		}
		// EOF error means that we reached the end of the stream body before finding
		// delimiter '\n'. If "line" is empty, it means the reader didn't read any
		// data from the stream before reaching EOF and there's nothing to append to
		// buf.
		if err == io.EOF && len(line) == 0 {
			// if buf has no data, propagate io.EOF to callers and let them know that
			// we've finished processing the stream.
			if r.buf.Len() == 0 {
				return nil, err
			}
			// Otherwise, we still have a remaining stream message to return.
			break
		}
		// If the line ends with "\r\n", it's the end of one stream message data.
		if bytes.HasSuffix(line, []byte("\r\n")) {
			// reader.ReadBytes() returns a slice including the delimiter itself, so
			// we need to trim '\n' as well as '\r' from the end of the slice.
			r.buf.Write(bytes.TrimRight(line, "\r\n"))
			break
		}
		// Otherwise, the line is not the end of a stream message, so we append
		// the line to buf and continue to scan lines.
		r.buf.Write(line)
	}

	// Get the stream message bytes from buf. Not that Bytes() won't mark the
	// returned data as "read", and we need to explicitly call Truncate(0) to
	// discard from buf before writing the next stream message to buf.
	return r.buf.Bytes(), nil
}
1211253
func readInitialStreamError(ws base.Stream) error {
	// We can use bufio here because the websocket guarantees that a
	// single read will not read more than a single frame; there is
	// no guarantee that a single read might not read less than the
	// whole frame though, so using a single Read call is not
	// correct. By using ReadSlice rather than ReadBytes, we
	// guarantee that the error can't be too big (>4096 bytes).
	messageType, reader, err := ws.NextReader()
	if err != nil {
		return errors.Annotate(err, "unable to get reader")
	}
	if messageType != websocket.TextMessage {
		return errors.Errorf("unexpected message type %v", messageType)
	}
	line, err := bufio.NewReader(reader).ReadSlice('\n')
	if err != nil {
		return errors.Annotate(err, "unable to read initial response")
	}
	var errResult params.ErrorResult
	if err := json.Unmarshal(line, &errResult); err != nil {
		return errors.Annotate(err, "unable to unmarshal initial response")
	}
	if errResult.Error != nil {
		return errResult.Error
	}
	return nil
}
949865
func (b *Builder) ReadByte() (c byte, err error) {
	b.lastRead = opInvalid
	if b.off >= len(b.buf) {
		// Buffer is empty, reset to recover space.
		b.Truncate(0)
		return 0, io.EOF
	}
	c = b.buf[b.off]
	b.off++
	b.lastRead = opRead
	return c, nil
}
485105
func (r *Reader) ReadObject() (*Object, error) {
	object := &Object{[]*ObjectHeader{}}
	for {
		p, err := r.NextPart()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		var b bytes.Buffer

		if _, err := io.Copy(&b, p); err != nil {
			return nil, err
		}

		oh := &ObjectHeader{
			content: b.Bytes(),
		}
		if p.Root {
			object.Values = append([]*ObjectHeader{oh}, object.Values...)
		} else {
			object.Values = append(object.Values, oh)
		}

	}

	return object, nil
}
33508
func ReadJSON(resp *http.Response, out interface{}) error {
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}

		return fmt.Errorf("StatusCode: %d, Body: %s", resp.StatusCode, body)
	}

	if out == nil {
		io.Copy(ioutil.Discard, resp.Body)
		return nil
	}

	decoder := json.NewDecoder(resp.Body)
	return decoder.Decode(out)
}
671541
func readJson(resp *http.Response, result interface{}) (err error) {
	defer drainAndClose(resp.Body, &err)
	decoder := json.NewDecoder(resp.Body)
	return decoder.Decode(result)
}
1158832
func (d *Decoder) decodeFrame3() error {
	if err := d.decodeSideInformation3(); err != nil {
		return err
	}

	if err := d.updateReservoir3(); err != nil {
		return err
	}

	// If window_switching_flag == 1 and block_type == 0, we only report the
	// error after reading the side information through and updating the bit
	// reservoir, so the decoder is more likely to stay in sync.
	for gr := 0; gr < 2; gr++ {
		for ch := 0; ch < d.nChannels; ch++ {
			if d.windowSwitchingFlag[gr][ch] == 1 && d.blockType[gr][ch] == 0 {
				return MalformedStream("block_type == 0")
			}
		}
	}

	if err := d.decodeMainData3(); err != nil {
		return err
	}

	// Parsing done, now do the math:
	d.dequantize3()
	d.stereo3()
	d.reorder3()
	d.antialias3()
	d.imdctFilter3()

	return nil
}
469530
func (d *llvmSymbolizer) readFrame() (plugin.Frame, bool) {
	funcname, err := d.readString()
	if err != nil {
		return plugin.Frame{}, true
	}

	switch funcname {
	case "":
		return plugin.Frame{}, true
	case "??":
		funcname = ""
	}

	fileline, err := d.readString()
	if err != nil {
		return plugin.Frame{Func: funcname}, true
	}

	linenumber := 0
	if fileline == "??:0" {
		fileline = ""
	} else {
		switch split := strings.Split(fileline, ":"); len(split) {
		case 1:
			// filename
			fileline = split[0]
		case 2, 3:
			// filename:line , or
			// filename:line:disc , or
			fileline = split[0]
			if line, err := strconv.Atoi(split[1]); err == nil {
				linenumber = line
			}
		default:
			// Unrecognized, ignore
		}
	}

	return plugin.Frame{Func: funcname, File: fileline, Line: linenumber}, false
}
1077585
func (m *Message) ReadJSON(v interface{}) error {
	return json.Unmarshal(m.Body, v)
}