2017-06-26 23:46:34 +02:00
|
|
|
// Copyright 2016-2017, Pulumi Corporation. All rights reserved.
|
2017-06-08 18:26:06 +02:00
|
|
|
|
|
|
|
package resource
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"encoding/hex"
|
|
|
|
|
2017-06-10 03:34:37 +02:00
|
|
|
"github.com/pulumi/lumi/pkg/eval/rt"
|
2017-06-08 18:26:06 +02:00
|
|
|
"github.com/pulumi/lumi/pkg/util/contract"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ID is a unique resource identifier; it is managed by the provider and is mostly opaque to Lumi.
|
|
|
|
type ID string
|
|
|
|
|
|
|
|
// String converts a resource ID into a string.
|
|
|
|
func (id ID) String() string {
|
|
|
|
return string(id)
|
|
|
|
}
|
|
|
|
|
|
|
|
// StringPtr converts an optional ID into an optional string.
|
|
|
|
func (id *ID) StringPtr() *string {
|
|
|
|
if id == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
ids := (*id).String()
|
|
|
|
return &ids
|
|
|
|
}
|
|
|
|
|
|
|
|
// IDStrings turns an array of resource IDs into an array of strings.
|
|
|
|
func IDStrings(ids []ID) []string {
|
|
|
|
ss := make([]string, len(ids))
|
|
|
|
for i, id := range ids {
|
|
|
|
ss[i] = id.String()
|
|
|
|
}
|
|
|
|
return ss
|
|
|
|
}
|
|
|
|
|
|
|
|
// MaybeID turns an optional string into an optional resource ID.
|
|
|
|
func MaybeID(s *string) *ID {
|
|
|
|
var ret *ID
|
|
|
|
if s != nil {
|
|
|
|
id := ID(*s)
|
|
|
|
ret = &id
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2017-06-10 03:34:37 +02:00
|
|
|
const (
|
|
|
|
// IDProperty is the special ID property name.
|
2017-07-14 17:53:02 +02:00
|
|
|
IDProperty = rt.PropertyKey("pid")
|
2017-06-10 03:34:37 +02:00
|
|
|
// IDPropertyKey is the special ID property name for resource maps.
|
2017-07-14 17:53:02 +02:00
|
|
|
IDPropertyKey = PropertyKey("pid")
|
2017-06-10 03:34:37 +02:00
|
|
|
)
|
|
|
|
|
2017-06-08 18:26:06 +02:00
|
|
|
// NewUniqueHex generates a new "random" hex string for use by resource providers. It has the given optional prefix and
|
|
|
|
// the total length is capped to the maxlen. Note that capping to maxlen necessarily increases the risk of collisions.
|
2017-06-16 00:51:22 +02:00
|
|
|
func NewUniqueHex(prefix string, maxlen, randlen int) string {
|
2017-06-08 18:26:06 +02:00
|
|
|
bs := make([]byte, randlen)
|
|
|
|
n, err := rand.Read(bs)
|
|
|
|
contract.Assert(err == nil)
|
|
|
|
contract.Assert(n == len(bs))
|
|
|
|
|
|
|
|
str := prefix + hex.EncodeToString(bs)
|
|
|
|
if len(str) > maxlen {
|
|
|
|
str = str[:maxlen]
|
|
|
|
}
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewUniqueHexID generates a new "random" hex ID for use by resource providers. It has the given optional prefix and
|
|
|
|
// the total length is capped to the maxlen. Note that capping to maxlen necessarily increases the risk of collisions.
|
2017-06-16 00:51:22 +02:00
|
|
|
func NewUniqueHexID(prefix string, maxlen, randlen int) ID {
|
2017-06-08 18:26:06 +02:00
|
|
|
return ID(NewUniqueHex(prefix, randlen, maxlen))
|
|
|
|
}
|