tools.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package lib
  2. import (
  3. "math"
  4. "strings"
  5. "git.sfnt.net/sfnt/cnlink/conf"
  6. )
  7. // Int2String converts an unsigned 64bit integer to a string.
  8. func Int2String(seq uint64) (shortURL string) {
  9. charSeq := []rune{}
  10. if seq != 0 {
  11. for seq != 0 {
  12. mod := seq % conf.Conf.Common.BaseStringLength
  13. div := seq / conf.Conf.Common.BaseStringLength
  14. charSeq = append(charSeq, rune(conf.Conf.Common.BaseString[mod]))
  15. seq = div
  16. }
  17. } else {
  18. charSeq = append(charSeq, rune(conf.Conf.Common.BaseString[seq]))
  19. }
  20. tmpShortURL := string(charSeq)
  21. shortURL = reverse(tmpShortURL)
  22. return
  23. }
  24. // String2Int converts a short URL string to an unsigned 64bit integer.
  25. func String2Int(shortURL string) (seq uint64) {
  26. shortURL = reverse(shortURL)
  27. for index, char := range shortURL {
  28. base := uint64(math.Pow(float64(conf.Conf.Common.BaseStringLength), float64(index)))
  29. seq += uint64(strings.Index(conf.Conf.Common.BaseString, string(char))) * base
  30. }
  31. return
  32. }
  33. func reverse(s string) string {
  34. r := []rune(s)
  35. for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
  36. r[i], r[j] = r[j], r[i]
  37. }
  38. return string(r)
  39. }