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.

93 lines
1.9 KiB

  1. // Copyright 2015 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. "fmt"
  8. "strings"
  9. )
  10. const EMPTY_SHA = "0000000000000000000000000000000000000000"
  11. type sha1 [20]byte
  12. // Equal returns true if s has the same sha1 as caller.
  13. // Support 40-length-string, []byte, sha1.
  14. func (id sha1) Equal(s2 interface{}) bool {
  15. switch v := s2.(type) {
  16. case string:
  17. if len(v) != 40 {
  18. return false
  19. }
  20. return v == id.String()
  21. case []byte:
  22. if len(v) != 20 {
  23. return false
  24. }
  25. for i, v := range v {
  26. if id[i] != v {
  27. return false
  28. }
  29. }
  30. case sha1:
  31. for i, v := range v {
  32. if id[i] != v {
  33. return false
  34. }
  35. }
  36. default:
  37. return false
  38. }
  39. return true
  40. }
  41. // String returns string (hex) representation of the Oid.
  42. func (s sha1) String() string {
  43. result := make([]byte, 0, 40)
  44. hexvalues := []byte("0123456789abcdef")
  45. for i := 0; i < 20; i++ {
  46. result = append(result, hexvalues[s[i]>>4])
  47. result = append(result, hexvalues[s[i]&0xf])
  48. }
  49. return string(result)
  50. }
  51. // MustID always creates a new sha1 from a [20]byte array with no validation of input.
  52. func MustID(b []byte) sha1 {
  53. var id sha1
  54. for i := 0; i < 20; i++ {
  55. id[i] = b[i]
  56. }
  57. return id
  58. }
  59. // NewID creates a new sha1 from a [20]byte array.
  60. func NewID(b []byte) (sha1, error) {
  61. if len(b) != 20 {
  62. return sha1{}, fmt.Errorf("Length must be 20: %v", b)
  63. }
  64. return MustID(b), nil
  65. }
  66. // MustIDFromString always creates a new sha from a ID with no validation of input.
  67. func MustIDFromString(s string) sha1 {
  68. b, _ := hex.DecodeString(s)
  69. return MustID(b)
  70. }
  71. // NewIDFromString creates a new sha1 from a ID string of length 40.
  72. func NewIDFromString(s string) (sha1, error) {
  73. var id sha1
  74. s = strings.TrimSpace(s)
  75. if len(s) != 40 {
  76. return id, fmt.Errorf("Length must be 40: %s", s)
  77. }
  78. b, err := hex.DecodeString(s)
  79. if err != nil {
  80. return id, err
  81. }
  82. return NewID(b)
  83. }