container/mts/meta: added GetAllAsMap function

This function is very similar to GetAll, except that is returns a map[string]string rather
than a [][2]string. It's become apparent that a map[string]string might be more useful in
some circumstances.
This commit is contained in:
Saxon 2019-06-11 22:07:51 +09:30
parent 2640b1b615
commit 9af964cfc9
1 changed files with 28 additions and 0 deletions

View File

@ -216,6 +216,34 @@ func GetAll(d []byte) ([][2]string, error) {
return all, nil return all, nil
} }
// GetAllAsMap returns a map containging keys and values from a slice d containing
// AusOcean metadata.
func GetAllAsMap(d []byte) (map[string]string, error) {
err := checkMeta(d)
if err != nil {
return nil, err
}
// Skip the header, which is our data length and version.
d = d[headSize:]
// Each metadata entry (key and value) is seperated by a tab, so split at tabs
// to get individual entries.
entries := strings.Split(string(d), "\t")
// Go through entries and add to all map.
all := make(map[string]string)
for _, entry := range entries {
// Keys and values are seperated by '=', so split and check that len(kv)=2.
kv := strings.Split(entry, "=")
if len(kv) != 2 {
return nil, errUnexpectedMetaFormat
}
all[kv[0]] = kv[1]
}
return all, nil
}
// checkHeader checks that a valid metadata header exists in the given data. // checkHeader checks that a valid metadata header exists in the given data.
func checkMeta(d []byte) error { func checkMeta(d []byte) error {
if len(d) == 0 || d[0] != 0 || binary.BigEndian.Uint16(d[2:headSize]) != uint16(len(d[headSize:])) { if len(d) == 0 || d[0] != 0 || binary.BigEndian.Uint16(d[2:headSize]) != uint16(len(d[headSize:])) {