// connectNext pops a datanode from the list based on previous failures, and
// connects to it.
2578
func (br *BlockReader) connectNext() error {
	address := br.datanodes.next()

	if br.DialFunc == nil {
		br.DialFunc = (&net.Dialer{}).DialContext
	}

	conn, err := br.DialFunc(context.Background(), "tcp", address)
	if err != nil {
		return err
	}

	err = br.writeBlockReadRequest(conn)
	if err != nil {
		return err
	}

	resp, err := readBlockOpResponse(conn)
	if err != nil {
		return err
	} else if resp.GetStatus() != hdfs.Status_SUCCESS {
		return fmt.Errorf("read failed: %s (%s)", resp.GetStatus().String(), resp.GetMessage())
	}

	readInfo := resp.GetReadOpChecksumInfo()
	checksumInfo := readInfo.GetChecksum()

	var checksumTab *crc32.Table
	checksumType := checksumInfo.GetType()
	switch checksumType {
	case hdfs.ChecksumTypeProto_CHECKSUM_CRC32:
		checksumTab = crc32.IEEETable
	case hdfs.ChecksumTypeProto_CHECKSUM_CRC32C:
		checksumTab = crc32.MakeTable(crc32.Castagnoli)
	default:
		return fmt.Errorf("unsupported checksum type: %d", checksumType)
	}

	chunkSize := int(checksumInfo.GetBytesPerChecksum())
	stream := newBlockReadStream(conn, chunkSize, checksumTab)

	// The read will start aligned to a chunk boundary, so we need to seek forward
	// to the requested offset.
	amountToDiscard := br.Offset - int64(readInfo.GetChunkOffset())
	if amountToDiscard > 0 {
		_, err := io.CopyN(ioutil.Discard, stream, amountToDiscard)
		if err != nil {
			if err == io.EOF {
				err = io.ErrUnexpectedEOF
			}

			conn.Close()
			return err
		}
	}

	br.stream = stream
	br.conn = conn
	err = br.conn.SetDeadline(br.deadline)
	if err != nil {
		return err
	}

	return nil
}
1005751
func (c *Client) next() (*conn, error) {
	// We do round-robin here.
	// TODO(oe) This should be a pluggable strategy, like the Selector in the official clients.
	c.connsMu.Lock()
	defer c.connsMu.Unlock()

	i := 0
	numConns := len(c.conns)
	for {
		i++
		if i > numConns {
			break // we visited all conns: they all seem to be dead
		}
		c.cindex++
		if c.cindex >= numConns {
			c.cindex = 0
		}
		conn := c.conns[c.cindex]
		if !conn.IsDead() {
			return conn, nil
		}
	}

	// We have a deadlock here: All nodes are marked as dead.
	// If sniffing is disabled, connections will never be marked alive again.
	// So we are marking them as alive--if sniffing is disabled.
	// They'll then be picked up in the next call to PerformRequest.
	if !c.snifferEnabled {
		c.errorf("elastic: all %d nodes marked as dead; resurrecting them to prevent deadlock", len(c.conns))
		for _, conn := range c.conns {
			conn.MarkAsAlive()
		}
	}

	// We tried hard, but there is no node available
	return nil, errors.Wrap(ErrNoClient, "no available connection")
}
1246584
func (s *ListNodesOutput) SetNextToken(v string) *ListNodesOutput {
	s.NextToken = &v
	return s
}
668948
func (sc *conn) failConnect(err error) {
	sc.cleanupOnClose(err)
	if sc.nc != nil && sc.ncOwned {
		sc.nc.Close()
	}
}
1297503
func (s *ListIPSetsInput) SetNextToken(v string) *ListIPSetsInput {
	s.NextToken = &v
	return s
}
1306605
func (c *Conn) FetchNext() ([]sqltypes.Value, error) {
	if c.fields == nil {
		// We are already done, and the result was closed.
		return nil, NewSQLError(CRCommandsOutOfSync, SSUnknownSQLState, "no streaming query in progress")
	}

	if len(c.fields) == 0 {
		// We received no fields, so there is no data.
		return nil, nil
	}

	data, err := c.ReadPacket()
	if err != nil {
		return nil, err
	}

	if isEOFPacket(data) {
		// Warnings and status flags are ignored.
		c.fields = nil
		return nil, nil
	} else if isErrorPacket(data) {
		// Error packet.
		return nil, ParseErrorPacket(data)
	}

	// Regular row.
	return c.parseRow(data, c.fields)
}
1276710
func (fp *formatParser) freshNext(i int, r rune) error {
	fp.start = i
	fp.code = (*formatParser).staticCode
	fp.next = (*formatParser).staticNext
	fp.end = (*formatParser).staticEnd
	return nil
}
104815
func (ig *IDGenerator) GetNextID() string {
	return strconv.FormatInt(atomic.AddInt64(&ig.counter, 1), 10)
}
763768
func NewConnection(config ConnectionConfig) (driver.Connection, error) {
	c, err := cluster.NewConnection(config.ConnectionConfig, func(endpoint string) (driver.Connection, error) {
		conn, err := newVSTConnection(endpoint, config)
		if err != nil {
			return nil, driver.WithStack(err)
		}
		return conn, nil
	}, config.Endpoints)
	if err != nil {
		return nil, driver.WithStack(err)
	}
	return c, nil
}
595511
func (it *LinksTo) Next(ctx context.Context) bool {
	for {
		graph.NextLogIn(it)
		it.runstats.Next += 1
		if it.nextIt.Next(ctx) {
			it.runstats.ContainsNext += 1
			it.result = it.nextIt.Result()
			return graph.NextLogOut(it, true)
		}

		// If there's an error in the 'next' iterator, we save it and we're done.
		it.err = it.nextIt.Err()
		if it.err != nil {
			return false
		}

		// Subiterator is empty, get another one
		if !it.primaryIt.Next(ctx) {
			// Possibly save error
			it.err = it.primaryIt.Err()

			// We're out of nodes in our subiterator, so we're done as well.
			return graph.NextLogOut(it, false)
		}
		it.nextIt.Close()
		it.nextIt = it.qs.QuadIterator(it.dir, it.primaryIt.Result())

		// Continue -- return the first in the next set.
	}
}
634292
func NewConnectResults(results ...ConnectResult) ConnectAttemptResults {
	mapResults := make(map[Attempt]ConnectResult)
	for _, r := range results {
		mapResults[r.Attempt] = r
	}
	return mapResults
}
856947
func (it *bytesKeyIterator) GetNext() (key string, rev int64, lastReceived bool) {
	if it.err != nil {
		return "", 0, true
	}
	if it.index >= len(it.keys) {
		if it.cursor == 0 {
			return "", 0, true
		}
		var err error
		it.keys, it.cursor, err = scanKeys(it.db, it.pattern, it.cursor)
		if err != nil {
			it.err = err
			it.db.Errorf("GetNext() failed: %s (pattern %s)", err.Error(), it.pattern)
			return "", 0, true
		}
		if len(it.keys) == 0 {
			return "", 0, it.cursor == 0
		}
		it.index = 0
	}

	key = it.keys[it.index]
	if it.trimPrefix != nil {
		key = it.trimPrefix(key)
	}
	it.index++

	return key, 0, false
}
389201
func (p *Pool) sendNextJobs(n int) error {
	jobs, err := p.getNextJobs(p.config.BatchSize)
	if err != nil {
		return err
	}
	// Send the jobs across the channel, where they will be picked up
	// by exactly one worker
	for _, job := range jobs {
		p.jobs <- job
	}
	return nil
}
394254
func (g *gossipRegistry) connectLoop() {
	// try every second
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-g.done:
			return
		case <-g.options.Context.Done():
			g.Stop()
			return
		case <-ticker.C:
			var addrs []string

			g.RLock()

			// only process if we have a memberlist
			if g.member == nil {
				g.RUnlock()
				continue
			}

			// self
			local := g.member.LocalNode().Address()

			// operate on each member
			for node, action := range g.members {
				switch action {
				// process leave event
				case nodeActionLeave:
					// don't process self
					if node == local {
						continue
					}
					addrs = append(addrs, node)
				}
			}

			g.RUnlock()

			// connect to all the members
			// TODO: only connect to new members
			if len(addrs) > 0 {
				g.connect(addrs)
			}
		}
	}
}
267289
func (r *boltRows) Next(dest []driver.Value) error {
	data, _, err := r.NextNeo()
	if err != nil {
		return err
	}

	for i, item := range data {
		switch item := item.(type) {
		case []interface{}, map[string]interface{}, graph.Node, graph.Path, graph.Relationship, graph.UnboundRelationship:
			dest[i], err = encoding.Marshal(item)
			if err != nil {
				return err
			}
		default:
			dest[i], err = driver.DefaultParameterConverter.ConvertValue(item)
			if err != nil {
				return err
			}
		}
	}

	return nil

}
187147
func UpdateBlockNext(db SqlExecutor, blockDbID uint64, next string) error {
	res, err := db.Exec(internal.UpdateBlockNext, blockDbID, next)
	if err != nil {
		return err
	}
	numRows, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if numRows != 1 {
		return fmt.Errorf("%s (%d)", notOneRowErrMsg, numRows)
	}
	return nil
}
1163245
func (r *FlatChain) handleNext(c *Context) {
	if r.next != nil {
		r.next.HandleContext(c)
	}
}