github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/cluster/clusterproviders/zk/utils.go (about)

     1  package zk
     2  
     3  import (
     4  	"fmt"
     5  	"log/slog"
     6  	"runtime"
     7  	"strconv"
     8  	"strings"
     9  )
    10  
    11  func intToStr(i int) string {
    12  	return strconv.FormatInt(int64(i), 10)
    13  }
    14  
    15  func strToInt(s string) int {
    16  	i, _ := strconv.ParseInt(s, 10, 64)
    17  	return int(i)
    18  }
    19  
    20  func isStrBlank(s string) bool { return s == "" }
    21  
    22  func formatBaseKey(s string) string {
    23  	if !strings.HasPrefix(s, "/") {
    24  		s = "/" + s
    25  	}
    26  	if strings.HasSuffix(s, "/") && s != "/" {
    27  		s = strings.TrimSuffix(s, "/")
    28  	}
    29  	return s
    30  }
    31  
    32  func parseSeq(path string) (int, error) {
    33  	parts := strings.Split(path, "-")
    34  	if len(parts) == 1 {
    35  		parts = strings.Split(path, "__")
    36  	}
    37  	return strconv.Atoi(parts[len(parts)-1])
    38  }
    39  
    40  func stringContains(list []string, str string) bool {
    41  	for _, v := range list {
    42  		if v == str {
    43  			return true
    44  		}
    45  	}
    46  	return false
    47  }
    48  
    49  func mapString(list []string, fn func(string) string) []string {
    50  	l := make([]string, len(list))
    51  	for i, str := range list {
    52  		l[i] = fn(str)
    53  	}
    54  	return l
    55  }
    56  
    57  func safeRun(logger *slog.Logger, fn func()) {
    58  	defer func() {
    59  		if r := recover(); r != nil {
    60  			logger.Warn("OnRoleChanged.", slog.Any("error", fmt.Errorf("%v\n%s", r, string(getRunTimeStack()))))
    61  		}
    62  	}()
    63  	fn()
    64  }
    65  
    66  func getRunTimeStack() []byte {
    67  	const size = 64 << 10
    68  	buf := make([]byte, size)
    69  	return buf[:runtime.Stack(buf, false)]
    70  }
    71  
    72  func getParentDir(path string) string {
    73  	parent := path[:strings.LastIndex(path, "/")]
    74  	if parent == "" {
    75  		return "/"
    76  	}
    77  	return parent
    78  }
    79  
    80  func joinPath(paths ...string) string {
    81  	return strings.Join(paths, "/")
    82  }