builtin: add charptr.vstring() and charptr.vstring_with_len() (#6830)

pull/6832/head
Swastik Baranwal 2020-11-14 23:13:42 +05:30 committed by GitHub
parent 827fb62c29
commit 00464ad988
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 0 deletions

View File

@ -138,6 +138,24 @@ pub fn (bp byteptr) vstring_with_len(len int) string {
}
}
// charptr.vstring() - converts C char* to V string. NB: the string data is reused, NOT copied.
[unsafe]
pub fn (cp charptr) vstring() string {
return string{
str: byteptr(cp)
len: unsafe {C.strlen(cp)}
}
}
// charptr.vstring_with_len() - converts C char* to V string. NB: the string data is reused, NOT copied.
[unsafe]
pub fn (cp charptr) vstring_with_len(len int) string {
return string{
str: byteptr(cp)
len: len
}
}
// string.clone_static returns an independent copy of a given array
// It should be used only in -autofree generated code.
fn (a string) clone_static() string {

View File

@ -528,6 +528,14 @@ fn test_bytes_to_string() {
assert bytes.bytestr() == 'hello'
}
fn test_charptr() {
foo := charptr('VLANG'.str)
println(typeof(foo))
assert typeof(foo) == 'charptr'
assert unsafe { foo.vstring() } == 'VLANG'
assert unsafe { foo.vstring_with_len(3) } == 'VLA'
}
fn test_count() {
assert ''.count('') == 0
assert ''.count('a') == 0