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.
 
 
 

66 lines
2.1 KiB

  1. /*
  2. https://github.com/fs111/kurz.go/blob/master/src/codec.go
  3. Originally written and Copyright (c) 2011 André Kelpe
  4. Modifications Copyright (c) 2015 John Ko
  5. Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. this software and associated documentation files (the "Software"), to deal in
  7. the Software without restriction, including without limitation the rights to
  8. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. the Software, and to permit persons to whom the Software is furnished to do so,
  10. subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  15. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  16. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  17. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  18. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  19. */
  20. package server
  21. import (
  22. "math"
  23. "strings"
  24. )
  25. const (
  26. // characters used for short-urls
  27. SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  28. // someone set us up the bomb !!
  29. BASE = int64(len(SYMBOLS))
  30. )
  31. // encodes a number into our *base* representation
  32. // TODO can this be made better with some bitshifting?
  33. func Encode(number int64) string {
  34. rest := number % BASE
  35. // strings are a bit weird in go...
  36. result := string(SYMBOLS[rest])
  37. if number-rest != 0 {
  38. newnumber := (number - rest) / BASE
  39. result = Encode(newnumber) + result
  40. }
  41. return result
  42. }
  43. // Decodes a string given in our encoding and returns the decimal
  44. // integer.
  45. func Decode(input string) int64 {
  46. const floatbase = float64(BASE)
  47. l := len(input)
  48. var sum int = 0
  49. for index := l - 1; index > -1; index -= 1 {
  50. current := string(input[index])
  51. pos := strings.Index(SYMBOLS, current)
  52. sum = sum + (pos * int(math.Pow(floatbase, float64((l-index-1)))))
  53. }
  54. return int64(sum)
  55. }