github.com/uber/kraken@v0.1.4/lib/torrent/networkevent/util.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, 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  package networkevent
    15  
    16  import (
    17  	"sort"
    18  	"time"
    19  
    20  	"github.com/uber/kraken/utils/stringset"
    21  )
    22  
    23  type byTime []*Event
    24  
    25  func (s byTime) Len() int           { return len(s) }
    26  func (s byTime) Less(i, j int) bool { return s[i].Time.Before(s[j].Time) }
    27  func (s byTime) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
    28  
    29  // Sort sorts events in place by timestamp.
    30  func Sort(events []*Event) {
    31  	sort.Sort(byTime(events))
    32  }
    33  
    34  // Filter filters events by name.
    35  func Filter(events []*Event, names ...Name) []*Event {
    36  	s := make(stringset.Set)
    37  	for _, name := range names {
    38  		s.Add(string(name))
    39  	}
    40  	var f []*Event
    41  	for _, e := range events {
    42  		if s.Has(string(e.Name)) {
    43  			f = append(f, e)
    44  		}
    45  	}
    46  	return f
    47  }
    48  
    49  // StripTimestamps overwrites timestamps in events as empty, allowing clients
    50  // to check equality of events.
    51  //
    52  // Mutates events in place and returns events for chaining purposes.
    53  func StripTimestamps(events []*Event) []*Event {
    54  	for _, e := range events {
    55  		e.Time = time.Time{}
    56  	}
    57  	return events
    58  }