Skip to content

Commit

Permalink
Updated RandomString function with a very efficient variant
Browse files Browse the repository at this point in the history
  • Loading branch information
onattech committed Jan 14, 2023
1 parent e22e277 commit e8c216b
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ package toolkit

import (
"bytes"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)

const randomStringSource = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+"
Expand All @@ -28,14 +29,14 @@ type Tools struct {
// RandomString returns a string of random characters of length n, using randomStringSource
// as the source for the string
func (t *Tools) RandomString(n int) string {
s, r := make([]rune, n), []rune(randomStringSource)
for i := range s {
p, _ := rand.Prime(rand.Reader, len(r))
x, y := p.Uint64(), uint64(len(r))
s[i] = r[x%y]
rand.Seed(time.Now().UnixNano())
sb := strings.Builder{}
sb.Grow(n)
for i := 0; i < n; i++ {
sb.WriteByte(randomStringSource[rand.Intn(len(randomStringSource))])
}

return string(s)
return sb.String()
}

// UploadedFile is a struct used to save information about an uploaded file
Expand Down

0 comments on commit e8c216b

Please sign in to comment.