blob: 281eb0f521364d1588796d1a852741f3793a6e5a [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2015 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package names
5
6import (
7 "fmt"
8 "net"
9)
10
11const SubnetTagKind = "subnet"
12
13// IsValidSubnet returns whether cidr is a valid subnet CIDR.
14func IsValidSubnet(cidr string) bool {
15 _, ipNet, err := net.ParseCIDR(cidr)
16 if err == nil && ipNet.String() == cidr {
17 return true
18 }
19 return false
20}
21
22type SubnetTag struct {
23 cidr string
24}
25
26func (t SubnetTag) String() string { return t.Kind() + "-" + t.cidr }
27func (t SubnetTag) Kind() string { return SubnetTagKind }
28func (t SubnetTag) Id() string { return t.cidr }
29
30// NewSubnetTag returns the tag for subnet with the given CIDR.
31func NewSubnetTag(cidr string) SubnetTag {
32 if !IsValidSubnet(cidr) {
33 panic(fmt.Sprintf("%s is not a valid subnet CIDR", cidr))
34 }
35 return SubnetTag{cidr: cidr}
36}
37
38// ParseSubnetTag parses a subnet tag string.
39func ParseSubnetTag(subnetTag string) (SubnetTag, error) {
40 tag, err := ParseTag(subnetTag)
41 if err != nil {
42 return SubnetTag{}, err
43 }
44 subt, ok := tag.(SubnetTag)
45 if !ok {
46 return SubnetTag{}, invalidTagError(subnetTag, SubnetTagKind)
47 }
48 return subt, nil
49}