Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

65 řádky
2.0 KiB

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