github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/key/path.go (about)

     1  // Copyright (c) 2018 Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package key
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  )
    11  
    12  // Path represents a path decomposed into elements where each
    13  // element is a Key. A Path can be interpreted as either
    14  // absolute or relative depending on how it is used.
    15  type Path []Key
    16  
    17  // String returns the Path as an absolute path string.
    18  func (p Path) String() string {
    19  	if len(p) == 0 {
    20  		return "/"
    21  	}
    22  	var b strings.Builder
    23  	for _, element := range p {
    24  		b.WriteByte('/')
    25  		// Use StringKey instead of element.String() because
    26  		// that will escape any invalid UTF-8.
    27  		b.WriteString(StringKey(element))
    28  	}
    29  	return b.String()
    30  }
    31  
    32  // MarshalJSON marshals a Path to JSON.
    33  func (p Path) MarshalJSON() ([]byte, error) {
    34  	return []byte(fmt.Sprintf(`{"_path":%q}`, p)), nil
    35  }
    36  
    37  // Equal returns whether a Path is equal to @other.
    38  func (p Path) Equal(other interface{}) bool {
    39  	o, ok := other.(Path)
    40  	return ok && pathEqual(p, o)
    41  }
    42  
    43  func pathEqual(a, b Path) bool {
    44  	if len(a) != len(b) {
    45  		return false
    46  	}
    47  	for i := range a {
    48  		if !a[i].Equal(b[i]) {
    49  			return false
    50  		}
    51  	}
    52  	return true
    53  }