// MakeNetworkReaderFrom is a helper to transform NetworkPacketReader to io.ReaderFrom.
1220
func MakeNetworkReaderFrom(rp NetworkPacketReader, p *NetworkPacket) io.ReaderFrom {
	return ioutil.ReaderFromFunc(func(r io.Reader) (int64, error) {
		packet, err := rp.ReadPacket(r)
		if err != nil {
			return 0, err
		}

		*p = *packet
		return packet.Len, nil
	})
}
1307833
func (d *OvsDriver) CreateNetwork(id string) error {
	cfgNw := mastercfg.CfgNetworkState{}
	cfgNw.StateDriver = d.oper.StateDriver
	err := cfgNw.Read(id)
	if err != nil {
		log.Errorf("Failed to read net %s \n", cfgNw.ID)
		return err
	}
	log.Infof("create net %+v \n", cfgNw)

	// Find the switch based on network type
	var sw *OvsSwitch
	if cfgNw.PktTagType == "vxlan" {
		sw = d.switchDb["vxlan"]
	} else {
		sw = d.switchDb["vlan"]
	}

	return sw.CreateNetwork(uint16(cfgNw.PktTag), uint32(cfgNw.ExtPktTag), cfgNw.Gateway, cfgNw.Tenant)
}
880029
func MakePayloadHeader(ch *cb.ChannelHeader, sh *cb.SignatureHeader) *cb.Header {
	return &cb.Header{
		ChannelHeader:   MarshalOrPanic(ch),
		SignatureHeader: MarshalOrPanic(sh),
	}
}
429902
func (p *Port) ReadFrom(r io.Reader) (int64, error) {
	p.HWAddr = make(net.HardwareAddr, 6)
	var name [portNameLen]byte

	n, err := encoding.ReadFrom(r, &p.PortNo, &defaultPad4, &p.HWAddr,
		&defaultPad2, &name, &p.Config, &p.State, &p.Curr, &p.Advertised,
		&p.Supported, &p.Peer, &p.CurrSpeed, &p.MaxSpeed,
	)

	p.Name = string(name[:])
	return n, err
}
989700
func JSONReader(v interface{}) (r io.Reader, err error) {
	buf := new(bytes.Buffer)
	err = json.NewEncoder(buf).Encode(v)
	r = bytes.NewReader(buf.Bytes())
	return
}
1047535
func MakeNodeNtfnHandlers() (*rpcclient.NotificationHandlers, *collectionQueue) {
	go superQueue()
	// ReorgSignaler must be started after creating the RPC client.
	return &rpcclient.NotificationHandlers{
		// TODO: considering using txns [][]byte to save on downstream RPCs.
		OnBlockConnected: func(blockHeaderSerialized []byte, _ [][]byte) {
			blockHeader := new(wire.BlockHeader)
			err := blockHeader.FromBytes(blockHeaderSerialized)
			if err != nil {
				log.Error("Failed to deserialize blockHeader in new block notification: "+
					"%v", err)
				return
			}
			height := int32(blockHeader.Height)
			hash := blockHeader.BlockHash()
			prevHash := blockHeader.PrevBlock // to ensure this is the next block

			log.Tracef("OnBlockConnected: %d / %v (previous: %v)", height, hash, prevHash)

			// Queue this block.
			anyQueue <- &blockHashHeight{
				hash:     hash,
				height:   int64(height),
				prevHash: prevHash,
			}
		},
		OnBlockDisconnected: func(blockHeaderSerialized []byte) {
			blockHeader := new(wire.BlockHeader)
			err := blockHeader.FromBytes(blockHeaderSerialized)
			if err != nil {
				log.Error("Failed to deserialize blockHeader in block disconnect notification: "+
					"%v", err)
				return
			}
			height := int32(blockHeader.Height)
			hash := blockHeader.BlockHash()

			log.Tracef("OnBlockDisconnected: %d / %v", height, hash)
		},
		OnReorganization: func(oldHash *chainhash.Hash, oldHeight int32,
			newHash *chainhash.Hash, newHeight int32) {
			log.Tracef("OnReorganization: %d / %s --> %d / %s",
				oldHeight, oldHash, newHeight, newHash)

			// Queue sending the details of this reorganization to each
			// package's reorg handler. This is not blocking.
			anyQueue <- ReorgData{
				OldChainHead:   *oldHash,
				OldChainHeight: oldHeight,
				NewChainHead:   *newHash,
				NewChainHeight: newHeight,
				WG:             new(sync.WaitGroup),
			}
		},

		// block height and hash are unused by OnWinningTickets.
		OnWinningTickets: func(_ *chainhash.Hash, _ int64, tickets []*chainhash.Hash) {
			var txstr []string
			for _, t := range tickets {
				txstr = append(txstr, t.String())
			}
			log.Tracef("Winning tickets: %v", strings.Join(txstr, ", "))
		},

		// Maturing tickets (maturing or mined?  clarify before use!).
		OnNewTickets: func(_ *chainhash.Hash, _ int64, _ int64, tickets []*chainhash.Hash) {
			for _, tick := range tickets {
				log.Tracef("Mined new ticket: %v", tick.String())
			}
		},

		// OnRelevantTxAccepted is invoked when a transaction containing a
		// registered address is inserted into mempool.
		OnRelevantTxAccepted: func(transaction []byte) {
			rec, err := udb.NewTxRecord(transaction, time.Now())
			if err != nil {
				return
			}
			tx := dcrutil.NewTx(&rec.MsgTx)
			txHash := rec.Hash
			select {
			case NtfnChans.RelevantTxMempoolChan <- tx:
				log.Debugf("Detected transaction %v in mempool containing registered address.",
					txHash.String())
			default:
			}
		},

		// OnTxAcceptedVerbose is invoked same as OnTxAccepted but is used here
		// for the mempool monitors to avoid an extra call to dcrd for
		// the tx details
		OnTxAcceptedVerbose: func(txDetails *dcrjson.TxRawResult) {
			// Current UNIX time to assign the new transaction.
			now := time.Now().Unix()

			select {
			case NtfnChans.InsightNewTxChan <- &insight.NewTx{
				Hex:   txDetails.Hex,
				Vouts: txDetails.Vout,
			}:
			default:
				if NtfnChans.InsightNewTxChan != nil {
					log.Warn("InsightNewTxChan buffer full!")
				}
			}

			// Patch txDetails.Time, which is 0, with current time.
			txDetails.Time = now

			select {
			case NtfnChans.NewTxChan <- txDetails:
			default:
				log.Warn("NewTxChan buffer full!")
			}
		},
	}, blockQueue
}
847138
func (t *TablePropApplySetField) ReadFrom(r io.Reader) (int64, error) {
	return readTablePropXM(r, &t.Fields, &t.Miss)
}
747262
func (a *AsyncConfig) ReadFrom(r io.Reader) (int64, error) {
	return encoding.ReadFrom(r, &a.PacketInMask,
		&a.PortStatusMask, &a.FlowRemovedMask)
}
36437
func NewReaderFromMap(o interface{}) *Reader {
	options := gojsonld.NewOptions("")
	options.DocumentLoader = gojsonld.NewDocumentLoader()
	data, err := gojsonld.ToRDF(o, options)
	if err != nil {
		return &Reader{err: err}
	}
	return &Reader{
		graphs: data.Graphs,
	}
}
964757
func (e *endpoint) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView) {
	if atomic.LoadUint32(&LogPackets) == 1 && e.file == nil {
		logPacket("recv", protocol, vv.First())
	}
	if e.file != nil && atomic.LoadUint32(&LogPacketsToFile) == 1 {
		vs := vv.Views()
		length := vv.Size()
		if length > int(e.maxPCAPLen) {
			length = int(e.maxPCAPLen)
		}

		buf := bytes.NewBuffer(make([]byte, 0, pcapPacketHeaderLen+length))
		if err := binary.Write(buf, binary.BigEndian, newPCAPPacketHeader(uint32(length), uint32(vv.Size()))); err != nil {
			panic(err)
		}
		for _, v := range vs {
			if length == 0 {
				break
			}
			if len(v) > length {
				v = v[:length]
			}
			if _, err := buf.Write([]byte(v)); err != nil {
				panic(err)
			}
			length -= len(v)
		}
		if _, err := e.file.Write(buf.Bytes()); err != nil {
			panic(err)
		}
	}
	e.dispatcher.DeliverNetworkPacket(e, remote, local, protocol, vv)
}
1211586
func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
	var create networkCreate

	err := json.Unmarshal(body, &create)
	if err != nil {
		return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
	}
	processCreateDefaults(c, &create)

	options := []libnetwork.NetworkOption{}
	if val, ok := create.NetworkOpts[netlabel.Internal]; ok {
		internal, err := strconv.ParseBool(val)
		if err != nil {
			return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
		}
		if internal {
			options = append(options, libnetwork.NetworkOptionInternalNetwork())
		}
	}
	if val, ok := create.NetworkOpts[netlabel.EnableIPv6]; ok {
		enableIPv6, err := strconv.ParseBool(val)
		if err != nil {
			return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
		}
		options = append(options, libnetwork.NetworkOptionEnableIPv6(enableIPv6))
	}
	if len(create.DriverOpts) > 0 {
		options = append(options, libnetwork.NetworkOptionDriverOpts(create.DriverOpts))
	}

	if len(create.IPv4Conf) > 0 {
		ipamV4Conf := &libnetwork.IpamConf{
			PreferredPool: create.IPv4Conf[0].PreferredPool,
			SubPool:       create.IPv4Conf[0].SubPool,
		}

		options = append(options, libnetwork.NetworkOptionIpam("default", "", []*libnetwork.IpamConf{ipamV4Conf}, nil, nil))
	}

	nw, err := c.NewNetwork(create.NetworkType, create.Name, create.ID, options...)
	if err != nil {
		return nil, convertNetworkError(err)
	}

	return nw.ID(), &createdResponse
}
1256484
func (e *Endpoint) DeliverNetworkPacket(linkEP stack.LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView) {
	if !e.dispatchGate.Enter() {
		return
	}

	e.dispatcher.DeliverNetworkPacket(e, remote, local, protocol, vv)
	e.dispatchGate.Leave()
}
160070
func (c *Client) CreateFabricNetwork(vlanID int16, opts CreateFabricNetworkOpts) (*FabricNetwork, error) {
	var resp FabricNetwork
	req := request{
		method:         client.POST,
		url:            makeURL(apiFabricVLANs, strconv.Itoa(int(vlanID)), apiFabricNetworks),
		reqValue:       opts,
		resp:           &resp,
		expectedStatus: http.StatusCreated,
	}
	if _, err := c.sendRequest(req); err != nil {
		return nil, errors.Newf(err, "failed to create fabric network %s on vlan %d", opts.Name, vlanID)
	}
	return &resp, nil
}
623241
func (arr *IntArray) ReadFrom(r io.Reader) (n int64, err error) {
	var nn int64

	// Read length-prefix
	var length Int32
	nn, err = length.ReadFrom(r)
	if err != nil {
		return
	}
	n += nn

	// Read length bytes
	arr.Value = make([]types.Int32, length.Int32)
	for index, elem := range arr.Value {
		nn, err = elem.ReadFrom(r)
		if err != nil {
			return
		}
		arr.Value[index] = elem
		n += nn
	}

	return
}
993830
func MD5FromReader(r io.Reader) (string, error) {
	h := md5.New()
	if _, err := io.Copy(h, r); err != nil {
		return "", nil
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}
608980
func NewReader(r io.Reader, ping bool) *Reader {
	return &Reader{
		r:    r,
		err:  make(chan error),
		ping: ping,
	}
}
239745
func (impl *repoImpl) packageReader(c context.Context, ref *api.ObjectRef) (*processing.PackageReader, error) {
	// Get slow Google Storage based ReaderAt.
	rawReader, err := impl.cas.GetReader(c, ref)
	switch code := grpc.Code(err); {
	case code == codes.NotFound:
		return nil, errors.Annotate(err, "package instance is not in the storage").Err()
	case code != codes.OK:
		return nil, errors.Annotate(err, "failed to open the object for reading").Tag(transient.Tag).Err()
	}

	// Read in 512 Kb chunks, keep 2 of them buffered.
	pkg, err := processing.NewPackageReader(
		iotools.NewBufferingReaderAt(rawReader, 512*1024, 2),
		rawReader.Size())
	if err != nil {
		return nil, errors.Annotate(err, "error when opening the package").Err()
	}
	return pkg, nil
}