-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotational_cipher.go
65 lines (49 loc) · 1.63 KB
/
rotational_cipher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Package rotationalcipher is used to encrypt data.
package rotationalcipher
import (
"strings"
"unicode"
)
// RotationalCipher returns a cipher text after applying a rotational cipher to a plain text input.
func RotationalCipher(plain string, shiftKey int) string {
if len(plain) == 0 {
return ""
}
var cipher strings.Builder
for _, char := range plain {
if !unicode.IsLower(char) && !unicode.IsUpper(char) {
cipher.WriteString(string(char))
} else {
cipher.WriteString(string(shiftChar(char, shiftKey)))
}
}
return cipher.String()
}
func shiftChar(char rune, shift int) rune {
var offset int
if unicode.IsLower(char) {
offset = 97
}
if unicode.IsUpper(char) {
offset = 65
}
return rune(((int(char) - offset + shift) % 26) + offset)
}
/*
=== string concat vs bytes.Buffer ===
name old time/op new time/op delta
RotationalCipher-4 3.61µs ± 0% 4.01µs ± 0% ~ (p=1.000 n=1+1)
name old alloc/op new alloc/op delta
RotationalCipher-4 680B ± 0% 680B ± 0% ~ (all equal)
name old allocs/op new allocs/op delta
RotationalCipher-4 14.0 ± 0% 14.0 ± 0% ~ (all equal)
*/
/*
=== bytes.Buffer vs strings.Builder ===
name old time/op new time/op delta
RotationalCipher-4 4.01µs ± 0% 3.61µs ± 0% ~ (p=1.000 n=1+1)
name old alloc/op new alloc/op delta
RotationalCipher-4 680B ± 0% 280B ± 0% ~ (p=1.000 n=1+1)
name old allocs/op new allocs/op delta
RotationalCipher-4 14.0 ± 0% 16.0 ± 0% ~ (p=1.000 n=1+1)
*/