// Copy a DriverNetwork struct. If it is nil, nil is returned.
177494
func (d *DriverNetwork) Copy() *DriverNetwork {
	if d == nil {
		return nil
	}
	pm := make(map[string]int, len(d.PortMap))
	for k, v := range d.PortMap {
		pm[k] = v
	}
	return &DriverNetwork{
		PortMap:       pm,
		IP:            d.IP,
		AutoAdvertise: d.AutoAdvertise,
	}
}
1006756
func (in *NetworkControllerConfig) DeepCopy() *NetworkControllerConfig {
	if in == nil {
		return nil
	}
	out := new(NetworkControllerConfig)
	in.DeepCopyInto(out)
	return out
}
1205865
func (s *LocalState) Copy() *LocalState {
	if s == nil {
		return nil
	}

	// Create a copy
	c := &LocalState{
		Hooks:         make(map[string]*HookState, len(s.Hooks)),
		DriverNetwork: s.DriverNetwork.Copy(),
		TaskHandle:    s.TaskHandle.Copy(),
	}

	// Copy the hook state
	for h, state := range s.Hooks {
		c.Hooks[h] = state.Copy()
	}

	return c
}
1179295
func (v ByteView) Copy(dest []byte) int {
	if v.b != nil {
		return copy(dest, v.b)
	}
	return copy(dest, v.s)
}
1103622
func (scw *LegacySplitCloneWorker) copy(ctx context.Context) error {
	scw.setState(WorkerStateCloneOffline)
	start := time.Now()
	defer func() {
		statsStateDurationsNs.Set(string(WorkerStateCloneOffline), time.Since(start).Nanoseconds())
	}()

	// get source schema from the first shard
	// TODO(alainjobart): for now, we assume the schema is compatible
	// on all source shards. Furthermore, we estimate the number of rows
	// in each source shard for each table to be about the same
	// (rowCount is used to estimate an ETA)
	shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
	sourceSchemaDefinition, err := scw.wr.GetSchema(shortCtx, scw.sourceAliases[0], nil, scw.excludeTables, false /* includeViews */)
	cancel()
	if err != nil {
		return vterrors.Wrapf(err, "cannot get schema from source %v", topoproto.TabletAliasString(scw.sourceAliases[0]))
	}
	if len(sourceSchemaDefinition.TableDefinitions) == 0 {
		return fmt.Errorf("no tables matching the table filter in tablet %v", topoproto.TabletAliasString(scw.sourceAliases[0]))
	}
	for _, td := range sourceSchemaDefinition.TableDefinitions {
		if len(td.Columns) == 0 {
			return fmt.Errorf("schema for table %v has no columns", td.Name)
		}
	}
	scw.wr.Logger().Infof("Source tablet 0 has %v tables to copy", len(sourceSchemaDefinition.TableDefinitions))
	scw.tableStatusList.initialize(sourceSchemaDefinition)

	// In parallel, setup the channels to send SQL data chunks to for each destination tablet:
	//
	// mu protects the context for cancelation, and firstError
	mu := sync.Mutex{}
	var firstError error

	ctx, cancelCopy := context.WithCancel(ctx)
	processError := func(format string, args ...interface{}) {
		scw.wr.Logger().Errorf(format, args...)
		mu.Lock()
		if firstError == nil {
			firstError = fmt.Errorf(format, args...)
			cancelCopy()
		}
		mu.Unlock()
	}

	insertChannels := make([]chan string, len(scw.destinationShards))
	destinationWaitGroup := sync.WaitGroup{}
	for shardIndex, si := range scw.destinationShards {
		// we create one channel per destination tablet.  It
		// is sized to have a buffer of a maximum of
		// destinationWriterCount * 2 items, to hopefully
		// always have data. We then have
		// destinationWriterCount go routines reading from it.
		insertChannels[shardIndex] = make(chan string, scw.destinationWriterCount*2)

		go func(keyspace, shard string, insertChannel chan string) {
			for j := 0; j < scw.destinationWriterCount; j++ {
				destinationWaitGroup.Add(1)
				go func(threadID int) {
					defer destinationWaitGroup.Done()

					keyspaceAndShard := topoproto.KeyspaceShardString(keyspace, shard)
					throttler := scw.destinationThrottlers[keyspaceAndShard]
					defer throttler.ThreadFinished(threadID)

					executor := newExecutor(scw.wr, scw.tsc, throttler, keyspace, shard, threadID)
					if err := executor.fetchLoop(ctx, insertChannel); err != nil {
						processError("executer.FetchLoop failed: %v", err)
					}
				}(j)
			}
		}(si.Keyspace(), si.ShardName(), insertChannels[shardIndex])
	}

	// read the vschema if needed
	var keyspaceSchema *vindexes.KeyspaceSchema
	if *useV3ReshardingMode {
		kschema, err := scw.wr.TopoServer().GetVSchema(ctx, scw.keyspace)
		if err != nil {
			return vterrors.Wrapf(err, "cannot load VSchema for keyspace %v", scw.keyspace)
		}
		if kschema == nil {
			return fmt.Errorf("no VSchema for keyspace %v", scw.keyspace)
		}

		keyspaceSchema, err = vindexes.BuildKeyspaceSchema(kschema, scw.keyspace)
		if err != nil {
			return vterrors.Wrapf(err, "cannot build vschema for keyspace %v", scw.keyspace)
		}
	}

	// Now for each table, read data chunks and send them to all
	// insertChannels
	sourceWaitGroup := sync.WaitGroup{}
	for shardIndex := range scw.sourceShards {
		sema := sync2.NewSemaphore(scw.sourceReaderCount, 0)
		for tableIndex, td := range sourceSchemaDefinition.TableDefinitions {
			var keyResolver keyspaceIDResolver
			if *useV3ReshardingMode {
				keyResolver, err = newV3ResolverFromTableDefinition(keyspaceSchema, td)
				if err != nil {
					return vterrors.Wrapf(err, "cannot resolve v3 sharding keys for keyspace %v", scw.keyspace)
				}
			} else {
				keyResolver, err = newV2Resolver(scw.keyspaceInfo, td)
				if err != nil {
					return vterrors.Wrapf(err, "cannot resolve sharding keys for keyspace %v", scw.keyspace)
				}
			}
			rowSplitter := NewRowSplitter(scw.destinationShards, keyResolver)

			chunks, err := generateChunks(ctx, scw.wr, scw.sourceTablets[shardIndex], td, scw.sourceReaderCount, defaultMinRowsPerChunk)
			if err != nil {
				return err
			}
			scw.tableStatusList.setThreadCount(tableIndex, len(chunks)-1)

			for _, c := range chunks {
				sourceWaitGroup.Add(1)
				go func(td *tabletmanagerdatapb.TableDefinition, shardIndex, tableIndex int, chunk chunk) {
					defer sourceWaitGroup.Done()

					sema.Acquire()
					defer sema.Release()

					scw.tableStatusList.threadStarted(tableIndex)
					defer scw.tableStatusList.threadDone(tableIndex)

					// Start streaming from the source tablets.
					tp := newSingleTabletProvider(ctx, scw.wr.TopoServer(), scw.sourceAliases[shardIndex])
					rr, err := NewRestartableResultReader(ctx, scw.wr.Logger(), tp, td, chunk, false /* allowMultipleRetries */)
					if err != nil {
						processError("NewRestartableResultReader failed: %v", err)
						return
					}
					defer rr.Close(ctx)

					// process the data
					dbNames := make([]string, len(scw.destinationShards))
					for i, si := range scw.destinationShards {
						keyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName())
						dbNames[i] = scw.destinationDbNames[keyspaceAndShard]
					}
					if err := scw.processData(ctx, dbNames, td, tableIndex, rr, rowSplitter, insertChannels, scw.destinationPackCount); err != nil {
						processError("processData failed: %v", err)
					}
				}(td, shardIndex, tableIndex, c)
			}
		}
	}
	sourceWaitGroup.Wait()

	for shardIndex := range scw.destinationShards {
		close(insertChannels[shardIndex])
	}
	destinationWaitGroup.Wait()
	if firstError != nil {
		return firstError
	}

	sourcePositions := make([]string, len(scw.sourceShards))
	// get the current position from the sources
	for shardIndex := range scw.sourceShards {
		shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout)
		status, err := scw.wr.TabletManagerClient().SlaveStatus(shortCtx, scw.sourceTablets[shardIndex])
		cancel()
		if err != nil {
			return err
		}
		sourcePositions[shardIndex] = status.Position
	}

	for _, si := range scw.destinationShards {
		keyspaceAndShard := topoproto.KeyspaceShardString(si.Keyspace(), si.ShardName())
		dbName := scw.destinationDbNames[keyspaceAndShard]

		destinationWaitGroup.Add(1)
		go func(keyspace, shard string, kr *topodatapb.KeyRange) {
			defer destinationWaitGroup.Done()
			scw.wr.Logger().Infof("Making and populating vreplication table for %v/%v", keyspace, shard)

			exc := newExecutor(scw.wr, scw.tsc, nil, keyspace, shard, 0)
			for shardIndex, src := range scw.sourceShards {
				bls := &binlogdatapb.BinlogSource{
					Keyspace: src.Keyspace(),
					Shard:    src.ShardName(),
					KeyRange: kr,
				}
				qr, err := exc.vreplicationExec(ctx, binlogplayer.CreateVReplication("LegacySplitClone", bls, sourcePositions[shardIndex], scw.maxTPS, throttler.ReplicationLagModuleDisabled, time.Now().Unix(), dbName))
				if err != nil {
					processError("vreplication queries failed: %v", err)
					break
				} else {
					scw.wr.Logger().Infof("Created replication for tablet %v/%v: %v, db: %v, pos: %v, uid: %v", keyspace, shard, bls, dbName, sourcePositions[shardIndex], uint32(qr.InsertID))
				}
				if err := scw.wr.SourceShardAdd(ctx, keyspace, shard, uint32(qr.InsertID), src.Keyspace(), src.ShardName(), src.Shard.KeyRange, nil); err != nil {
					processError("could not add source shard: %v", err)
					break
				}
			}
			// refreshState will cause the destination to become non-serving because
			// it's now participating in the resharding workflow.
			if err := exc.refreshState(ctx); err != nil {
				processError("RefreshState failed on tablet %v/%v: %v", keyspace, shard, err)
			}
		}(si.Keyspace(), si.ShardName(), si.KeyRange)
	}
	destinationWaitGroup.Wait()
	return firstError
}
356565
func (e *Env) Copy() *Env {
	e.Lock()
	defer e.Unlock()
	copy := Env{
		name:     e.name,
		env:      make(map[string]reflect.Value),
		typ:      make(map[string]reflect.Type),
		parent:   e.parent,
		external: e.external,
	}
	for name, value := range e.env {
		copy.env[name] = value
	}
	for name, typ := range e.typ {
		copy.typ[name] = typ
	}
	return &copy
}
673683
func (m *networkMechanismManager) Driver() (NetworkDriver, error) {
	m.drvLock.RLock()
	defer m.drvLock.RUnlock()

	if m.drv == nil {
		log.ErrorLog("network/NETWORK_DRIVER",
			"Network layer driver is not itialized")
		return nil, ErrNetworkNotInitialized
	}

	return m.drv, nil
}
1140549
func (s *State) Copy() *State {
	taskStates := make(map[string]*structs.TaskState, len(s.TaskStates))
	for k, v := range s.TaskStates {
		taskStates[k] = v.Copy()
	}
	return &State{
		ClientStatus:      s.ClientStatus,
		ClientDescription: s.ClientDescription,
		DeploymentStatus:  s.DeploymentStatus.Copy(),
		TaskStates:        taskStates,
	}
}
288401
func (b *batchNodeUpdates) updateNodeFromDriver(driver string, info *structs.DriverInfo) {
	b.driversMu.Lock()
	defer b.driversMu.Unlock()
	if b.driversBatched {
		b.driverCB(driver, info)
		return
	}

	b.drivers[driver] = info
}
465889
func (g *MutableDirectedGraph) Copy() *MutableDirectedGraph {
	newGraph := NewMutableDirectedGraph(g.rootNodeNames)

	// copy nodes
	for _, n := range g.Nodes() {
		newNode, ok := n.(*Node)
		if !ok {
			continue
		}

		if err := newGraph.AddNode(newNode); err != nil {
			// this should never happen: the only error that could occur is a node name collision,
			// which would imply that the original graph that we are copying had node-name collisions.
			panic(fmt.Errorf("unexpected error while copying graph: %v", err))
		}
	}

	// copy edges
	for _, n := range g.Nodes() {
		node, ok := n.(*Node)
		if !ok {
			continue
		}

		if _, exists := newGraph.NodeByName(node.UniqueName); !exists {
			continue
		}

		from := g.From(n)
		for _, to := range from {
			if newGraph.HasEdgeFromTo(n, to) {
				continue
			}

			newGraph.SetEdge(simple.Edge{F: n, T: to})
		}
	}

	return newGraph
}
184258
func (c Config) Copy() (m Map) {
	m = make(Map)
	for k, v := range c.root {
		m[k] = v
	}
	return
}
836295
func (c *Client) updateNodeFromDriver(name string, info *structs.DriverInfo) {
	c.configLock.Lock()
	defer c.configLock.Unlock()

	if c.updateNodeFromDriverLocked(name, info) {
		c.config.Node.Drivers[name] = info
		if c.config.Node.Drivers[name].UpdateTime.IsZero() {
			c.config.Node.Drivers[name].UpdateTime = time.Now()
		}
		c.updateNodeLocked()
	}
}
1114017
func copyHeaders(destination http.Header, source *http.Header) {
	for k, v := range *source {
		vClone := make([]string, len(v))
		copy(vClone, v)
		destination[k] = vClone
	}
}
659480
func (nm *NickMode) Copy() *NickMode {
	if nm == nil {
		return nil
	}
	n := *nm
	return &n
}
710822
func Copy(header http.Header) http.Header {
	h := make(http.Header)
	for k, vs := range header {
		h[k] = vs
	}
	return h
}
1249180
func (tc *clientTransportCredentials) Clone() credentials.TransportCredentials {
	return NewClientCredentials(tc.roots, tc.clients, tc.hostOverride)
}
1304387
func Copy(src reflect.Value) reflect.Value {
	d := make(deepcopy)
	return d.copy(src)
}