aboutsummaryrefslogtreecommitdiffstats
path: root/util/hash.go
blob: df0a83b873c5a93d9cf8f61f2d8969cfe771020c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package util

import (
	"fmt"
	"io"
)

type Hash string

func (h Hash) String() string {
	return string(h)
}

func (h *Hash) UnmarshalGQL(v interface{}) error {
	_, ok := v.(string)
	if !ok {
		return fmt.Errorf("labels must be strings")
	}

	*h = v.(Hash)

	if !h.IsValid() {
		return fmt.Errorf("invalid hash")
	}

	return nil
}

func (h Hash) MarshalGQL(w io.Writer) {
	w.Write([]byte(`"` + h.String() + `"`))
}

func (h *Hash) IsValid() bool {
	if len(*h) != 40 {
		return false
	}
	for _, r := range *h {
		if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
			return false
		}
	}
	return true
}