Skip to content

Commit

Permalink
Strings to Runes
Browse files Browse the repository at this point in the history
  • Loading branch information
Mobilpadde committed Jan 11, 2023
1 parent ac33c0a commit 0cb53ac
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 18 deletions.
13 changes: 6 additions & 7 deletions moths/emojies/emojies.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
package emojies

import (
"strings"
)
import "strings"

type Emojies []string
type Emojies []rune

func (emojies Emojies) String() string {
return strings.Join(emojies, "")
return string(emojies)
}

func (emojies Emojies) SpacedString() string {
return strings.Join(emojies, " ")
return strings.Join(emojies.Slice(), " ")
}

func (emojies Emojies) Slice() []string {
return emojies
str := emojies.String()
return strings.Split(str, "")
}
19 changes: 19 additions & 0 deletions moths/emojies/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package emojies

import "unicode/utf8"

func ToEmojies(emojies []string) Emojies {
em := Emojies{}

for i := 0; i < len(emojies); i++ {
current := emojies[i]
for j := 0; j < len(current); {
r, width := utf8.DecodeRuneInString(current[j:])
em = append(em, r)

j += width
}
}

return em
}
24 changes: 13 additions & 11 deletions moths/otp/otp.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ import (

const emojiBytes = 4

func NewOTP(token string, amount int, emojies emojies.Emojies) (OTP, error) {
emojiAmount := len(emojies)
func NewOTP(token string, amount int, em emojies.Emojies) (OTP, error) {
emojiAmount := len(em)
size := emojiBytes * amount

// https://github.com/tilaklodha/google-authenticator
mask := 2<<uint32(31-bits.LeadingZeros32(uint32(emojiAmount-1|1))) - 1
step := int(math.Ceil(1.6 * float64(mask*size) / float64(emojiAmount)))

id := new(strings.Builder)
id.Grow(size)
moth := new(strings.Builder)
moth.Grow(size)

buffer := bufferFromToken(token)
loop:
Expand All @@ -29,24 +29,26 @@ loop:
return OTP{}, err
}

// TODO: This goes on forever? - figure why!
// Use emojies.GESTURES
for i := 0; i < step; i++ {
currentIndex := int(randomBuffer[i]) & mask

if currentIndex < len(emojies) {
if _, err := id.WriteString(emojies[currentIndex]); err != nil {
if currentIndex < emojiAmount {
if _, err := moth.WriteRune(em[currentIndex]); err != nil {
return OTP{}, err
} else if id.Len() == size {
} else if moth.Len() == size {
break loop
}

if moth.Len() > size {
moth.Reset()
}
}
}
}

emojies = strings.Split(id.String(), "")
split := strings.Split(moth.String(), "")
return OTP{
token: token,
emojies: emojies,
emojies: emojies.ToEmojies(split),
}, nil
}

0 comments on commit 0cb53ac

Please sign in to comment.