github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/context/entries.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package context
    19  
    20  import (
    21  	"bytes"
    22  )
    23  
    24  type Entry struct {
    25  	key []byte
    26  	val any
    27  }
    28  
    29  type Entries []Entry
    30  
    31  func (entries *Entries) Get(key []byte) (val any) {
    32  	s := *entries
    33  	for _, entry := range s {
    34  		if bytes.Equal(key, entry.key) {
    35  			val = entry.val
    36  			return
    37  		}
    38  	}
    39  	return
    40  }
    41  
    42  func (entries *Entries) Set(key []byte, val any) {
    43  	s := *entries
    44  	for _, entry := range s {
    45  		if bytes.Equal(key, entry.key) {
    46  			entry.val = val
    47  			*entries = s
    48  			return
    49  		}
    50  	}
    51  	s = append(s, Entry{
    52  		key: key,
    53  		val: val,
    54  	})
    55  	*entries = s
    56  	return
    57  }
    58  
    59  func (entries *Entries) Remove(key []byte) (ok bool) {
    60  	s := *entries
    61  	n := -1
    62  	for i, entry := range s {
    63  		if bytes.Equal(key, entry.key) {
    64  			n = i
    65  			break
    66  		}
    67  	}
    68  	if n > -1 {
    69  		s = append(s[:n], s[n+1:]...)
    70  		*entries = s
    71  		ok = true
    72  	}
    73  	return
    74  }
    75  
    76  func (entries *Entries) Foreach(fn func(key []byte, value any)) {
    77  	s := *entries
    78  	for _, entry := range s {
    79  		fn(entry.key, entry.val)
    80  	}
    81  }
    82  
    83  func (entries *Entries) Len() int {
    84  	return len(*entries)
    85  }
    86  
    87  func (entries *Entries) Reset() {
    88  	s := *entries
    89  	s = s[:0]
    90  	*entries = s
    91  }