From 2d7e9f0c40d9993f7c3c79b20d95e296bce5f7d3 Mon Sep 17 00:00:00 2001 From: Alex Vanin Date: Tue, 31 Aug 2021 18:39:04 +0300 Subject: [PATCH] [#787] util/attributes: Return consistent list of attributes Attributes are linked to each other through parents, so they can be returned in any order. However, it will be better to return the list in consistent order to reduce entropy. Signed-off-by: Alex Vanin --- pkg/util/attributes/parser.go | 7 ++----- pkg/util/attributes/parser_test.go | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/pkg/util/attributes/parser.go b/pkg/util/attributes/parser.go index cef73598..340443bf 100644 --- a/pkg/util/attributes/parser.go +++ b/pkg/util/attributes/parser.go @@ -28,6 +28,7 @@ func ParseV2Attributes(attrs []string, excl []string) ([]*netmap.NodeAttribute, } cache := make(map[string]*netmap.NodeAttribute, len(attrs)) + result := make([]*netmap.NodeAttribute, 0, len(attrs)) for i := range attrs { line := strings.Trim(attrs[i], pairSeparator) @@ -67,6 +68,7 @@ func ParseV2Attributes(attrs []string, excl []string) ([]*netmap.NodeAttribute, attribute.SetValue(value) cache[key] = attribute + result = append(result, attribute) } if parentKey != "" { @@ -80,11 +82,6 @@ func ParseV2Attributes(attrs []string, excl []string) ([]*netmap.NodeAttribute, } } - result := make([]*netmap.NodeAttribute, 0, len(cache)) - for _, v := range cache { - result = append(result, v) - } - return result, nil } diff --git a/pkg/util/attributes/parser_test.go b/pkg/util/attributes/parser_test.go index 305f5583..c1370332 100644 --- a/pkg/util/attributes/parser_test.go +++ b/pkg/util/attributes/parser_test.go @@ -94,4 +94,20 @@ func TestParseV2Attributes(t *testing.T) { } require.True(t, flag) }) + + t.Run("consistent order in chain", func(t *testing.T) { + from := []string{"/a:1/b:2/c:3"} + + for i := 0; i < 10000; i++ { + attrs, err := attributes.ParseV2Attributes(from, nil) + require.NoError(t, err) + + require.Equal(t, attrs[0].Key(), "a") + require.Equal(t, attrs[0].Value(), "1") + require.Equal(t, attrs[1].Key(), "b") + require.Equal(t, attrs[1].Value(), "2") + require.Equal(t, attrs[2].Key(), "c") + require.Equal(t, attrs[2].Value(), "3") + } + }) }