// read at can be called numerous times
// concurrent reads are allowed
// Size() needs to be called synchronously on the LazyChunkReader first
174463
func (r *LazyChunkReader) ReadAt(b []byte, off int64) (read int, err error) {
	metrics.GetOrRegisterCounter("lazychunkreader.readat", nil).Inc(1)

	var sp opentracing.Span
	var cctx context.Context
	cctx, sp = spancontext.StartSpan(
		r.ctx,
		"lcr.read")
	defer sp.Finish()

	defer func() {
		sp.LogFields(
			olog.Int("off", int(off)),
			olog.Int("read", read))
	}()

	// this is correct, a swarm doc cannot be zero length, so no EOF is expected
	if len(b) == 0 {
		return 0, nil
	}
	quitC := make(chan bool)
	size, err := r.Size(cctx, quitC)
	if err != nil {
		log.Debug("lazychunkreader.readat.size", "size", size, "err", err)
		return 0, err
	}

	errC := make(chan error)

	// }
	var treeSize int64
	var depth int
	// calculate depth and max treeSize
	treeSize = r.chunkSize
	for ; treeSize < size; treeSize *= r.branches {
		depth++
	}
	wg := sync.WaitGroup{}
	length := int64(len(b))
	for d := 0; d < r.depth; d++ {
		off *= r.chunkSize
		length *= r.chunkSize
	}
	wg.Add(1)
	go r.join(cctx, b, off, off+length, depth, treeSize/r.branches, r.chunkData, &wg, errC, quitC)
	go func() {
		wg.Wait()
		close(errC)
	}()

	err = <-errC
	if err != nil {
		log.Debug("lazychunkreader.readat.errc", "err", err)
		close(quitC)
		return 0, err
	}
	if off+int64(len(b)) >= size {
		log.Debug("lazychunkreader.readat.return at end", "size", size, "off", off)
		return int(size - off), io.EOF
	}
	log.Debug("lazychunkreader.readat.errc", "buff", len(b))
	return len(b), nil
}
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
}
1230360
func (r *BodyWithCallback) Read(p []byte) (int, error) {
	n, err := r.ReadSeekCloser.Read(p)

	if n > 0 {
		r.readSize += int64(n)

		if (err == nil || err == io.EOF) && r.c != nil {
			err = r.c(r.totalSize, r.readSize, n)
		}
	}
	return n, err
}
233929
func (c *IdleTimingConn) Read(b []byte) (int, error) {
	c.closeMutex.RLock()
	n, err := c.doRead(b)
	c.closeMutex.RUnlock()
	return n, err
}
560406
func (r *translateFileReader) read(p []byte) (n int, err error) {
	sz := r.store.size()

	// Exit if there is no new data.
	if sz < r.offset {
		return 0, fmt.Errorf("pilosa: translate store reader past file size: sz=%d off=%d", sz, r.offset)
	} else if sz == r.offset {
		return 0, nil
	}

	if max := sz - r.offset; max > int64(len(p)) {
		// If p is not large enough to hold a single entry,
		// return an error so the client can increase the
		// size of p and try again.
		return 0, ErrTranslateReadTargetUndersized
	} else if int64(len(p)) > max {
		// Shorten buffer to maximum read size.
		p = p[:max]
	}

	// Read data from file at offset.
	// Limit the number of bytes read to only whole entries.
	n, err = r.file.ReadAt(p, r.offset)
	n = validLogEntriesLen(p[:n])
	r.offset += int64(n)
	return n, err
}
389499
func (m *MemoryAsset) Read(p []byte) (int, error) {
	return m.reader.Read(p)
}
474324
func (acc *Accumulator) Read(p []byte) (n int, err error) {
	copy(p, acc.RandomData(uint(len(p))))
	return len(p), nil
}
1226949
func (cr *s3ChunkedReader) Read(buf []byte) (n int, err error) {
	for {
		switch cr.state {
		case readChunkHeader:
			cr.readS3ChunkHeader()
			// If we're at the end of a chunk.
			if cr.n == 0 && cr.err == io.EOF {
				cr.state = readChunkTrailer
				cr.lastChunk = true
				continue
			}
			if cr.err != nil {
				return 0, cr.err
			}
			cr.state = readChunk
		case readChunkTrailer:
			cr.err = readCRLF(cr.reader)
			if cr.err != nil {
				return 0, errMalformedEncoding
			}
			cr.state = verifyChunk
		case readChunk:
			// There is no more space left in the request buffer.
			if len(buf) == 0 {
				return n, nil
			}
			rbuf := buf
			// The request buffer is larger than the current chunk size.
			// Read only the current chunk from the underlying reader.
			if uint64(len(rbuf)) > cr.n {
				rbuf = rbuf[:cr.n]
			}
			var n0 int
			n0, cr.err = cr.reader.Read(rbuf)
			if cr.err != nil {
				// We have lesser than chunk size advertised in chunkHeader, this is 'unexpected'.
				if cr.err == io.EOF {
					cr.err = io.ErrUnexpectedEOF
				}
				return 0, cr.err
			}

			// Calculate sha256.
			cr.chunkSHA256Writer.Write(rbuf[:n0])
			// Update the bytes read into request buffer so far.
			n += n0
			buf = buf[n0:]
			// Update bytes to be read of the current chunk before verifying chunk's signature.
			cr.n -= uint64(n0)

			// If we're at the end of a chunk.
			if cr.n == 0 {
				cr.state = readChunkTrailer
				continue
			}
		case verifyChunk:
			// Calculate the hashed chunk.
			hashedChunk := hex.EncodeToString(cr.chunkSHA256Writer.Sum(nil))
			// Calculate the chunk signature.
			newSignature := getChunkSignature(cr.cred, cr.seedSignature, cr.region, cr.seedDate, hashedChunk)
			if !compareSignatureV4(cr.chunkSignature, newSignature) {
				// Chunk signature doesn't match we return signature does not match.
				cr.err = errSignatureMismatch
				return 0, cr.err
			}
			// Newly calculated signature becomes the seed for the next chunk
			// this follows the chaining.
			cr.seedSignature = newSignature
			cr.chunkSHA256Writer.Reset()
			if cr.lastChunk {
				cr.state = eofChunk
			} else {
				cr.state = readChunkHeader
			}
		case eofChunk:
			return n, io.EOF
		}
	}
}
432761
func (lr *LockedRand) Read(p []byte) (n int, err error) {
	lr.lk.Lock()
	n, err = lr.r.Read(p)
	lr.lk.Unlock()
	return
}
138280
func (cr *ChainReader) Read(p []byte) (int, error) {
	if len(p) == 0 {
		return 0, nil
	}

	consumed := 0
	defer func() {
		*cr = (*cr)[consumed:]
	}()

	total := 0
	for idx, source := range *cr {
		if source == nil {
			consumed++
			continue
		}

		count, err := source.Read(p)
		total += count
		if err == io.EOF {
			(*cr)[idx] = nil
			consumed++
		} else if err != nil {
			return total, err
		}

		p = p[count:]
		if len(p) == 0 {
			return total, nil
		}
	}
	return total, io.EOF
}
247791
func (oh *ObjectHeader) Read(b []byte) (n int, err error) {
	if len(b) == 0 {
		return 0, nil
	}
	if oh.i >= int64(len(oh.content)) {
		return 0, io.EOF
	}
	n = copy(b, oh.content[oh.i:])
	oh.i += int64(n)
	return
}
729919
func (r *reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	if err != nil {
		return
	}

	err = r.Limiter.Count(n)
	return
}
948199
func (r *randReader) Read(b []byte) (int, error) {
	if len(b) == 0 {
		return 0, nil
	}
	// Grab a unique counter from the reader, while atomically updating the
	// counter so that concurrent callers also end up with unique values.
	counter := atomic.AddUint64(&r.counter, 1)
	counterExtra := atomic.LoadUint64(&r.counterExtra)

	// Increment counterExtra when counter is close to overflowing. We cannot
	// wait until counter == math.MaxUint64 to increment counterExtra, because
	// another goroutine could call Read, overflowing counter to 0 before the
	// first goroutine increments counterExtra. The second goroutine would then
	// be reusing the counter pair (0, 0). Instead, we increment at 1<<63 so
	// that there is little risk of an overflow.
	//
	// There is still a potential overlap near 1<<63, though, because another
	// goroutine could see counter == 1<<63+1 before the first goroutine
	// increments counterExtra. The counter pair (1<<63+1, 1) would then be
	// reused. To prevent this, we also increment at math.MaxUint64. This means
	// that in order for an overlap to occur, 1<<63 goroutine would need to
	// increment counter before the first goroutine increments counterExtra.
	//
	// This strategy means that many counters will be omitted, and that the
	// total space cycle time is potentially as low as 2^126. This is fine
	// however, as the security model merely mandates that no counter is ever
	// used twice.
	if counter == 1<<63 || counter == math.MaxUint64 {
		atomic.AddUint64(&r.counterExtra, 1)
	}

	// Copy the counter and entropy into a separate slice, so that the result
	// may be used in isolation of the other threads. The counter ensures that
	// the result is unique to this thread.
	seed := make([]byte, 64)
	binary.LittleEndian.PutUint64(seed[0:8], counter)
	binary.LittleEndian.PutUint64(seed[8:16], counterExtra)
	// Leave 16 bytes for the inner counter.
	copy(seed[32:], r.entropy[:])

	// Set up an inner counter, that can be incremented to produce unique
	// entropy within this thread.
	n := 0
	innerCounter := uint64(0)
	innerCounterExtra := uint64(0)
	for n < len(b) {
		// Copy in the inner counter values.
		binary.LittleEndian.PutUint64(seed[16:24], innerCounter)
		binary.LittleEndian.PutUint64(seed[24:32], innerCounterExtra)

		// Hash the seed to produce the next set of entropy.
		result := blake2b.Sum512(seed)
		n += copy(b[n:], result[:])

		// Increment the inner counter. Because we are the only thread accessing
		// the counter, we can wait until the first 64 bits have reached their
		// maximum value before incrementing the next 64 bits.
		innerCounter++
		if innerCounter == math.MaxUint64 {
			innerCounterExtra++
		}
	}
	return n, nil
}
478070
func (r *reader) Read(b []byte) (int, error) {
	if len(r.buf) == 0 {
		if r.bufToReturn != nil {
			r.chunkPool.Put(r.bufToReturn)
			r.bufToReturn = nil
		}
		if r.err != nil {
			// Make sure any goroutines are done. Ignore
			// the error since it will just be r.err.
			r.Close()
			return 0, r.err
		}
		resp, ok := <-r.chunkRespc
		if !ok {
			glog.Fatal("chunkRespc channel has been closed without a final error")
		}
		if resp.err != nil {
			r.err = resp.err
		}
		r.buf = resp.chunk
		r.bufToReturn = resp.chunk[:cap(resp.chunk)]
	}
	n := copy(b, r.buf)
	r.buf = r.buf[n:]
	if len(r.buf) == 0 {
		return n, r.err
	}
	return n, nil
}
926016
func (r *Reader) Read(p []byte) (n int, err error) {
	p = p[:r.Limit(len(p), r.limit, r.block)]
	if len(p) > 0 {
		n, err = r.IO(r.Reader.Read(p))
	}
	return
}
531870
func (m *randomReader) Read(b []byte) (int, error) {
	for i := 0; i < len(b); {
		binary.Write(m.b, binary.LittleEndian, m.r.Int63())
		n, _ := m.b.Read(b[i:])
		i += n
	}

	return len(b), nil
}
564432
func (r *reader) Read(b []byte) (int, error) {
	n, err := r.Reader.Read(b)
	r.read += int64(n)
	return n, err
}