github.com/Ptt-official-app/go-bbs@v0.12.0/cstr.go (about)

     1  package bbs
     2  
     3  import "bytes"
     4  
     5  //Cstr
     6  //
     7  //[]byte with C String property in that \0 is considered as the end of the bytes/string.
     8  //It is used to convert from fixed-length bytes to string or []byte with no \0.
     9  //
    10  //Naming Cstr instead of CString is to avoid confusion with C.CString
    11  //(C.CString is from string, and should be compatible with string, not with []byte)
    12  //(We also have str(len/cpy/cmp) functions in C)
    13  //
    14  //See tests for more examples of how to use fixed-bytes with Cstr to get no-\0 string / []byte
    15  type Cstr []byte
    16  
    17  //CstrToString
    18  //
    19  //Only the bytes until \0 when converting to string.
    20  //See tests for more examples.
    21  //
    22  //Params
    23  //	cstr
    24  //
    25  //Return
    26  //	string: string
    27  func CstrToString(cstr Cstr) string {
    28  	theBytes := CstrToBytes(cstr)
    29  	return string(theBytes)
    30  }
    31  
    32  //CstrToBytes
    33  //
    34  //Only the bytes until \0.
    35  //See tests for more examples.
    36  //
    37  //Params
    38  //	cstr
    39  //
    40  //Return
    41  //	[]byte: bytes
    42  func CstrToBytes(cstr Cstr) []byte {
    43  	len := bytes.IndexByte(cstr, 0x00)
    44  	if len == -1 {
    45  		return cstr
    46  	}
    47  
    48  	return cstr[:len]
    49  }