Skip to content

Commit

Permalink
add possibility to sort TrustChains
Browse files Browse the repository at this point in the history
  • Loading branch information
zachmann committed Jan 29, 2025
1 parent 2286c7b commit 34923b5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/metadata_resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ func (LocalMetadataResolver) resolveResponsePayloadWithoutTrustMarks(
Types: req.EntityTypes,
}
chains := tr.ResolveToValidChains()
chains = chains.Filter(TrustChainsFilterMinPathLength)
if len(chains) == 0 {
err = errors.New("no trust chain found")
return
}
chains = chains.SortAsc(TrustChainScoringPathLen)
for _, chain = range chains {
m, err := chain.Metadata()
if err == nil {
Expand Down
43 changes: 43 additions & 0 deletions pkg/trustchainfilter.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package pkg

import (
"sort"
)

// TrustChains is a slice of multiple TrustChain
type TrustChains []TrustChain

Expand All @@ -14,6 +18,45 @@ func (c TrustChains) Filter(filter ...TrustChainsFilter) TrustChains {
return c
}

// SortAsc sorts multiple TrustChains ascending by using the passed TrustChainScoringFnc
func (c TrustChains) SortAsc(scorer TrustChainScoringFnc) TrustChains {
scores := make([]int, len(c))
for i, tc := range c {
scores[i] = scorer(tc)
}

sort.Slice(
c, func(i, j int) bool {
return scores[i] < scores[j]
},
)
return c
}

// SortDesc sorts multiple TrustChains descending by using the passed TrustChainScoringFnc
func (c TrustChains) SortDesc(scorer TrustChainScoringFnc) TrustChains {
scores := make([]int, len(c))
for i, tc := range c {
scores[i] = scorer(tc)
}

sort.Slice(
c, func(i, j int) bool {
return scores[i] > scores[j]
},
)
return c
}

// TrustChainScoringFnc a function type that takes a TrustChain and calculates a score for the chain.
// This score then can be used to sort TrustChains
type TrustChainScoringFnc func(c TrustChain) int

// TrustChainScoringPathLen is a TrustChainScoringFnc that uses the chain's path len
func TrustChainScoringPathLen(c TrustChain) int {
return c.PathLen()
}

// TrustChainChecker can check a single TrustChain to determine if it should be included or not,
// i.e. in a TrustChainsFilter
type TrustChainChecker interface {
Expand Down

0 comments on commit 34923b5

Please sign in to comment.