// memNeededForSearch is a helper function that returns an estimate of RAM
// needed to execute a search request.
330084
func memNeededForSearch(req *SearchRequest,
	searcher search.Searcher,
	topnCollector *collector.TopNCollector) uint64 {

	backingSize := req.Size + req.From + 1
	if req.Size+req.From > collector.PreAllocSizeSkipCap {
		backingSize = collector.PreAllocSizeSkipCap + 1
	}
	numDocMatches := backingSize + searcher.DocumentMatchPoolSize()

	estimate := 0

	// overhead, size in bytes from collector
	estimate += topnCollector.Size()

	// pre-allocing DocumentMatchPool
	estimate += searchContextEmptySize + numDocMatches*documentMatchEmptySize

	// searcher overhead
	estimate += searcher.Size()

	// overhead from results, lowestMatchOutsideResults
	estimate += (numDocMatches + 1) * documentMatchEmptySize

	// additional overhead from SearchResult
	estimate += reflectStaticSizeSearchResult + reflectStaticSizeSearchStatus

	// overhead from facet results
	if req.Facets != nil {
		estimate += len(req.Facets) * facetResultEmptySize
	}

	// highlighting, store
	if len(req.Fields) > 0 || req.Highlight != nil {
		// Size + From => number of hits
		estimate += (req.Size + req.From) * documentEmptySize
	}

	return uint64(estimate)
}
1147221
func (c *Container) Mem() uint {
	v := c.Config["limits.memory"]
	if v == "" {
		return 0
	}

	bytes, err := shared.ParseByteSizeString(v)
	if err != nil {
		logger.Errorf("failed to parse %q into bytes, ignoring err: %s", v, err)
		return 0
	}

	const oneMiB = 1024 * 1024
	mib := bytes / oneMiB
	if mib > math.MaxUint32 {
		logger.Errorf("byte string %q overflowed uint32, using max value", v)
		return math.MaxUint32
	}

	return uint(mib)
}
859052
func (db *DB) getMems() (e, f *memDB) {
	db.memMu.RLock()
	defer db.memMu.RUnlock()
	if db.mem != nil {
		db.mem.incref()
	} else if !db.isClosed() {
		panic("nil effective mem")
	}
	if db.frozenMem != nil {
		db.frozenMem.incref()
	}
	return db.mem, db.frozenMem
}
47688
func isMemoryBestEffort(container *api.Container) bool {
	// A container is memory best-effort if its memory request is unspecified or 0.
	// If a request is specified, then the user expects some kind of resource guarantee.
	return container.Resources.Requests.Memory().Value() == 0
}
732687
func (p *propServerPlan) GetMemoryMB() int {
	if p.ServerPlan == nil {
		return -1
	}

	return p.ServerPlan.GetMemoryMB()
}
1220294
func (m *MemoryRange) ReadMemory(buf []byte, addr uintptr) (int, error) {
	if len(buf) == 0 {
		return 0, nil
	}
	if (uint64(addr) < m.Addr) || (uint64(addr)+uint64(len(buf)) > m.Addr+uint64(len(m.Data))) {
		return 0, io.EOF
	}
	copy(buf, m.Data[uint64(addr)-m.Addr:])
	return len(buf), nil
}
814719
func handleGetMempoolInfo(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	mempoolTxns := s.cfg.TxMemPool.TxDescs()

	var numBytes int64
	for _, txD := range mempoolTxns {
		numBytes += int64(txD.Tx.MsgTx().SerializeSize())
	}

	ret := &btcjson.GetMempoolInfoResult{
		Size:  int64(len(mempoolTxns)),
		Bytes: numBytes,
	}

	return ret, nil
}
364200
func (p *Profile) ParseMemoryMapFromScanner(s *bufio.Scanner) error {
	mapping, err := parseProcMapsFromScanner(s)
	if err != nil {
		return err
	}
	p.Mapping = append(p.Mapping, mapping...)
	p.massageMappings()
	p.remapLocationIDs()
	p.remapFunctionIDs()
	p.remapMappingIDs()
	return nil
}
1065968
func (a *segment) searchIndex(key []byte) (int, int) {
	if a.index != nil {
		// Check the in-memory index for a more accurate window.
		return a.index.lookup(key)
	}

	return 0, a.Len()
}
261146
func (p *Plugin) GetMemory(in *Msg, k string) Memory {
	var buf []byte
	var err error

	// Only retrieve state-related values of that specific plugin.
	// Otherwise fetch the memory from any plugin.
	if in.User.ID > 0 {
		if k == StateKey || k == stateEnteredKey {
			q := `SELECT value FROM states
			      WHERE userid=$1 AND key=$2 AND pluginname=$3`
			err = p.DB.Get(&buf, q, in.User.ID, k, p.Config.Name)
		} else {
			q := `SELECT value FROM states
			      WHERE userid=$1 AND key=$2`
			err = p.DB.Get(&buf, q, in.User.ID, k)
		}
	} else {
		if k == StateKey || k == stateEnteredKey {
			q := `SELECT value FROM states
			      WHERE flexid=$1 AND flexidtype=$2 AND key=$3 AND pluginname=$4`
			err = p.DB.Get(&buf, q, in.User.FlexID,
				in.User.FlexIDType, k, p.Config.Name)
		} else {
			q := `SELECT value FROM states
			      WHERE flexid=$1 AND flexidtype=$2 AND key=$3`
			err = p.DB.Get(&buf, q, in.User.FlexID,
				in.User.FlexIDType, k)
		}
	}
	if err == sql.ErrNoRows {
		return Memory{Key: k, Val: json.RawMessage{}, log: p.Log}
	}
	if err != nil {
		p.Log.Infof("could not get memory for key %s. %s", k,
			err.Error())
		return Memory{Key: k, Val: json.RawMessage{}, log: p.Log}
	}
	return Memory{Key: k, Val: buf, log: p.Log}
}
274532
func memoryUsage(memStats *statsapi.MemoryStats) *resource.Quantity {
	if memStats == nil || memStats.WorkingSetBytes == nil {
		return &resource.Quantity{Format: resource.BinarySI}
	}
	usage := int64(*memStats.WorkingSetBytes)
	return resource.NewQuantity(usage, resource.BinarySI)
}
603427
func (_m *API) SetHostMemory(_a0 api.HostUpdateConfig) error {
	ret := _m.Called(_a0)

	var r0 error
	if rf, ok := ret.Get(0).(func(api.HostUpdateConfig) error); ok {
		r0 = rf(_a0)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
1168565
func wordsNeeded(i uint) int {
	if i > (Cap() - wordSize + 1) {
		return int(Cap() >> log2WordSize)
	}
	return int((i + (wordSize - 1)) >> log2WordSize)
}
985617
func (t *Thread) ReadMemory(buf []byte, addr uintptr) (int, error) {
	panic(ErrNativeBackendDisabled)
}
715285
func (md *MDServerMemory) CheckForRekeys(ctx context.Context) <-chan error {
	// Nothing to do
	c := make(chan error, 1)
	c <- nil
	return c
}
434611
func QueryAttemptsForQuest(c context.Context, qid string) *ds.Query {
	from := ds.MakeKey(c, "Attempt", qid+"|")
	to := ds.MakeKey(c, "Attempt", qid+"~")
	return ds.NewQuery("Attempt").Gt("__key__", from).Lt("__key__", to)
}
1325545
func (m *Potassium) SelectMemoryNodes(nodesInfo []types.NodeInfo, quota float64, memory int64) ([]types.NodeInfo, int, error) {
	log.Debugf("[SelectMemoryNodes] nodesInfo: %v, cpu: %f, memory: %d", nodesInfo, quota, memory)
	if memory <= 0 {
		return nil, 0, types.ErrNegativeMemory
	}

	nodesInfoLength := len(nodesInfo)

	// 筛选出能满足 CPU 需求的
	sort.Slice(nodesInfo, func(i, j int) bool { return len(nodesInfo[i].CPUMap) < len(nodesInfo[j].CPUMap) })
	p := sort.Search(nodesInfoLength, func(i int) bool { return float64(len(nodesInfo[i].CPUMap)) >= quota })
	// p 最大也就是 nodesInfoLength - 1
	if p == nodesInfoLength {
		return nil, 0, types.ErrInsufficientCPU
	}
	nodesInfoLength -= p
	nodesInfo = nodesInfo[p:]

	// 计算是否有足够的内存满足需求
	sort.Slice(nodesInfo, func(i, j int) bool { return nodesInfo[i].MemCap < nodesInfo[j].MemCap })
	p = sort.Search(nodesInfoLength, func(i int) bool { return nodesInfo[i].MemCap >= memory })
	if p == nodesInfoLength {
		return nil, 0, types.ErrInsufficientMEM
	}
	nodesInfoLength -= p
	nodesInfo = nodesInfo[p:]

	// 这里 memCap 一定是大于 memory 的所以不用判断 cap 内容
	volTotal := 0
	for i, nodeInfo := range nodesInfo {
		capacity := int(nodeInfo.MemCap / memory)
		volTotal += capacity
		nodesInfo[i].Capacity = capacity
	}
	return nodesInfo, volTotal, nil
}