get.pme.sh/pnats@v0.0.0-20240304004023-26bb5a137ed0/server/stree/dump.go (about)

     1  // Copyright 2024 The NATS Authors
     2  // Licensed under the Apache License, Version 2.0 (the "License");
     3  // you may not use this file except in compliance with the License.
     4  // You may obtain a copy of the License at
     5  //
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package stree
    15  
    16  import (
    17  	"fmt"
    18  	"io"
    19  	"strings"
    20  )
    21  
    22  // For dumping out a text representation of a tree.
    23  func (t *SubjectTree[T]) Dump(w io.Writer) {
    24  	t.dump(w, t.root, 0)
    25  	fmt.Fprintln(w)
    26  }
    27  
    28  // Will dump out a node.
    29  func (t *SubjectTree[T]) dump(w io.Writer, n node, depth int) {
    30  	if n == nil {
    31  		fmt.Fprintf(w, "EMPTY\n")
    32  		return
    33  	}
    34  	if n.isLeaf() {
    35  		leaf := n.(*leaf[T])
    36  		fmt.Fprintf(w, "%s LEAF: Suffix: %q Value: %+v\n", dumpPre(depth), leaf.suffix, leaf.value)
    37  		n = nil
    38  	} else {
    39  		// We are a node type here, grab meta portion.
    40  		bn := n.base()
    41  		fmt.Fprintf(w, "%s %s Prefix: %q\n", dumpPre(depth), n.kind(), bn.prefix[:bn.prefixLen])
    42  		depth++
    43  		n.iter(func(n node) bool {
    44  			t.dump(w, n, depth)
    45  			return true
    46  		})
    47  	}
    48  }
    49  
    50  // For individual node/leaf dumps.
    51  func (n *leaf[T]) kind() string { return "LEAF" }
    52  func (n *node4) kind() string   { return "NODE4" }
    53  func (n *node16) kind() string  { return "NODE16" }
    54  func (n *node256) kind() string { return "NODE256" }
    55  
    56  // Calculates the indendation, etc.
    57  func dumpPre(depth int) string {
    58  	if depth == 0 {
    59  		return "-- "
    60  	} else {
    61  		var b strings.Builder
    62  		for i := 0; i < depth; i++ {
    63  			b.WriteString("  ")
    64  		}
    65  		b.WriteString("|__ ")
    66  		return b.String()
    67  	}
    68  }