github.com/quantosnetwork/Quantos@v0.0.0-20220306172517-e20b28c5a29a/quantix/runeset/runeset.go (about)

     1  package runeset
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"sort"
     7  )
     8  
     9  type RuneSet struct {
    10  	set map[rune]bool
    11  }
    12  
    13  // New returns a new RuneSet
    14  func New() *RuneSet {
    15  	return &RuneSet{
    16  		set: make(map[rune]bool),
    17  	}
    18  }
    19  
    20  // Add adds r to rs
    21  func (rs *RuneSet) Add(r rune) {
    22  	rs.set[r] = true
    23  }
    24  
    25  // Contains returns true iff r is in rs
    26  func (rs *RuneSet) Contains(r rune) bool {
    27  	return rs.set[r]
    28  }
    29  
    30  // Elements returns the runes in rs sorted in ascending order
    31  func (rs *RuneSet) Elements() []rune {
    32  	elements := make([]rune, 0, len(rs.set))
    33  	for r := range rs.set {
    34  		elements = append(elements, r)
    35  	}
    36  	sort.Slice(elements, func(i, j int) bool {
    37  		return elements[i] < elements[j]
    38  	})
    39  	return elements
    40  }
    41  
    42  // Empty returns true iff rs has no elements
    43  func (rs *RuneSet) Empty() bool {
    44  	return len(rs.set) == 0
    45  }
    46  
    47  // Equal returns true iff rs and rs1 have the same elements
    48  func (rs *RuneSet) Equal(rs1 *RuneSet) bool {
    49  	if len(rs.set) != len(rs1.set) {
    50  		return false
    51  	}
    52  	for r := range rs.set {
    53  		if !rs1.set[r] {
    54  			return false
    55  		}
    56  	}
    57  	return true
    58  }
    59  
    60  // Intersection contains all elements common to rs and rs1
    61  func (rs *RuneSet) Intersection(rs1 *RuneSet) *RuneSet {
    62  	intersection := New()
    63  	for r := range rs.set {
    64  		if rs1.Contains(r) {
    65  			intersection.Add(r)
    66  		}
    67  	}
    68  	return intersection
    69  }
    70  
    71  // Subset returns true iff every element of rs is in rs1
    72  func (rs *RuneSet) Subset(rs1 *RuneSet) bool {
    73  	for r := range rs.set {
    74  		if !rs1.set[r] {
    75  			return false
    76  		}
    77  	}
    78  	return true
    79  }
    80  
    81  func (rs *RuneSet) String() string {
    82  	w := new(bytes.Buffer)
    83  	fmt.Fprintf(w, "[]rune{")
    84  	for i, r := range rs.Elements() {
    85  		if i > 0 {
    86  			fmt.Fprint(w, ",")
    87  		}
    88  		fmt.Fprintf(w, "'%s'", escape(r))
    89  	}
    90  	fmt.Fprint(w, "}")
    91  	return w.String()
    92  }
    93  
    94  func escape(r rune) string {
    95  	switch r {
    96  	case '\\':
    97  		return "\\\\"
    98  	case '\'':
    99  		return "\\'"
   100  	case '\r':
   101  		return "\\r"
   102  	case '\n':
   103  		return "\\n"
   104  	case '\t':
   105  		return "\\t"
   106  	}
   107  	return string(r)
   108  }