nativehttp

Simple interface to the native http client
Log | Files | Refs | README | LICENSE

strings.go (1689B)


      1 package core
      2 
      3 /*
      4 	copied from "strings"
      5 */
      6 
      7 // TrimPrefix returns s without the provided leading prefix string.
      8 // If s doesn't start with prefix, s is returned unchanged.
      9 func TrimPrefix(s, prefix string) string {
     10 	if HasPrefix(s, prefix) {
     11 		return s[len(prefix):]
     12 	}
     13 	return s
     14 }
     15 
     16 // HasPrefix tests whether the string s begins with prefix.
     17 func HasPrefix(s, prefix string) bool {
     18 	return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
     19 }
     20 
     21 // Cut slices s around the first instance of sep,
     22 // returning the text before and after sep.
     23 // The found result reports whether sep appears in s.
     24 // If sep does not appear in s, cut returns s, "", false.
     25 func Cut(s, sep string) (before, after string, found bool) {
     26 	if i := Index(s, sep); i >= 0 {
     27 		return s[:i], s[i+len(sep):], true
     28 	}
     29 	return s, "", false
     30 }
     31 
     32 // Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
     33 //
     34 // NOTE: Copied from strings, but without the bytealg calls.
     35 func Index(s, substr string) int {
     36 	n := len(substr)
     37 	switch {
     38 	case n == 0:
     39 		return 0
     40 	case n == 1:
     41 		return IndexByte(s, substr[0])
     42 	case n == len(s):
     43 		if substr == s {
     44 			return 0
     45 		}
     46 		return -1
     47 	default:
     48 		c0 := substr[0]
     49 		c1 := substr[1]
     50 		i := 0
     51 		t := len(s) - n + 1
     52 		for i < t {
     53 			if s[i] != c0 {
     54 				o := IndexByte(s[i+1:t], c0)
     55 				if o < 0 {
     56 					return -1
     57 				}
     58 				i += o + 1
     59 			}
     60 			if s[i+1] == c1 && s[i:i+n] == substr {
     61 				return i
     62 			}
     63 			i++
     64 		}
     65 		return -1
     66 	}
     67 }
     68 
     69 // IndexByte returns the byte index of the first instance of the given byte, or -1 if not present.
     70 func IndexByte(s string, b byte) int {
     71 	for ii := 0; ii < len(s); ii++ {
     72 		if s[ii] == b {
     73 			return ii
     74 		}
     75 	}
     76 	return -1
     77 }