github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/dedupedslice.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     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 utils
    16  
    17  type DedupedSlice[T comparable] struct {
    18  	maxLen int
    19  
    20  	values []T
    21  }
    22  
    23  func NewDedupedSlice[T comparable](maxLen int) *DedupedSlice[T] {
    24  	return &DedupedSlice[T]{
    25  		maxLen: maxLen,
    26  	}
    27  }
    28  
    29  func (d *DedupedSlice[T]) Add(val T) bool {
    30  	for _, v := range d.values {
    31  		if val == v {
    32  			return false
    33  		}
    34  	}
    35  
    36  	d.values = append(d.values, val)
    37  	if len(d.values) > d.maxLen {
    38  		d.values = d.values[len(d.values)-d.maxLen:]
    39  	}
    40  	return true
    41  }
    42  
    43  func (d *DedupedSlice[T]) Get() []T {
    44  	return d.values
    45  }
    46  
    47  func (d *DedupedSlice[T]) Len() int {
    48  	return len(d.values)
    49  }
    50  
    51  func (d *DedupedSlice[T]) Has(val T) bool {
    52  	for _, v := range d.values {
    53  		if v == val {
    54  			return true
    55  		}
    56  	}
    57  
    58  	return false
    59  }
    60  
    61  func (d *DedupedSlice[T]) Clear() {
    62  	d.values = nil
    63  }