Skip to content

Commit 42f0601

Browse files
authored
Merge pull request #827 from hashicorp/malloc-partialMaskMessage
Reduces allocations and improves performance in `logging.partialMaskString`
2 parents 5066f26 + 5972987 commit 42f0601

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

logging/aws_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,44 @@ func TestMaskAWSSensitiveValues(t *testing.T) {
9999
})
100100
}
101101
}
102+
103+
func BenchmarkMaskAWSAccessKey(b *testing.B) {
104+
var s string
105+
b.ReportAllocs()
106+
for n := 0; n < b.N; n++ {
107+
s = MaskAWSAccessKey(`
108+
{
109+
"AWSSecretKey": "LEfH8nZmFN4BGIJnku6lkChHydRN5B/YlWCIjOte",
110+
"BucketName": "test-bucket",
111+
"AWSKeyId": "AIDACKCEVSQ6C2EXAMPLE",
112+
}
113+
`)
114+
}
115+
dump = s
116+
}
117+
118+
func BenchmarkPartialMaskString(b *testing.B) {
119+
var s string
120+
b.ReportAllocs()
121+
for n := 0; n < b.N; n++ {
122+
s = partialMaskString("AIDACKCEVSQ6C2EXAMPLE", 4, 4)
123+
}
124+
dump = s
125+
}
126+
127+
func BenchmarkMaskAWSSecretKeys(b *testing.B) {
128+
var s string
129+
b.ReportAllocs()
130+
for n := 0; n < b.N; n++ {
131+
s = MaskAWSSecretKeys(`
132+
{
133+
"AWSSecretKey": "LEfH8nZmFN4BGIJnku6lkChHydRN5B/YlWCIjOte",
134+
"BucketName": "test-bucket",
135+
"AWSKeyId": "AIDACKCEVSQ6C2EXAMPLE",
136+
}
137+
`)
138+
}
139+
dump = s
140+
}
141+
142+
var dump string

logging/mask.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@ import (
99

1010
func partialMaskString(s string, first, last int) string {
1111
l := len(s)
12-
result := s[0:first]
13-
result += strings.Repeat("*", l-first-last)
14-
result += s[l-last:]
15-
return result
12+
result := strings.Builder{}
13+
result.Grow(l)
14+
result.WriteString(s[0:first])
15+
for i := 0; i < l-first-last; i++ {
16+
result.WriteByte('*')
17+
}
18+
result.WriteString(s[l-last:])
19+
return result.String()
1620
}

0 commit comments

Comments
 (0)