9fans.net/go@v0.0.7/cmd/sam/string.go (about)

     1  package main
     2  
     3  func Strinit(p *String) {
     4  	p.s = nil
     5  }
     6  
     7  func Strinit0(p *String) {
     8  	p.s = nil
     9  }
    10  
    11  func Strclose(p *String) {
    12  	// free(p.s)
    13  }
    14  
    15  const MAXSIZE = 256
    16  
    17  func Strzero(p *String) {
    18  	if cap(p.s) > MAXSIZE {
    19  		p.s = nil /* throw away the garbage */
    20  	}
    21  	p.s = p.s[:0]
    22  }
    23  
    24  func Strlen(r []rune) int {
    25  	return len(r)
    26  }
    27  
    28  func Strdupl(p *String, s []rune) {
    29  	Strinsure(p, len(s))
    30  	copy(p.s, s)
    31  }
    32  
    33  func Strduplstr(p *String, q *String) {
    34  	Strinsure(p, len(q.s))
    35  	copy(p.s, q.s)
    36  }
    37  
    38  func Straddc(p *String, c rune) {
    39  	p.s = append(p.s, c)
    40  }
    41  
    42  func Strinsure(p *String, n int) {
    43  	if n > STRSIZE {
    44  		error_(Etoolong)
    45  	}
    46  	for cap(p.s) < n {
    47  		p.s = append(p.s[:cap(p.s)], 0)
    48  	}
    49  	p.s = p.s[:n]
    50  }
    51  
    52  func Strinsert(p *String, q *String, p0 Posn) {
    53  	Strinsure(p, len(p.s)+len(q.s))
    54  	copy(p.s[p0+len(q.s):], p.s[p0:])
    55  	copy(p.s[p0:], q.s)
    56  }
    57  
    58  func Strdelete(p *String, p1 Posn, p2 Posn) {
    59  	if p1 <= len(p.s) && p2 == len(p.s)+1 {
    60  		// "deleting" the NUL at the end is OK
    61  		p2--
    62  	}
    63  	copy(p.s[p1:], p.s[p2:])
    64  	p.s = p.s[:len(p.s)-(p2-p1)]
    65  }
    66  
    67  func Strcmp(a *String, b *String) int {
    68  	var i int
    69  	for i = 0; i < len(a.s) && i < len(b.s); i++ {
    70  		c := int(a.s[i] - b.s[i])
    71  		if c != 0 { /* assign = */
    72  			return c
    73  		}
    74  	}
    75  	return len(a.s) - len(b.s)
    76  }
    77  
    78  func Strispre(prefix, s *String) bool {
    79  	for i := 0; i < len(prefix.s); i++ {
    80  		if i >= len(s.s) || s.s[i] != prefix.s[i] {
    81  			return false
    82  		}
    83  	}
    84  	return true
    85  }
    86  
    87  func Strtoc(s *String) string {
    88  	return string(s.s)
    89  }
    90  
    91  /*
    92   * Build very temporary String from Rune*
    93   */
    94  var tmprstr_p String
    95  
    96  func tmprstr(r []rune) *String {
    97  	return &String{r}
    98  }
    99  
   100  /*
   101   * Convert null-terminated char* into String
   102   */
   103  func tmpcstr(s string) *String {
   104  	if len(s) > 0 && s[len(s)-1] == '\x00' {
   105  		s = s[:len(s)-1]
   106  	}
   107  	r := []rune(s)
   108  	return &String{r}
   109  }
   110  
   111  func freetmpstr(s *String) {
   112  	// free(s.s)
   113  	// free(s)
   114  }