github.com/xyproto/orbiton/v2@v2.65.12-0.20240516144430-e10a419274ec/runes.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  // Check if the given string only consists of the given rune,
    11  // ignoring the other given runes.
    12  func consistsOf(s string, e rune, ignore []rune) bool {
    13  OUTER_LOOP:
    14  	for _, r := range s {
    15  		for _, x := range ignore {
    16  			if r == x {
    17  				continue OUTER_LOOP
    18  			}
    19  		}
    20  		if r != e {
    21  			return false
    22  		}
    23  	}
    24  	return true
    25  }
    26  
    27  // hexDigit checks if the given rune is 0-9, a-f, A-F or x
    28  func hexDigit(r rune) bool {
    29  	switch r {
    30  	case 'x', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f':
    31  		return true
    32  	}
    33  	return false
    34  }
    35  
    36  // runeCount counts the instances of r in the given string
    37  func runeCount(s string, r rune) int {
    38  	counter := 0
    39  	for _, e := range s {
    40  		if e == r {
    41  			counter++
    42  		}
    43  	}
    44  	return counter
    45  }
    46  
    47  // runeFromUBytes returns a rune from a byte slice on the form "U+0000"
    48  func runeFromUBytes(bs []byte) (rune, error) {
    49  	if !bytes.HasPrefix(bs, []byte("U+")) && !bytes.HasPrefix(bs, []byte("u+")) {
    50  		return rune(0), errors.New("not a rune on the form U+0000 or u+0000")
    51  	}
    52  	numberString := string(bs[2:])
    53  	unicodeNumber, err := strconv.ParseUint(numberString, 16, 64)
    54  	if err != nil {
    55  		return rune(0), err
    56  	}
    57  	return rune(unicodeNumber), nil
    58  }
    59  
    60  // repeatRune can repeat a rune, n number of times.
    61  // Returns an empty string if memory can not be allocated within append.
    62  func repeatRune(r rune, n uint) string {
    63  	var sb strings.Builder
    64  	for i := uint(0); i < n; i++ {
    65  		_, err := sb.WriteRune(r)
    66  		if err != nil {
    67  			// In the unlikely event that append inside WriteRune won't work
    68  			return ""
    69  		}
    70  	}
    71  	return sb.String()
    72  }