You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

42 lines
975 B

  1. package main
  2. import (
  3. "math"
  4. "strings"
  5. )
  6. const (
  7. // characters used for short-urls
  8. SYMBOLS = "0123456789abcdefghijklmnopqrsuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ"
  9. // someone set us up the bomb !!
  10. BASE = int64(len(SYMBOLS))
  11. )
  12. // encodes a number into our *base* representation
  13. // TODO can this be made better with some bitshifting?
  14. func Encode(number int64) string {
  15. rest := number % BASE
  16. // strings are a bit weird in go...
  17. result := string(SYMBOLS[rest])
  18. if number-rest != 0 {
  19. newnumber := (number - rest) / BASE
  20. result = Encode(newnumber) + result
  21. }
  22. return result
  23. }
  24. // Decodes a string given in our encoding and returns the decimal
  25. // integer.
  26. func Decode(input string) int64 {
  27. const floatbase = float64(BASE)
  28. l := len(input)
  29. var sum int = 0
  30. for index := l - 1; index > -1; index -= 1 {
  31. current := string(input[index])
  32. pos := strings.Index(SYMBOLS, current)
  33. sum = sum + (pos * int(math.Pow(floatbase, float64((l-index-1)))))
  34. }
  35. return int64(sum)
  36. }