Debian Codegraph @

api/v1/lib/resources/reduce.go

raw symbols SCIP
1 package resources
2
3 import (
4 "github.com/mesos/mesos-go/api/v1/lib"
5 "github.com/mesos/mesos-go/api/v1/lib/resourcefilters"
6 )
7
8 // Reducer applies some operation to possibly combine an accumulator (acc) and a resource (x), returning
9 // either the combined result or nil.
10 type Reducer func(acc, x *mesos.Resource) *mesos.Resource
11
12 // If applies a filter func to a resource reducer; rejected resources are not processed by the receiving reducer.
13 func (rf Reducer) If(f func(*mesos.Resource) bool) Reducer {
14 if f == nil {
15 return rf
16 }
17 return func(acc, x *mesos.Resource) *mesos.Resource {
18 if f(x) {
19 return rf(acc, x)
20 }
21 return acc
22 }
23 }
24
25 // IfNot applies a filter func to a resource reducer; accepted resources are not processed by the receiving reducer.
26 func (rf Reducer) IfNot(f func(*mesos.Resource) bool) Reducer {
27 if f == nil {
28 return rf
29 }
30 return rf.If(func(r *mesos.Resource) bool {
31 return !f(r)
32 })
33 }
34
35 // Reduce applies the given Reducer to produce a final Resource, iterating left-to-right over the given
36 // resources; panics if the Reducer is nil.
37 func Reduce(rf Reducer, rs ...mesos.Resource) (r *mesos.Resource) {
38 if rf == nil {
39 panic("Reduce: reducer func may not be nil")
40 }
41 for i := range rs {
42 r = rf(r, &rs[i])
43 }
44 return
45 }
46
47 func Sum(fs ...resourcefilters.Filter) Reducer {
48 return Reducer(func(acc, x *mesos.Resource) *mesos.Resource {
49 p := acc
50 if p == nil {
51 p = x
52 }
53 if p == nil {
54 return nil
55 }
56 switch p.GetType() {
57 case mesos.SCALAR:
58 return &mesos.Resource{Scalar: acc.GetScalar().Add(x.GetScalar())}
59 case mesos.RANGES:
60 return &mesos.Resource{Ranges: acc.GetRanges().Add(x.GetRanges())}
61 case mesos.SET:
62 return &mesos.Resource{Set: acc.GetSet().Add(x.GetSet())}
63 default:
64 // we can't take the sum of TEXT type
65 }
66 return nil
67 }).If(resourcefilters.Filters(fs).Accepts)
68 }