fspl/entity/key.go

71 lines
1.5 KiB
Go

package entity
import "fmt"
import "crypto/md5"
import "encoding/base64"
import "github.com/google/uuid"
// A hash represents a hash sum that fits within a uint64.
type Hash [8]byte
// NewHash creates a new truncated md5 hash using the specified data.
func NewHash (data []byte) Hash {
sum := md5.Sum(data)
hash := Hash { }
copy(hash[:], sum[:8])
return hash
}
// Number converts the hash into a uint64.
func (hash Hash) Number () uint64 {
var number uint64
for _, part := range hash {
number <<= 8
number |= uint64(part)
}
return number
}
// Key globally indexes top level entities in contexts where modules matter.
type Key struct {
Unit uuid.UUID
Name string
Method string
}
func (key Key) String () string {
out := fmt.Sprintf("%v::%v", key.Unit, key.Name)
if key.Method != "" {
out = fmt.Sprintf("%s.%s", out, key.Method)
}
return out
}
// Hash returns a representation of the hash of this key that fits within a
// uint64.
func (key Key) Hash () Hash {
return NewHash([]byte("Key:" + key.String()))
}
// LinkName returns the name that the entity it refers to will be given when
// compiled.
func (key Key) LinkName () string {
data := [16]byte(key.Unit)
out := fmt.Sprintf(
"%s::%s",
base64.StdEncoding.EncodeToString(data[:]),
key.Name)
if key.Method != "" {
out = fmt.Sprintf("%s.%s", out, key.Method)
}
return out
}
// StripMethod returns a copy of the key that refers to a type instead of a
// method.
func (key Key) StripMethod () Key {
key.Method = ""
return key
}