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.

sha1.go 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "strings"
  10. )
  11. var (
  12. IdNotExist = errors.New("sha1 id not exist")
  13. )
  14. type sha1 [20]byte
  15. // Return true if s has the same sha1 as caller.
  16. // Support 40-length-string, []byte, sha1
  17. func (id sha1) Equal(s2 interface{}) bool {
  18. switch v := s2.(type) {
  19. case string:
  20. if len(v) != 40 {
  21. return false
  22. }
  23. return v == id.String()
  24. case []byte:
  25. if len(v) != 20 {
  26. return false
  27. }
  28. for i, v := range v {
  29. if id[i] != v {
  30. return false
  31. }
  32. }
  33. case sha1:
  34. for i, v := range v {
  35. if id[i] != v {
  36. return false
  37. }
  38. }
  39. default:
  40. return false
  41. }
  42. return true
  43. }
  44. // Return string (hex) representation of the Oid
  45. func (s sha1) String() string {
  46. result := make([]byte, 0, 40)
  47. hexvalues := []byte("0123456789abcdef")
  48. for i := 0; i < 20; i++ {
  49. result = append(result, hexvalues[s[i]>>4])
  50. result = append(result, hexvalues[s[i]&0xf])
  51. }
  52. return string(result)
  53. }
  54. // Create a new sha1 from a 20 byte slice.
  55. func NewId(b []byte) (sha1, error) {
  56. var id sha1
  57. if len(b) != 20 {
  58. return id, errors.New("Length must be 20")
  59. }
  60. for i := 0; i < 20; i++ {
  61. id[i] = b[i]
  62. }
  63. return id, nil
  64. }
  65. // Create a new sha1 from a Sha1 string of length 40.
  66. func NewIdFromString(s string) (sha1, error) {
  67. s = strings.TrimSpace(s)
  68. var id sha1
  69. if len(s) != 40 {
  70. return id, fmt.Errorf("Length must be 40")
  71. }
  72. b, err := hex.DecodeString(s)
  73. if err != nil {
  74. return id, err
  75. }
  76. return NewId(b)
  77. }