builtin: vfmt every .v file, except vlib/builtin/int_test.v (#9448)

pull/9445/head
zakuro 2021-03-25 03:39:59 +09:00 committed by GitHub
parent 5d8b9b0151
commit 6bc9ef7373
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 259 additions and 272 deletions

View File

@ -17,6 +17,7 @@ const (
'examples/term.ui', 'examples/term.ui',
] ]
verify_known_failing_exceptions = [ verify_known_failing_exceptions = [
'vlib/builtin/int_test.v' /* special number formatting that should be tested */,
'vlib/gg/m4/graphic.v' /* has hand crafted meaningful formatting of matrices */, 'vlib/gg/m4/graphic.v' /* has hand crafted meaningful formatting of matrices */,
'vlib/gg/m4/m4_test.v' /* has hand crafted meaningful formatting of matrices */, 'vlib/gg/m4/m4_test.v' /* has hand crafted meaningful formatting of matrices */,
'vlib/gg/m4/matrix.v' /* has hand crafted meaningful formatting of matrices */, 'vlib/gg/m4/matrix.v' /* has hand crafted meaningful formatting of matrices */,
@ -28,12 +29,7 @@ const (
'vlib/arrays/', 'vlib/arrays/',
'vlib/benchmark/', 'vlib/benchmark/',
'vlib/bitfield/', 'vlib/bitfield/',
'vlib/builtin/array.v', 'vlib/builtin/',
'vlib/builtin/array_test.v',
'vlib/builtin/string.v',
'vlib/builtin/map.v',
'vlib/builtin/int.v',
'vlib/builtin/option.v',
'vlib/cli/', 'vlib/cli/',
'vlib/dl/', 'vlib/dl/',
'vlib/flag/', 'vlib/flag/',
@ -72,7 +68,6 @@ const (
'vlib/v/vmod/', 'vlib/v/vmod/',
'vlib/cli/', 'vlib/cli/',
'vlib/flag/', 'vlib/flag/',
'vlib/gg/gg.v',
'vlib/math/big/', 'vlib/math/big/',
'vlib/os/', 'vlib/os/',
'vlib/semver/', 'vlib/semver/',

View File

@ -2,15 +2,15 @@ module builtin
pub struct array { pub struct array {
pub: pub:
data voidptr data voidptr
len int len int
cap int cap int
element_size int element_size int
} }
// for now off the stack // for now off the stack
fn new_array_from_c_array(len int, cap int, elm_size int, c_array voidptr) array { fn new_array_from_c_array(len int, cap int, elm_size int, c_array voidptr) array {
arr := array { arr := array{
len: len len: len
cap: cap cap: cap
element_size: elm_size element_size: elm_size
@ -30,24 +30,23 @@ fn (a array) get(i int) voidptr {
// Private function. Used to implement assigment to the array element. // Private function. Used to implement assigment to the array element.
fn (mut a array) set(i int, val voidptr) { fn (mut a array) set(i int, val voidptr) {
if i < 0 || i >= a.len { if i < 0 || i >= a.len {
panic('array.set: index out of range') //FIXME: (i == $i, a.len == $a.len)') panic('array.set: index out of range') // FIXME: (i == $i, a.len == $a.len)')
} }
mem_copy(a.data + a.element_size * i, val, a.element_size) mem_copy(a.data + a.element_size * i, val, a.element_size)
} }
// array.repeat returns new array with the given array elements // array.repeat returns new array with the given array elements
// repeated `nr_repeat` times // repeated `nr_repeat` times
pub fn (a array) repeat(nr_repeats int) array { pub fn (a array) repeat(nr_repeats int) array {
assert nr_repeats >= 0 assert nr_repeats >= 0
arr := array { arr := array{
len: nr_repeats * a.len len: nr_repeats * a.len
cap: nr_repeats * a.len cap: nr_repeats * a.len
element_size: a.element_size element_size: a.element_size
data: malloc(nr_repeats * a.len * a.element_size) data: malloc(nr_repeats * a.len * a.element_size)
} }
for i in 0..nr_repeats { for i in 0 .. nr_repeats {
mem_copy(arr.data + i * a.len * a.element_size, a.data, a.len * a.element_size) mem_copy(arr.data + i * a.len * a.element_size, a.data, a.len * a.element_size)
} }
return arr return arr

View File

@ -14,7 +14,7 @@ pub fn print(s string) {
pub fn println(s string) { pub fn println(s string) {
print(s) print(s)
print("\n") print('\n')
} }
pub fn panic(s string) { pub fn panic(s string) {
@ -24,7 +24,7 @@ pub fn panic(s string) {
} }
// replaces panic when -debug arg is passed // replaces panic when -debug arg is passed
fn panic_debug(line_no int, file, mod, fn_name, s string) { fn panic_debug(line_no int, file string, mod string, fn_name string, s string) {
eprintln('================ V panic ================') eprintln('================ V panic ================')
eprint(' module: ') eprint(' module: ')
eprintln('mod') eprintln('mod')
@ -33,12 +33,13 @@ fn panic_debug(line_no int, file, mod, fn_name, s string) {
eprintln('()') eprintln('()')
eprintln(' file: ') eprintln(' file: ')
eprintln(file) eprintln(file)
//println(' line: ${line_no}') // println(' line: ${line_no}')
eprint(' message: ') eprint(' message: ')
eprintln(s) eprintln(s)
eprintln('=========================================') eprintln('=========================================')
sys_exit(1) sys_exit(1)
} }
pub fn eprint(s string) { pub fn eprint(s string) {
if isnil(s.str) { if isnil(s.str) {
panic('eprint(NIL)') panic('eprint(NIL)')
@ -48,7 +49,7 @@ pub fn eprint(s string) {
pub fn eprint_ln(s string) { pub fn eprint_ln(s string) {
eprint(s) eprint(s)
eprint("\n") eprint('\n')
} }
pub fn eprintln(s string) { pub fn eprintln(s string) {

View File

@ -257,6 +257,7 @@ fn sys_call2(scn u64, arg1 u64, arg2 u64) u64 {
} }
return res return res
} }
fn sys_call3(scn u64, arg1 u64, arg2 u64, arg3 u64) u64 { fn sys_call3(scn u64, arg1 u64, arg2 u64, arg3 u64) u64 {
res := u64(0) res := u64(0)
asm amd64 { asm amd64 {
@ -269,6 +270,7 @@ fn sys_call3(scn u64, arg1 u64, arg2 u64, arg3 u64) u64 {
} }
return res return res
} }
fn sys_call4(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64) u64 { fn sys_call4(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64) u64 {
res := u64(0) res := u64(0)
asm amd64 { asm amd64 {
@ -280,7 +282,7 @@ fn sys_call4(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64) u64 {
S (arg2) S (arg2)
d (arg3) d (arg3)
r (arg4) r (arg4)
; r10 ; r10
} }
return res return res
} }
@ -298,10 +300,12 @@ fn sys_call5(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64, arg5 u64) u64 {
d (arg3) d (arg3)
r (arg4) r (arg4)
r (arg5) r (arg5)
; r10 r8 ; r10
r8
} }
return res return res
} }
fn sys_call6(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64, arg5 u64, arg6 u64) u64 { fn sys_call6(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64, arg5 u64, arg6 u64) u64 {
res := u64(0) res := u64(0)
asm amd64 { asm amd64 {
@ -317,7 +321,9 @@ fn sys_call6(scn u64, arg1 u64, arg2 u64, arg3 u64, arg4 u64, arg5 u64, arg6 u64
r (arg4) r (arg4)
r (arg5) r (arg5)
r (arg6) r (arg6)
; r10 r8 r9 ; r10
r8
r9
} }
return res return res
} }

View File

@ -1,31 +1,31 @@
module builtin module builtin
const ( const (
mem_prot = Mm_prot(int(Mm_prot.prot_read) | int(Mm_prot.prot_write)) mem_prot = Mm_prot(int(Mm_prot.prot_read) | int(Mm_prot.prot_write))
mem_flags = Map_flags(int(Map_flags.map_private) | int(Map_flags.map_anonymous)) mem_flags = Map_flags(int(Map_flags.map_private) | int(Map_flags.map_anonymous))
page_size = u64(Linux_mem.page_size) page_size = u64(Linux_mem.page_size)
) )
pub fn mm_pages(size u64) u32 { pub fn mm_pages(size u64) u32 {
pages := (size+u64(4)+page_size)/page_size pages := (size + u64(4) + page_size) / page_size
return u32(pages) return u32(pages)
} }
pub fn mm_alloc(size u64) (byteptr, Errno) { pub fn mm_alloc(size u64) (byteptr, Errno) {
pages := mm_pages(size) pages := mm_pages(size)
n_bytes := u64(pages*u32(Linux_mem.page_size)) n_bytes := u64(pages * u32(Linux_mem.page_size))
a, e := sys_mmap(0, n_bytes, mem_prot, mem_flags, -1, 0) a, e := sys_mmap(0, n_bytes, mem_prot, mem_flags, -1, 0)
if e == .enoerror { if e == .enoerror {
mut ap := &int(a) mut ap := &int(a)
*ap = pages *ap = pages
return byteptr(a+4), e return byteptr(a + 4), e
} }
return byteptr(0), e return byteptr(0), e
} }
pub fn mm_free(addr byteptr) Errno { pub fn mm_free(addr byteptr) Errno {
ap := &int(addr-4) ap := &int(addr - 4)
size := u64(*ap) * u64(Linux_mem.page_size) size := u64(*ap) * u64(Linux_mem.page_size)
return sys_munmap(ap, size) return sys_munmap(ap, size)
@ -34,7 +34,7 @@ pub fn mm_free(addr byteptr) Errno {
pub fn mem_copy(dest0 voidptr, src0 voidptr, n int) voidptr { pub fn mem_copy(dest0 voidptr, src0 voidptr, n int) voidptr {
mut dest := byteptr(dest0) mut dest := byteptr(dest0)
src := byteptr(src0) src := byteptr(src0)
for i in 0..n { for i in 0 .. n {
dest[i] = src[i] dest[i] = src[i]
} }
return dest0 return dest0

View File

@ -16,7 +16,7 @@ pub fn tos(s byteptr, len int) string {
if s == 0 { if s == 0 {
panic('tos(): nil string') panic('tos(): nil string')
} }
return string { return string{
str: s str: s
len: len len: len
} }
@ -24,17 +24,17 @@ pub fn tos(s byteptr, len int) string {
fn (s string) add(a string) string { fn (s string) add(a string) string {
new_len := a.len + s.len new_len := a.len + s.len
mut res := string { mut res := string{
len: new_len len: new_len
str: malloc(new_len + 1) str: malloc(new_len + 1)
} }
for j in 0..s.len { for j in 0 .. s.len {
res[j] = s[j] res[j] = s[j]
} }
for j in 0..a.len { for j in 0 .. a.len {
res[s.len + j] = a[j] res[s.len + j] = a[j]
} }
res[new_len] = `\0`// V strings are not null terminated, but just in case res[new_len] = `\0` // V strings are not null terminated, but just in case
return res return res
} }
@ -53,7 +53,7 @@ pub fn tos2(s byteptr) string {
if s == 0 { if s == 0 {
panic('tos2: nil string') panic('tos2: nil string')
} }
return string { return string{
str: s str: s
len: strlen(s) len: strlen(s)
} }
@ -63,51 +63,67 @@ pub fn tos3(s charptr) string {
if s == 0 { if s == 0 {
panic('tos3: nil string') panic('tos3: nil string')
} }
return string { return string{
str: byteptr(s) str: byteptr(s)
len: strlen(byteptr(s)) len: strlen(byteptr(s))
} }
} }
pub fn string_eq (s1, s2 string) bool { pub fn string_eq(s1 string, s2 string) bool {
if s1.len != s2.len { return false } if s1.len != s2.len {
for i in 0..s1.len { return false
if s1[i] != s2[i] { return false } }
for i in 0 .. s1.len {
if s1[i] != s2[i] {
return false
}
} }
return true return true
} }
pub fn string_ne (s1, s2 string) bool {
return !string_eq(s1,s2) pub fn string_ne(s1 string, s2 string) bool {
return !string_eq(s1, s2)
} }
pub fn i64_tos(buf byteptr, len int, n0 i64, base int) string { pub fn i64_tos(buf byteptr, len int, n0 i64, base int) string {
if base < 2 { panic("base must be >= 2")} if base < 2 {
if base > 36 { panic("base must be <= 36")} panic('base must be >= 2')
}
if base > 36 {
panic('base must be <= 36')
}
mut b := tos(buf, len) mut b := tos(buf, len)
mut i := len-1 mut i := len - 1
mut n := n0 mut n := n0
neg := n < 0 neg := n < 0
if neg { n = -n } if neg {
n = -n
}
b[i--] = 0 b[i--] = 0
for { for {
c := (n%base) + 48 c := (n % base) + 48
b[i--] = if c > 57 {c+7} else {c} b[i--] = if c > 57 { c + 7 } else { c }
if i < 0 { panic ("buffer to small") } if i < 0 {
panic('buffer to small')
}
n /= base n /= base
if n < 1 {break} if n < 1 {
break
}
} }
if neg { if neg {
if i < 0 { panic ("buffer to small") } if i < 0 {
panic('buffer to small')
}
b[i--] = 45 b[i--] = 45
} }
offset := i+1 offset := i + 1
b.str = b.str + offset b.str = b.str + offset
b.len -= (offset+1) b.len -= (offset + 1)
return b return b
} }
@ -117,14 +133,14 @@ pub fn i64_str(n0 i64, base int) string {
} }
pub fn ptr_str(ptr voidptr) string { pub fn ptr_str(ptr voidptr) string {
buf := [16]byte buf := [16]byte{}
hex := i64_tos(buf, 15, i64(ptr), 16) hex := i64_tos(buf, 15, i64(ptr), 16)
res := '0x' + hex res := '0x' + hex
return res return res
} }
pub fn (a string) clone() string { pub fn (a string) clone() string {
mut b := string { mut b := string{
len: a.len len: a.len
str: malloc(a.len + 1) str: malloc(a.len + 1)
} }

View File

@ -3,7 +3,7 @@
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
module builtin module builtin
//pub fn vsyscall(id int // pub fn vsyscall(id int
// //
/* /*
@ -16,7 +16,6 @@ const (
stdout_value = 1 stdout_value = 1
stderr_value = 2 stderr_value = 2
) )
*/ */
fn builtin_init() { fn builtin_init() {
@ -87,7 +86,7 @@ fn print_backtrace_skipping_top_frames_linux(skipframes int) bool {
return false return false
} $else { } $else {
$if tinyc { $if tinyc {
C.tcc_backtrace("Backtrace") C.tcc_backtrace('Backtrace')
return false return false
} }
buffer := [100]voidptr{} buffer := [100]voidptr{}
@ -101,7 +100,7 @@ fn print_backtrace_skipping_top_frames_linux(skipframes int) bool {
//////csymbols := backtrace_symbols(*voidptr(&buffer[skipframes]), nr_actual_frames) //////csymbols := backtrace_symbols(*voidptr(&buffer[skipframes]), nr_actual_frames)
csymbols := C.backtrace_symbols(voidptr(&buffer[skipframes]), nr_actual_frames) csymbols := C.backtrace_symbols(voidptr(&buffer[skipframes]), nr_actual_frames)
for i in 0 .. nr_actual_frames { for i in 0 .. nr_actual_frames {
sframes << unsafe {tos2( byteptr(csymbols[i]) )} sframes << unsafe { tos2(byteptr(csymbols[i])) }
} }
for sframe in sframes { for sframe in sframes {
executable := sframe.all_before('(') executable := sframe.all_before('(')

View File

@ -88,66 +88,42 @@ pub fn (x f32) strlong() string {
// Example: assert f32_abs(-2.0) == 2.0 // Example: assert f32_abs(-2.0) == 2.0
[inline] [inline]
pub fn f32_abs(a f32) f32 { pub fn f32_abs(a f32) f32 {
return if a < 0 { return if a < 0 { -a } else { a }
-a
} else {
a
}
} }
// f64_abs returns the absolute value of `a` as a `f64` value. // f64_abs returns the absolute value of `a` as a `f64` value.
// Example: assert f64_abs(-2.0) == f64(2.0) // Example: assert f64_abs(-2.0) == f64(2.0)
[inline] [inline]
fn f64_abs(a f64) f64 { fn f64_abs(a f64) f64 {
return if a < 0 { return if a < 0 { -a } else { a }
-a
} else {
a
}
} }
// f32_max returns the largest `f32` of input `a` and `b`. // f32_max returns the largest `f32` of input `a` and `b`.
// Example: assert f32_max(2.0,3.0) == 3.0 // Example: assert f32_max(2.0,3.0) == 3.0
[inline] [inline]
pub fn f32_max(a f32, b f32) f32 { pub fn f32_max(a f32, b f32) f32 {
return if a > b { return if a > b { a } else { b }
a
} else {
b
}
} }
// f32_min returns the smallest `f32` of input `a` and `b`. // f32_min returns the smallest `f32` of input `a` and `b`.
// Example: assert f32_min(2.0,3.0) == 2.0 // Example: assert f32_min(2.0,3.0) == 2.0
[inline] [inline]
pub fn f32_min(a f32, b f32) f32 { pub fn f32_min(a f32, b f32) f32 {
return if a < b { return if a < b { a } else { b }
a
} else {
b
}
} }
// f64_max returns the largest `f64` of input `a` and `b`. // f64_max returns the largest `f64` of input `a` and `b`.
// Example: assert f64_max(2.0,3.0) == 3.0 // Example: assert f64_max(2.0,3.0) == 3.0
[inline] [inline]
pub fn f64_max(a f64, b f64) f64 { pub fn f64_max(a f64, b f64) f64 {
return if a > b { return if a > b { a } else { b }
a
} else {
b
}
} }
// f64_min returns the smallest `f64` of input `a` and `b`. // f64_min returns the smallest `f64` of input `a` and `b`.
// Example: assert f64_min(2.0,3.0) == 2.0 // Example: assert f64_min(2.0,3.0) == 2.0
[inline] [inline]
fn f64_min(a f64, b f64) f64 { fn f64_min(a f64, b f64) f64 {
return if a < b { return if a < b { a } else { b }
a
} else {
b
}
} }
// eq_epsilon returns true if the `f32` is equal to input `b`. // eq_epsilon returns true if the `f32` is equal to input `b`.

View File

@ -1,38 +1,38 @@
fn test_float_decl() { fn test_float_decl() {
//z := 1f // z := 1f
//assert z > 0 // assert z > 0
x1 := 1e10 x1 := 1e10
x2 := -2e16 x2 := -2e16
x3 := 1e-15 x3 := 1e-15
x4 := -9e-4 x4 := -9e-4
assert typeof(x1).name == 'f64' assert typeof(x1).name == 'f64'
assert typeof(x2).name == 'f64' assert typeof(x2).name == 'f64'
assert typeof(x3).name == 'f64' assert typeof(x3).name == 'f64'
assert typeof(x4).name == 'f64' assert typeof(x4).name == 'f64'
x5 := 4e108 x5 := 4e108
x6 := -7e99 x6 := -7e99
x7 := 3e-205 x7 := 3e-205
x8 := -6e-147 x8 := -6e-147
assert typeof(x5).name == 'f64' assert typeof(x5).name == 'f64'
assert typeof(x6).name == 'f64' assert typeof(x6).name == 'f64'
assert typeof(x7).name == 'f64' assert typeof(x7).name == 'f64'
assert typeof(x8).name == 'f64' assert typeof(x8).name == 'f64'
x9 := 312874834.77 x9 := 312874834.77
x10 := -22399994.06 x10 := -22399994.06
x11 := 0.0000000019 x11 := 0.0000000019
x12 := -0.00000000008 x12 := -0.00000000008
assert typeof(x9).name == 'f64' assert typeof(x9).name == 'f64'
assert typeof(x10).name == 'f64' assert typeof(x10).name == 'f64'
assert typeof(x11).name == 'f64' assert typeof(x11).name == 'f64'
assert typeof(x12).name == 'f64' assert typeof(x12).name == 'f64'
x13 := 34234234809890890898903213154353453453253253243432413232228908902183918392183902432432438980380123021983901392183921389083913890389089031.0 x13 := 34234234809890890898903213154353453453253253243432413232228908902183918392183902432432438980380123021983901392183921389083913890389089031.0
x14 := -39999999999999999999222212128182813294989082302832183928343325325233253242312331324392839238239829389038097438248932789371837218372837293.8 x14 := -39999999999999999999222212128182813294989082302832183928343325325233253242312331324392839238239829389038097438248932789371837218372837293.8
x15 := 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002 x15 := 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002
x16 := -0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 x16 := -0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004
assert typeof(x13).name == 'f64' assert typeof(x13).name == 'f64'
assert typeof(x14).name == 'f64' assert typeof(x14).name == 'f64'
assert typeof(x15).name == 'f64' assert typeof(x15).name == 'f64'
assert typeof(x16).name == 'f64' assert typeof(x16).name == 'f64'
} }
fn test_f32_equal_operator() { fn test_f32_equal_operator() {

View File

@ -2,5 +2,5 @@
// Use of this source code is governed by an MIT license that can be found in the LICENSE file. // Use of this source code is governed by an MIT license that can be found in the LICENSE file.
module builtin module builtin
fn float_test() { fn float_test() {
} }

View File

@ -1,19 +1,19 @@
fn test_isnil_byteptr(){ fn test_isnil_byteptr() {
pb := byteptr(0) pb := byteptr(0)
assert isnil( pb ) assert isnil(pb)
} }
fn test_isnil_voidptr(){ fn test_isnil_voidptr() {
pv := voidptr(0) pv := voidptr(0)
assert isnil( pv ) assert isnil(pv)
} }
fn test_isnil_charptr(){ fn test_isnil_charptr() {
pc := &char(0) pc := &char(0)
assert isnil( pc ) assert isnil(pc)
} }
fn test_isnil_intptr(){ fn test_isnil_intptr() {
pi := &int(0) pi := &int(0)
assert isnil( pi ) assert isnil(pi)
} }

View File

@ -15,7 +15,7 @@ pub fn println(s any) {
pub fn print(s any) { pub fn print(s any) {
// TODO // TODO
// $if js.node { // $if js.node {
JS.process.stdout.write(s.toString()) JS.process.stdout.write(s.toString())
// } $else { // } $else {
// panic('Cannot `print` in a browser, use `println` instead') // panic('Cannot `print` in a browser, use `println` instead')
// } // }
@ -28,7 +28,7 @@ pub fn eprintln(s any) {
pub fn eprint(s any) { pub fn eprint(s any) {
// TODO // TODO
// $if js.node { // $if js.node {
JS.process.stderr.write(s.toString()) JS.process.stderr.write(s.toString())
// } $else { // } $else {
// panic('Cannot `eprint` in a browser, use `eprintln` instead') // panic('Cannot `eprint` in a browser, use `eprintln` instead')
// } // }
@ -68,13 +68,13 @@ pub:
} }
pub fn (o Option) str() string { pub fn (o Option) str() string {
if o.state == 0 { if o.state == 0 {
return 'Option{ ok }' return 'Option{ ok }'
} }
if o.state == 1 { if o.state == 1 {
return 'Option{ none }' return 'Option{ none }'
} }
return 'Option{ error: "${o.err}" }' return 'Option{ error: "$o.err" }'
} }
pub fn error(s string) Option { pub fn error(s string) Option {
@ -94,5 +94,4 @@ pub fn error_with_code(s string, code int) Option {
code: code code: code
} }
} }
} }

View File

@ -8,13 +8,17 @@
module builtin module builtin
pub struct JS.Number {} pub struct JS.Number {}
pub struct JS.String { pub struct JS.String {
length JS.Number length JS.Number
} }
pub struct JS.Boolean {} pub struct JS.Boolean {}
pub struct JS.Array { pub struct JS.Array {
length JS.Number length JS.Number
} }
pub struct JS.Map {} pub struct JS.Map {}
// Type prototype functions // Type prototype functions
@ -29,6 +33,7 @@ fn (v JS.Map) toString() JS.String
fn native_str_arr_len(arr []JS.String) int { fn native_str_arr_len(arr []JS.String) int {
len := 0 len := 0
#len = arr.length #len = arr.length
return len return len
} }
@ -41,7 +46,9 @@ fn JS.isFinite(f64) bool
fn JS.decodeURI(string) string fn JS.decodeURI(string) string
fn JS.decodeURIComponent(string) string fn JS.decodeURIComponent(string) string
fn JS.encodeURI(string) string fn JS.encodeURI(string) string
type EncodeURIComponentArg = string | f64 | bool
type EncodeURIComponentArg = bool | f64 | string
fn JS.encodeURIComponent(EncodeURIComponentArg) string fn JS.encodeURIComponent(EncodeURIComponentArg) string
fn JS.escape(string) string fn JS.escape(string) string
fn JS.unescape(string) string fn JS.unescape(string) string

View File

@ -19,7 +19,7 @@ fn JS.clearTimeout(int)
// TODO: js async attribute // TODO: js async attribute
// [js_async] // [js_async]
// fn JS.fetch(RequestInfo, RequestInit) Promise<Response> // fn JS.fetch(RequestInfo, RequestInit) Promise<Response>
fn JS.queueMicrotask(fn()) fn JS.queueMicrotask(fn ())
fn JS.setInterval(any, int, ...any) int fn JS.setInterval(any, int, ...any) int
fn JS.setTimeout(any, int, ...any) int fn JS.setTimeout(any, int, ...any) int
@ -28,8 +28,10 @@ fn JS.blur()
fn JS.captureEvents() fn JS.captureEvents()
fn JS.close() fn JS.close()
fn JS.confirm(string) bool fn JS.confirm(string) bool
// fn JS.departFocus(NavigationReason, FocusNavigationOrigin) // fn JS.departFocus(NavigationReason, FocusNavigationOrigin)
fn JS.focus() fn JS.focus()
// fn JS.getComputedStyle(Element, string | null) CSSStyleDeclaration // fn JS.getComputedStyle(Element, string | null) CSSStyleDeclaration
// fn JS.getMatchedCSSRules(Element, string | null) CSSRuleList // fn JS.getMatchedCSSRules(Element, string | null) CSSRuleList
// fn JS.getSelection() Selection | null // fn JS.getSelection() Selection | null
@ -37,6 +39,7 @@ fn JS.focus()
fn JS.moveBy(int, int) fn JS.moveBy(int, int)
fn JS.moveTo(int, int) fn JS.moveTo(int, int)
fn JS.msWriteProfilerMark(string) fn JS.msWriteProfilerMark(string)
// fn JS.open(string, string, string, bool) ?Window // fn JS.open(string, string, string, bool) ?Window
// fn JS.postMessage(any, string, []Transferable) // fn JS.postMessage(any, string, []Transferable)
fn JS.print() fn JS.print()
@ -44,10 +47,13 @@ fn JS.prompt(string, string) ?string
fn JS.releaseEvents() fn JS.releaseEvents()
fn JS.resizeBy(int, int) fn JS.resizeBy(int, int)
fn JS.resizeTo(int, int) fn JS.resizeTo(int, int)
// fn JS.scroll(ScrollToOptions) // fn JS.scroll(ScrollToOptions)
fn JS.scroll(int, int) fn JS.scroll(int, int)
//fn JS.scrollBy(ScrollToOptions)
// fn JS.scrollBy(ScrollToOptions)
fn JS.scrollBy(int, int) fn JS.scrollBy(int, int)
// fn JS.scrollTo(ScrollToOptions) // fn JS.scrollTo(ScrollToOptions)
fn JS.scrollTo(int, int) fn JS.scrollTo(int, int)
fn JS.stop() fn JS.stop()

View File

@ -14,7 +14,6 @@ pub fn (s string) after(dot string) string {
return string(s.str.slice(s.str.lastIndexOf(dot.str) + 1, int(s.str.length))) return string(s.str.slice(s.str.lastIndexOf(dot.str) + 1, int(s.str.length)))
} }
pub fn (s string) after_char(dot byte) string { pub fn (s string) after_char(dot byte) string {
// TODO: Implement after byte // TODO: Implement after byte
return s return s
@ -97,7 +96,7 @@ pub fn (s string) starts_with(p string) bool {
} }
pub fn (s string) fields() []string { pub fn (s string) fields() []string {
return []// s.str.split() return [] // s.str.split()
} }
pub fn (s string) find_between(start string, end string) string { pub fn (s string) find_between(start string, end string) string {
@ -105,9 +104,9 @@ pub fn (s string) find_between(start string, end string) string {
} }
// unnecessary in the JS backend, implemented for api parity. // unnecessary in the JS backend, implemented for api parity.
pub fn (s string) free () {} pub fn (s string) free() {}
pub fn (s string) hash () int { pub fn (s string) hash() int {
mut h := u32(0) mut h := u32(0)
if h == 0 && s.len > 0 { if h == 0 && s.len > 0 {
for c in s { for c in s {
@ -161,4 +160,4 @@ pub fn (s string) u32() u32 {
// u64 returns the value of the string as u64 `'1'.u64() == u64(1)`. // u64 returns the value of the string as u64 `'1'.u64() == u64(1)`.
pub fn (s string) u64() u64 { pub fn (s string) u64() u64 {
return u64(JS.parseInt(s)) return u64(JS.parseInt(s))
} }

View File

@ -15,9 +15,9 @@ module builtin
// ous benchmarking but can be changed to any number > 1. // ous benchmarking but can be changed to any number > 1.
// `degree` determines the maximum length of each node. // `degree` determines the maximum length of each node.
const ( const (
degree = 6 degree = 6
mid_index = degree - 1 mid_index = degree - 1
max_len = 2 * degree - 1 max_len = 2 * degree - 1
children_bytes = sizeof(voidptr) * (max_len + 1) children_bytes = sizeof(voidptr) * (max_len + 1)
) )
@ -38,7 +38,7 @@ mut:
} }
fn new_sorted_map(n int, value_bytes int) SortedMap { // TODO: Remove `n` fn new_sorted_map(n int, value_bytes int) SortedMap { // TODO: Remove `n`
return SortedMap { return SortedMap{
value_bytes: value_bytes value_bytes: value_bytes
root: new_node() root: new_node()
len: 0 len: 0
@ -59,7 +59,7 @@ fn new_sorted_map_init(n int, value_bytes int, keys &string, values voidptr) Sor
// avoid having to check whether the root is null for // avoid having to check whether the root is null for
// each insertion. // each insertion.
fn new_node() &mapnode { fn new_node() &mapnode {
return &mapnode { return &mapnode{
children: 0 children: 0
len: 0 len: 0
} }
@ -85,13 +85,15 @@ fn (mut m SortedMap) set(key string, value voidptr) {
return return
} }
if key < parent.keys[child_index] { if key < parent.keys[child_index] {
node = unsafe {&mapnode(parent.children[child_index])} node = unsafe { &mapnode(parent.children[child_index]) }
} else { } else {
node = unsafe {&mapnode(parent.children[child_index + 1])} node = unsafe { &mapnode(parent.children[child_index + 1]) }
} }
} }
mut i := 0 mut i := 0
for i < node.len && key > node.keys[i] { i++ } for i < node.len && key > node.keys[i] {
i++
}
if i != node.len && key == node.keys[i] { if i != node.len && key == node.keys[i] {
unsafe { unsafe {
C.memcpy(node.values[i], value, m.value_bytes) C.memcpy(node.values[i], value, m.value_bytes)
@ -116,7 +118,7 @@ fn (mut m SortedMap) set(key string, value voidptr) {
} }
parent = node parent = node
child_index = i child_index = i
node = unsafe {&mapnode(node.children[child_index])} node = unsafe { &mapnode(node.children[child_index]) }
} }
} }
@ -129,7 +131,7 @@ fn (mut n mapnode) split_child(child_index int, mut y mapnode) {
z.values[j] = y.values[j + degree] z.values[j] = y.values[j + degree]
} }
if !isnil(y.children) { if !isnil(y.children) {
z.children = unsafe {&voidptr(malloc(int(children_bytes)))} z.children = unsafe { &voidptr(malloc(int(children_bytes))) }
for jj := degree - 1; jj >= 0; jj-- { for jj := degree - 1; jj >= 0; jj-- {
unsafe { unsafe {
z.children[jj] = y.children[jj + degree] z.children[jj] = y.children[jj + degree]
@ -162,7 +164,9 @@ fn (m SortedMap) get(key string, out voidptr) bool {
mut node := m.root mut node := m.root
for { for {
mut i := node.len - 1 mut i := node.len - 1
for i >= 0 && key < node.keys[i] { i-- } for i >= 0 && key < node.keys[i] {
i--
}
if i != -1 && key == node.keys[i] { if i != -1 && key == node.keys[i] {
unsafe { unsafe {
C.memcpy(out, node.values[i], m.value_bytes) C.memcpy(out, node.values[i], m.value_bytes)
@ -172,7 +176,7 @@ fn (m SortedMap) get(key string, out voidptr) bool {
if isnil(node.children) { if isnil(node.children) {
break break
} }
node = unsafe {&mapnode(node.children[i + 1])} node = unsafe { &mapnode(node.children[i + 1]) }
} }
return false return false
} }
@ -184,14 +188,16 @@ fn (m SortedMap) exists(key string) bool {
mut node := m.root mut node := m.root
for { for {
mut i := node.len - 1 mut i := node.len - 1
for i >= 0 && key < node.keys[i] { i-- } for i >= 0 && key < node.keys[i] {
i--
}
if i != -1 && key == node.keys[i] { if i != -1 && key == node.keys[i] {
return true return true
} }
if isnil(node.children) { if isnil(node.children) {
break break
} }
node = unsafe {&mapnode(node.children[i + 1])} node = unsafe { &mapnode(node.children[i + 1]) }
} }
return false return false
} }
@ -217,16 +223,16 @@ fn (mut n mapnode) remove_key(k string) bool {
if isnil(n.children) { if isnil(n.children) {
return false return false
} }
flag := if idx == n.len {true} else {false} flag := if idx == n.len { true } else { false }
if unsafe {&mapnode(n.children[idx])}.len < degree { if unsafe { &mapnode(n.children[idx]) }.len < degree {
n.fill(idx) n.fill(idx)
} }
mut node := &mapnode(0) mut node := &mapnode(0)
if flag && idx > n.len { if flag && idx > n.len {
node = unsafe {&mapnode(n.children[idx - 1])} node = unsafe { &mapnode(n.children[idx - 1]) }
} else { } else {
node = unsafe {&mapnode(n.children[idx])} node = unsafe { &mapnode(n.children[idx]) }
} }
return node.remove_key(k) return node.remove_key(k)
} }
@ -242,37 +248,37 @@ fn (mut n mapnode) remove_from_leaf(idx int) {
fn (mut n mapnode) remove_from_non_leaf(idx int) { fn (mut n mapnode) remove_from_non_leaf(idx int) {
k := n.keys[idx] k := n.keys[idx]
if unsafe {&mapnode(n.children[idx])}.len >= degree { if unsafe { &mapnode(n.children[idx]) }.len >= degree {
mut current := unsafe {&mapnode(n.children[idx])} mut current := unsafe { &mapnode(n.children[idx]) }
for !isnil(current.children) { for !isnil(current.children) {
current = unsafe {&mapnode(current.children[current.len])} current = unsafe { &mapnode(current.children[current.len]) }
} }
predecessor := current.keys[current.len - 1] predecessor := current.keys[current.len - 1]
n.keys[idx] = predecessor n.keys[idx] = predecessor
n.values[idx] = current.values[current.len - 1] n.values[idx] = current.values[current.len - 1]
mut node := unsafe {&mapnode(n.children[idx])} mut node := unsafe { &mapnode(n.children[idx]) }
node.remove_key(predecessor) node.remove_key(predecessor)
} else if unsafe {&mapnode(n.children[idx + 1])}.len >= degree { } else if unsafe { &mapnode(n.children[idx + 1]) }.len >= degree {
mut current := unsafe {&mapnode(n.children[idx + 1])} mut current := unsafe { &mapnode(n.children[idx + 1]) }
for !isnil(current.children) { for !isnil(current.children) {
current = unsafe {&mapnode(current.children[0])} current = unsafe { &mapnode(current.children[0]) }
} }
successor := current.keys[0] successor := current.keys[0]
n.keys[idx] = successor n.keys[idx] = successor
n.values[idx] = current.values[0] n.values[idx] = current.values[0]
mut node := unsafe {&mapnode(n.children[idx + 1])} mut node := unsafe { &mapnode(n.children[idx + 1]) }
node.remove_key(successor) node.remove_key(successor)
} else { } else {
n.merge(idx) n.merge(idx)
mut node := unsafe {&mapnode(n.children[idx])} mut node := unsafe { &mapnode(n.children[idx]) }
node.remove_key(k) node.remove_key(k)
} }
} }
fn (mut n mapnode) fill(idx int) { fn (mut n mapnode) fill(idx int) {
if idx != 0 && unsafe {&mapnode(n.children[idx - 1])}.len >= degree { if idx != 0 && unsafe { &mapnode(n.children[idx - 1]) }.len >= degree {
n.borrow_from_prev(idx) n.borrow_from_prev(idx)
} else if idx != n.len && unsafe {&mapnode(n.children[idx + 1])}.len >= degree { } else if idx != n.len && unsafe { &mapnode(n.children[idx + 1]) }.len >= degree {
n.borrow_from_next(idx) n.borrow_from_next(idx)
} else if idx != n.len { } else if idx != n.len {
n.merge(idx) n.merge(idx)
@ -282,8 +288,8 @@ fn (mut n mapnode) fill(idx int) {
} }
fn (mut n mapnode) borrow_from_prev(idx int) { fn (mut n mapnode) borrow_from_prev(idx int) {
mut child := unsafe {&mapnode(n.children[idx])} mut child := unsafe { &mapnode(n.children[idx]) }
mut sibling := unsafe {&mapnode(n.children[idx - 1])} mut sibling := unsafe { &mapnode(n.children[idx - 1]) }
for i := child.len - 1; i >= 0; i-- { for i := child.len - 1; i >= 0; i-- {
child.keys[i + 1] = child.keys[i] child.keys[i + 1] = child.keys[i]
child.values[i + 1] = child.values[i] child.values[i + 1] = child.values[i]
@ -309,8 +315,8 @@ fn (mut n mapnode) borrow_from_prev(idx int) {
} }
fn (mut n mapnode) borrow_from_next(idx int) { fn (mut n mapnode) borrow_from_next(idx int) {
mut child := unsafe {&mapnode(n.children[idx])} mut child := unsafe { &mapnode(n.children[idx]) }
mut sibling := unsafe {&mapnode(n.children[idx + 1])} mut sibling := unsafe { &mapnode(n.children[idx + 1]) }
child.keys[child.len] = n.keys[idx] child.keys[child.len] = n.keys[idx]
child.values[child.len] = n.values[idx] child.values[child.len] = n.values[idx]
if !isnil(child.children) { if !isnil(child.children) {
@ -336,11 +342,11 @@ fn (mut n mapnode) borrow_from_next(idx int) {
} }
fn (mut n mapnode) merge(idx int) { fn (mut n mapnode) merge(idx int) {
mut child := unsafe {&mapnode(n.children[idx])} mut child := unsafe { &mapnode(n.children[idx]) }
sibling := unsafe {&mapnode(n.children[idx + 1])} sibling := unsafe { &mapnode(n.children[idx + 1]) }
child.keys[mid_index] = n.keys[idx] child.keys[mid_index] = n.keys[idx]
child.values[mid_index] = n.values[idx] child.values[mid_index] = n.values[idx]
for i in 0..sibling.len { for i in 0 .. sibling.len {
child.keys[i + degree] = sibling.keys[i] child.keys[i + degree] = sibling.keys[i]
child.values[i + degree] = sibling.values[i] child.values[i + degree] = sibling.values[i]
} }
@ -380,7 +386,7 @@ pub fn (mut m SortedMap) delete(key string) {
if isnil(m.root.children) { if isnil(m.root.children) {
return return
} else { } else {
m.root = unsafe {&mapnode(m.root.children[0])} m.root = unsafe { &mapnode(m.root.children[0]) }
} }
// free(tmp) // free(tmp)
} }
@ -393,18 +399,18 @@ fn (n &mapnode) subkeys(mut keys []string, at int) int {
if !isnil(n.children) { if !isnil(n.children) {
// Traverse children and insert // Traverse children and insert
// keys inbetween children // keys inbetween children
for i in 0..n.len { for i in 0 .. n.len {
child := unsafe {&mapnode(n.children[i])} child := unsafe { &mapnode(n.children[i]) }
position += child.subkeys(mut keys, position) position += child.subkeys(mut keys, position)
keys[position] = n.keys[i] keys[position] = n.keys[i]
position++ position++
} }
// Insert the keys of the last child // Insert the keys of the last child
child := unsafe {&mapnode(n.children[n.len])} child := unsafe { &mapnode(n.children[n.len]) }
position += child.subkeys(mut keys, position) position += child.subkeys(mut keys, position)
} else { } else {
// If leaf, insert keys // If leaf, insert keys
for i in 0..n.len { for i in 0 .. n.len {
keys[position + i] = n.keys[i] keys[position + i] = n.keys[i]
} }
position += n.len position += n.len
@ -414,7 +420,7 @@ fn (n &mapnode) subkeys(mut keys []string, at int) int {
} }
pub fn (m &SortedMap) keys() []string { pub fn (m &SortedMap) keys() []string {
mut keys := []string{len:m.len} mut keys := []string{len: m.len}
if isnil(m.root) || m.root.len == 0 { if isnil(m.root) || m.root.len == 0 {
return keys return keys
} }

View File

@ -1,11 +1,11 @@
fn test_common_atoi() { fn test_common_atoi() {
// test common cases // test common cases
assert "70zzz".int() == 70 assert '70zzz'.int() == 70
assert "2901issue".int() == 2901 assert '2901issue'.int() == 2901
assert '234232w'.int() == 234232 assert '234232w'.int() == 234232
assert '-9009x'.int() == -9009 assert '-9009x'.int() == -9009
assert '0y'.int() == 0 assert '0y'.int() == 0
// test lead zeros // test lead zeros
assert '0000012'.int() == 12 assert '0000012'.int() == 12
assert '-0000012'.int() == -12 assert '-0000012'.int() == -12
@ -21,7 +21,7 @@ fn test_common_atoi() {
assert '10_000_000'.int() == 10000000 assert '10_000_000'.int() == 10000000
for n in -10000 .. 100000 { for n in -10000 .. 100000 {
s := n.str()+"z" s := n.str() + 'z'
assert s.int() == n assert s.int() == n
} }
} }
@ -29,11 +29,11 @@ fn test_common_atoi() {
fn test_unsigned_cast() { fn test_unsigned_cast() {
// tests for u16 // tests for u16
// test common cases // test common cases
assert "70zzz".u16() == 70 assert '70zzz'.u16() == 70
assert "2901issue".u16() == 2901 assert '2901issue'.u16() == 2901
assert '0y'.u16() == 0 assert '0y'.u16() == 0
// test lead zeros // test lead zeros
assert '0000012'.u16() == 12 assert '0000012'.u16() == 12
assert '0x001F'.u16() == 31 assert '0x001F'.u16() == 31
@ -43,13 +43,13 @@ fn test_unsigned_cast() {
// tests for u32 // tests for u32
// test common cases // test common cases
assert "70zzz".u32() == 70 assert '70zzz'.u32() == 70
assert "2901issue".u32() == 2901 assert '2901issue'.u32() == 2901
assert '234232w'.u32() == 234232 assert '234232w'.u32() == 234232
assert '-9009x'.u32() == 0 assert '-9009x'.u32() == 0
assert '0y'.u32() == 0 assert '0y'.u32() == 0
// test lead zeros // test lead zeros
assert '0000012'.u32() == 12 assert '0000012'.u32() == 12
assert '-0000012'.u32() == 0 assert '-0000012'.u32() == 0
@ -65,19 +65,19 @@ fn test_unsigned_cast() {
assert '10_000_000'.u32() == 10000000 assert '10_000_000'.u32() == 10000000
for n in 0 .. 100 { for n in 0 .. 100 {
s := n.str()+"z" s := n.str() + 'z'
assert s.u32() == n assert s.u32() == n
} }
// tests for u64 // tests for u64
// test common cases // test common cases
assert "70zzz".u64() == 70 assert '70zzz'.u64() == 70
assert "2901issue".u64() == 2901 assert '2901issue'.u64() == 2901
assert '234232w'.u64() == 234232 assert '234232w'.u64() == 234232
assert '-9009x'.u64() == 0 assert '-9009x'.u64() == 0
assert '0y'.u64() == 0 assert '0y'.u64() == 0
// test lead zeros // test lead zeros
assert '0000012'.u64() == 12 assert '0000012'.u64() == 12
assert '-0000012'.u64() == 0 assert '-0000012'.u64() == 0
@ -93,22 +93,21 @@ fn test_unsigned_cast() {
assert '10_000_000'.u64() == 10000000 assert '10_000_000'.u64() == 10000000
for n in 0 .. 10000 { for n in 0 .. 10000 {
s := n.str()+"z" s := n.str() + 'z'
assert s.u64() == n assert s.u64() == n
} }
} }
fn test_signed_cast() { fn test_signed_cast() {
// tests for i64 // tests for i64
// test common cases // test common cases
assert "70zzz".i64() == 70 assert '70zzz'.i64() == 70
assert "2901issue".i64() == 2901 assert '2901issue'.i64() == 2901
assert '234232w'.i64() == 234232 assert '234232w'.i64() == 234232
assert '-9009x'.i64() == -9009 assert '-9009x'.i64() == -9009
assert '0y'.i64() == 0 assert '0y'.i64() == 0
// test lead zeros // test lead zeros
assert '0000012'.i64() == 12 assert '0000012'.i64() == 12
assert '-0000012'.i64() == -12 assert '-0000012'.i64() == -12
@ -124,19 +123,19 @@ fn test_signed_cast() {
assert '10_000_000'.i64() == 10000000 assert '10_000_000'.i64() == 10000000
for n in -10000 .. 100000 { for n in -10000 .. 100000 {
s := n.str()+"z" s := n.str() + 'z'
assert s.i64() == n assert s.i64() == n
} }
// tests for i8 // tests for i8
// test common cases // test common cases
assert "70zzz".i8() == 70 assert '70zzz'.i8() == 70
assert "29issue".i8() == 29 assert '29issue'.i8() == 29
assert '22w'.i8() == 22 assert '22w'.i8() == 22
assert '-90x'.i8() == -90 assert '-90x'.i8() == -90
assert '0y'.i8() == 0 assert '0y'.i8() == 0
// test lead zeros // test lead zeros
assert '0000012'.i8() == 12 assert '0000012'.i8() == 12
assert '-0000012'.i8() == -12 assert '-0000012'.i8() == -12
@ -152,19 +151,19 @@ fn test_signed_cast() {
assert '10_0'.i8() == 100 assert '10_0'.i8() == 100
for n in -10 .. 100 { for n in -10 .. 100 {
s := n.str()+"z" s := n.str() + 'z'
assert s.i8() == n assert s.i8() == n
} }
// tests for i16 // tests for i16
// test common cases // test common cases
assert "70zzz".i16() == 70 assert '70zzz'.i16() == 70
assert "2901issue".i16() == 2901 assert '2901issue'.i16() == 2901
assert '2342w'.i16() == 2342 assert '2342w'.i16() == 2342
assert '-9009x'.i16() == -9009 assert '-9009x'.i16() == -9009
assert '0y'.i16() == 0 assert '0y'.i16() == 0
// test lead zeros // test lead zeros
assert '0000012'.i16() == 12 assert '0000012'.i16() == 12
assert '-0000012'.i16() == -12 assert '-0000012'.i16() == -12
@ -180,7 +179,7 @@ fn test_signed_cast() {
assert '10_0'.i16() == 100 assert '10_0'.i16() == 100
for n in -100 .. 100 { for n in -100 .. 100 {
s := n.str()+"z" s := n.str() + 'z'
assert s.i16() == n assert s.i16() == n
} }
} }

View File

@ -3,10 +3,7 @@
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
fn test_strip_margins_no_tabs() { fn test_strip_margins_no_tabs() {
no_tabs := ['Hello there', no_tabs := ['Hello there', 'This is a string', 'With multiple lines'].join('\n')
'This is a string',
'With multiple lines',
].join('\n')
no_tabs_stripped := 'Hello there no_tabs_stripped := 'Hello there
|This is a string |This is a string
|With multiple lines'.strip_margin() |With multiple lines'.strip_margin()
@ -14,10 +11,7 @@ fn test_strip_margins_no_tabs() {
} }
fn test_strip_margins_text_before() { fn test_strip_margins_text_before() {
text_before := ['There is text', text_before := ['There is text', 'before the delimiter', 'that should be removed as well'].join('\n')
'before the delimiter',
'that should be removed as well',
].join('\n')
text_before_stripped := 'There is text text_before_stripped := 'There is text
f lasj asldfj j lksjdf |before the delimiter f lasj asldfj j lksjdf |before the delimiter
Which is removed hello |that should be removed as well'.strip_margin() Which is removed hello |that should be removed as well'.strip_margin()
@ -25,10 +19,7 @@ fn test_strip_margins_text_before() {
} }
fn test_strip_margins_white_space_after_delim() { fn test_strip_margins_white_space_after_delim() {
tabs := [' Tab', tabs := [' Tab', ' spaces', ' another tab'].join('\n')
' spaces',
' another tab',
].join('\n')
tabs_stripped := ' Tab tabs_stripped := ' Tab
| spaces | spaces
| another tab'.strip_margin() | another tab'.strip_margin()
@ -36,10 +27,9 @@ fn test_strip_margins_white_space_after_delim() {
} }
fn test_strip_margins_alternate_delim() { fn test_strip_margins_alternate_delim() {
alternate_delimiter := ['This has a different delim,', alternate_delimiter := ['This has a different delim,', 'but that is ok',
'but that is ok', 'because everything works',
'because everything works', ].join('\n')
].join('\n')
alternate_delimiter_stripped := 'This has a different delim, alternate_delimiter_stripped := 'This has a different delim,
#but that is ok #but that is ok
#because everything works'.strip_margin_custom(`#`) #because everything works'.strip_margin_custom(`#`)
@ -48,9 +38,7 @@ fn test_strip_margins_alternate_delim() {
fn test_strip_margins_multiple_delims_after_first() { fn test_strip_margins_multiple_delims_after_first() {
delim_after_first_instance := ['The delimiter used', delim_after_first_instance := ['The delimiter used',
'only matters the |||| First time it is seen', 'only matters the |||| First time it is seen', 'not any | other | times'].join('\n')
'not any | other | times',
].join('\n')
delim_after_first_instance_stripped := 'The delimiter used delim_after_first_instance_stripped := 'The delimiter used
|only matters the |||| First time it is seen |only matters the |||| First time it is seen
|not any | other | times'.strip_margin() |not any | other | times'.strip_margin()
@ -58,22 +46,21 @@ fn test_strip_margins_multiple_delims_after_first() {
} }
fn test_strip_margins_uneven_delims() { fn test_strip_margins_uneven_delims() {
uneven_delims := ['It doesn\'t matter if the delims are uneven,', uneven_delims := ["It doesn't matter if the delims are uneven,",
'The text will still be delimited correctly.', 'The text will still be delimited correctly.', 'Maybe not everything needs 3 lines?',
'Maybe not everything needs 3 lines?', 'Let us go for 4 then',
'Let us go for 4 then', ].join('\n')
].join('\n') uneven_delims_stripped := "It doesn't matter if the delims are uneven,
uneven_delims_stripped := 'It doesn\'t matter if the delims are uneven,
|The text will still be delimited correctly. |The text will still be delimited correctly.
|Maybe not everything needs 3 lines? |Maybe not everything needs 3 lines?
|Let us go for 4 then'.strip_margin() |Let us go for 4 then".strip_margin()
assert uneven_delims_stripped == uneven_delims assert uneven_delims_stripped == uneven_delims
} }
fn test_strip_margins_multiple_blank_lines() { fn test_strip_margins_multiple_blank_lines() {
multi_blank_lines := ['Multiple blank lines will be removed.', multi_blank_lines := ['Multiple blank lines will be removed.',
' I actually consider this a feature.', ' I actually consider this a feature.',
].join('\n') ].join('\n')
multi_blank_lines_stripped := 'Multiple blank lines will be removed. multi_blank_lines_stripped := 'Multiple blank lines will be removed.
@ -83,10 +70,7 @@ fn test_strip_margins_multiple_blank_lines() {
} }
fn test_strip_margins_end_newline() { fn test_strip_margins_end_newline() {
end_with_newline := ['This line will end with a newline', end_with_newline := ['This line will end with a newline', 'Something cool or something.', ''].join('\n')
'Something cool or something.',
'',
].join('\n')
end_with_newline_stripped := 'This line will end with a newline end_with_newline_stripped := 'This line will end with a newline
|Something cool or something. |Something cool or something.
@ -95,22 +79,17 @@ fn test_strip_margins_end_newline() {
} }
fn test_strip_margins_space_delimiter() { fn test_strip_margins_space_delimiter() {
space_delimiter := ['Using a white-space char will', space_delimiter := ['Using a white-space char will', 'revert back to default behavior.'].join('\n')
'revert back to default behavior.',
].join('\n')
space_delimiter_stripped := 'Using a white-space char will space_delimiter_stripped := 'Using a white-space char will
|revert back to default behavior.'.strip_margin_custom(`\n`) |revert back to default behavior.'.strip_margin_custom(`\n`)
assert space_delimiter == space_delimiter_stripped assert space_delimiter == space_delimiter_stripped
} }
fn test_strip_margins_crlf() { fn test_strip_margins_crlf() {
crlf := ['This string\'s line endings have CR as well as LFs.', crlf := ["This string's line endings have CR as well as LFs.", 'This should pass', 'Definitely'].join('\r\n')
'This should pass', crlf_stripped := "This string's line endings have CR as well as LFs.\r
'Definitely',
].join('\r\n')
crlf_stripped := 'This string\'s line endings have CR as well as LFs.\r
|This should pass\r |This should pass\r
|Definitely'.strip_margin() |Definitely".strip_margin()
assert crlf == crlf_stripped assert crlf == crlf_stripped
} }

View File

@ -7,8 +7,8 @@ const (
pub fn (_str string) to_wide() &u16 { pub fn (_str string) to_wide() &u16 {
$if windows { $if windows {
unsafe { unsafe {
num_chars := (C.MultiByteToWideChar(cp_utf8, 0, charptr(_str.str), _str.len, 0, num_chars := (C.MultiByteToWideChar(cp_utf8, 0, charptr(_str.str), _str.len,
0)) 0, 0))
mut wstr := &u16(malloc((num_chars + 1) * 2)) // sizeof(wchar_t) mut wstr := &u16(malloc((num_chars + 1) * 2)) // sizeof(wchar_t)
if wstr != 0 { if wstr != 0 {
C.MultiByteToWideChar(cp_utf8, 0, charptr(_str.str), _str.len, wstr, num_chars) C.MultiByteToWideChar(cp_utf8, 0, charptr(_str.str), _str.len, wstr, num_chars)