*: make use of min/max where appropriate

Signed-off-by: Roman Khimov <roman@nspcc.ru>
This commit is contained in:
Roman Khimov 2024-08-23 22:09:20 +03:00
parent f21edef43b
commit 1c1d77c9b8
12 changed files with 26 additions and 82 deletions

View file

@ -64,8 +64,8 @@ func cancelTx(ctx *cli.Context) error {
if err != nil {
return err
}
if mainTx != nil && t.NetworkFee < mainTx.NetworkFee+1 {
t.NetworkFee = mainTx.NetworkFee + 1
if mainTx != nil {
t.NetworkFee = max(t.NetworkFee, mainTx.NetworkFee+1)
}
t.NetworkFee += int64(flags.Fixed8FromContext(ctx, "gas"))
if mainTx != nil {

View file

@ -118,9 +118,7 @@ func (c *codegen) traverseGlobals() bool {
var currMax int
lastCnt, currMax = c.convertInitFuncs(f, pkg.Types, lastCnt)
if currMax > maxCnt {
maxCnt = currMax
}
maxCnt = max(currMax, maxCnt)
}
// because we reuse `convertFuncDecl` for init funcs,
// we need to clear scope, so that global variables
@ -128,9 +126,7 @@ func (c *codegen) traverseGlobals() bool {
c.scope = nil
})
if c.globalInlineCount > maxCnt {
maxCnt = c.globalInlineCount
}
maxCnt = max(c.globalInlineCount, maxCnt)
// Here we remove `INITSLOT` if no code was emitted for `init` function.
// Note that the `INITSSLOT` must stay in place.

View file

@ -402,9 +402,7 @@ func (c *codegen) convertInitFuncs(f *ast.File, pkg *types.Package, lastCount in
f := c.convertFuncDecl(f, n, pkg)
lastCount = f.vars.localsCnt
if lastCount > maxCount {
maxCount = lastCount
}
maxCount = max(lastCount, maxCount)
}
case *ast.GenDecl:
return false
@ -437,9 +435,7 @@ func (c *codegen) convertDeployFuncs() int {
f := c.convertFuncDecl(f, n, pkg)
lastCount = f.vars.localsCnt
if lastCount > maxCount {
maxCount = lastCount
}
maxCount = max(lastCount, maxCount)
}
case *ast.GenDecl:
return false

View file

@ -47,9 +47,7 @@ func (c *codegen) inlineCall(f *funcScope, n *ast.CallExpr) {
c.scope = &funcScope{}
c.scope.vars.newScope()
defer func() {
if cnt := c.scope.vars.localsCnt; cnt > c.globalInlineCount {
c.globalInlineCount = cnt
}
c.globalInlineCount = max(c.globalInlineCount, c.scope.vars.localsCnt)
c.scope = nil
}()
}

View file

@ -634,9 +634,7 @@ func (s *service) processBlock(b dbft.Block[util.Uint256]) {
}
func (s *service) postBlock(b *coreb.Block) {
if s.lastTimestamp < b.Timestamp {
s.lastTimestamp = b.Timestamp
}
s.lastTimestamp = max(s.lastTimestamp, b.Timestamp)
s.lastProposal = nil
}

View file

@ -1115,9 +1115,7 @@ func (bc *Blockchain) Run() {
}
nextSync = dur > persistInterval*2
interval := persistInterval - dur - gcDur
if interval <= 0 {
interval = time.Microsecond // Reset doesn't work with zero value
}
interval = max(interval, time.Microsecond) // Reset doesn't work with zero or negative value.
persistTimer.Reset(interval)
}
}
@ -1134,9 +1132,7 @@ func (bc *Blockchain) tryRunGC(oldHeight uint32) time.Duration {
syncP := newHeight / uint32(bc.config.StateSyncInterval)
syncP--
syncP *= uint32(bc.config.StateSyncInterval)
if tgtBlock > int64(syncP) {
tgtBlock = int64(syncP)
}
tgtBlock = min(tgtBlock, int64(syncP))
}
// Always round to the GCP.
tgtBlock /= int64(bc.config.Ledger.GarbageCollectionPeriod)
@ -1619,9 +1615,7 @@ func (bc *Blockchain) storeBlock(block *block.Block, txpool *mempool.Pool) error
block.Index >= uint32(bc.config.StateSyncInterval)+bc.config.MaxTraceableBlocks && // check this in case if MaxTraceableBlocks>StateSyncInterval
int(block.Index)%bc.config.StateSyncInterval == 0 {
stop = block.Index - uint32(bc.config.StateSyncInterval) - bc.config.MaxTraceableBlocks
if stop > uint32(bc.config.StateSyncInterval) {
start = stop - uint32(bc.config.StateSyncInterval)
}
start = stop - min(stop, uint32(bc.config.StateSyncInterval))
}
} else if block.Index > bc.config.MaxTraceableBlocks {
start = block.Index - bc.config.MaxTraceableBlocks // is at least 1
@ -2954,10 +2948,7 @@ func (bc *Blockchain) VerifyWitness(h util.Uint160, c hash.Hashable, w *transact
// verifyHashAgainstScript verifies given hash against the given witness and returns the amount of GAS consumed.
func (bc *Blockchain) verifyHashAgainstScript(hash util.Uint160, witness *transaction.Witness, interopCtx *interop.Context, gas int64) (int64, error) {
gasPolicy := bc.contracts.Policy.GetMaxVerificationGas(interopCtx.DAO)
if gas > gasPolicy {
gas = gasPolicy
}
gas = min(gas, bc.contracts.Policy.GetMaxVerificationGas(interopCtx.DAO))
vm := interopCtx.SpawnVM()
vm.GasLimit = gas

View file

@ -475,11 +475,7 @@ func (s *Server) run() {
} else if s.MinPeers > 0 && loopCnt%s.MinPeers == 0 && optimalN > peerN && optimalN < s.MaxPeers && optimalN < netSize {
// Having some number of peers, but probably can get some more, the network is big.
// It also allows to start picking up new peers proactively, before we suddenly have <s.MinPeers of them.
var connN = s.AttemptConnPeers
if connN > optimalN-peerN {
connN = optimalN - peerN
}
s.discovery.RequestRemote(connN)
s.discovery.RequestRemote(min(s.AttemptConnPeers, optimalN-peerN))
}
if addrCheckTimeout || s.discovery.PoolCount() < s.AttemptConnPeers {
@ -1509,9 +1505,7 @@ func (s *Server) RequestTx(hashes ...util.Uint256) {
for i := 0; i <= len(hashes)/payload.MaxHashesCount; i++ {
start := i * payload.MaxHashesCount
stop := (i + 1) * payload.MaxHashesCount
if stop > len(hashes) {
stop = len(hashes)
}
stop = min(stop, len(hashes))
if start == stop {
break
}
@ -1660,9 +1654,7 @@ func (s *Server) initStaleMemPools() {
threshold := 5
// Not perfect, can change over time, but should be sufficient.
numOfCNs := s.config.GetNumOfCNs(s.chain.BlockHeight())
if numOfCNs*2 > threshold {
threshold = numOfCNs * 2
}
threshold = max(threshold, numOfCNs*2)
s.mempool.SetResendThreshold(uint32(threshold), s.broadcastTX)
if s.chain.P2PSigExtensionsEnabled() {
@ -1769,12 +1761,5 @@ func (s *Server) Port(localAddr net.Addr) (uint16, error) {
func optimalNumOfThreads() int {
// Doing more won't help, mempool is still a contention point.
const maxThreads = 16
var threads = runtime.GOMAXPROCS(0)
if threads > runtime.NumCPU() {
threads = runtime.NumCPU()
}
if threads > maxThreads {
threads = maxThreads
}
return threads
return min(runtime.GOMAXPROCS(0), runtime.NumCPU(), maxThreads)
}

View file

@ -229,9 +229,7 @@ func iterateNext(rpc RPCSessions, sessionID uuid.UUID, iterator *result.Iterator
if iterator.ID != nil {
return rpc.TraverseIterator(sessionID, *iterator.ID, num)
}
if num > len(iterator.Values) {
num = len(iterator.Values)
}
num = min(num, len(iterator.Values))
items := iterator.Values[:num]
iterator.Values = iterator.Values[num:]

View file

@ -265,9 +265,7 @@ func (n *Notary) OnNewRequest(payload *payload.P2PNotaryRequest) {
return // then we already have processed this request
}
}
if nvbFallback < r.minNotValidBefore {
r.minNotValidBefore = nvbFallback
}
r.minNotValidBefore = min(r.minNotValidBefore, nvbFallback)
} else {
// Avoid changes in the main transaction witnesses got from the notary request pool to
// keep the pooled tx valid. We will update its copy => the copy's size will be changed.

View file

@ -449,9 +449,7 @@ func (p *pathParser) descendByRange(objs []any, start, end int) ([]any, bool) {
subEnd += len(arr)
}
if subEnd > len(arr) {
subEnd = len(arr)
}
subEnd = min(subEnd, len(arr))
if subEnd <= subStart {
continue

View file

@ -273,10 +273,7 @@ func New(chain Ledger, conf config.RPC, coreServer *network.Server,
protoCfg := chain.GetConfig().ProtocolConfiguration
if conf.SessionEnabled {
if conf.SessionExpirationTime <= 0 {
conf.SessionExpirationTime = int(protoCfg.TimePerBlock / time.Second)
if conf.SessionExpirationTime < 5 {
conf.SessionExpirationTime = 5
}
conf.SessionExpirationTime = max(int(protoCfg.TimePerBlock/time.Second), 5)
log.Info("SessionExpirationTime is not set or wrong, setting default value", zap.Int("SessionExpirationTime", conf.SessionExpirationTime))
}
if conf.SessionPoolSize <= 0 {
@ -958,13 +955,9 @@ func (s *Server) calculateNetworkFee(reqParams params.Params) (any, *neorpc.Erro
size := len(hashablePart) + io.GetVarSize(len(tx.Signers))
var (
netFee int64
// Verification GAS cost can't exceed this policy.
gasLimit = s.chain.GetMaxVerificationGAS()
// Verification GAS cost can't exceed chin policy, but RPC config can limit it further.
gasLimit = min(s.chain.GetMaxVerificationGAS(), int64(s.config.MaxGasInvoke))
)
if gasLimit > int64(s.config.MaxGasInvoke) {
// But we honor instance configuration as well.
gasLimit = int64(s.config.MaxGasInvoke)
}
for i, signer := range tx.Signers {
w := tx.Scripts[i]
if len(w.InvocationScript) == 0 { // No invocation provided, try to infer one.
@ -1683,9 +1676,7 @@ func (s *Server) findStates(ps params.Params) (any, *neorpc.Error) {
if err != nil {
return nil, neorpc.WrapErrorWithData(neorpc.ErrInvalidParams, fmt.Sprintf("invalid count: %s", err))
}
if count > s.config.MaxFindResultItems {
count = s.config.MaxFindResultItems
}
count = min(count, s.config.MaxFindResultItems)
}
cs, respErr := s.getHistoricalContractState(root, csHash)
if respErr != nil {
@ -2379,10 +2370,7 @@ func (s *Server) prepareInvocationContext(t trigger.Type, script []byte, contrac
if t == trigger.Verification {
// We need this special case because witnesses verification is not the simple System.Contract.Call,
// and we need to define exactly the amount of gas consumed for a contract witness verification.
gasPolicy := s.chain.GetMaxVerificationGAS()
if ic.VM.GasLimit > gasPolicy {
ic.VM.GasLimit = gasPolicy
}
ic.VM.GasLimit = min(ic.VM.GasLimit, s.chain.GetMaxVerificationGAS())
err = s.chain.InitVerificationContext(ic, contractScriptHash, &transaction.Witness{InvocationScript: script, VerificationScript: []byte{}})
if err != nil {

View file

@ -676,11 +676,9 @@ func (i *ByteArray) equalsLimited(s Item, limit *int) bool {
if !ok {
return false
}
comparedSize = lCurr
lOther := len(*val)
if lOther > comparedSize {
comparedSize = lOther
}
comparedSize = max(lCurr, lOther)
if i == val {
return true
}