go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucicfg/sequence.go (about)

     1  // Copyright 2019 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lucicfg
    16  
    17  import (
    18  	"go.starlark.net/starlark"
    19  )
    20  
    21  // sequences is a mapping "name -> int", mutable via `sequence_next()` calls.
    22  type sequences struct {
    23  	s map[string]int
    24  }
    25  
    26  // next returns the next number in the given sequence.
    27  //
    28  // Sequences start with 1.
    29  func (s *sequences) next(seq string) int {
    30  	if s.s == nil {
    31  		s.s = make(map[string]int, 1)
    32  	}
    33  	v := s.s[seq] + 1
    34  	s.s[seq] = v
    35  	return v
    36  }
    37  
    38  func init() {
    39  	// sequence_next(name) returns a next integer in the sequence.
    40  	declNative("sequence_next", func(call nativeCall) (starlark.Value, error) {
    41  		var name starlark.String
    42  		if err := call.unpack(1, &name); err != nil {
    43  			return nil, err
    44  		}
    45  		return starlark.MakeInt(call.State.seq.next(name.GoString())), nil
    46  	})
    47  }