From 887ee0fd419d3b84b1d2ccadc7322d039593edd6 Mon Sep 17 00:00:00 2001 From: visualfc Date: Wed, 26 Jun 2024 20:09:38 +0800 Subject: [PATCH] ssa: fix slice high --- internal/lib/internal/bytealg/bytealg.go | 67 ++++++++++++++++++++++++ ssa/datastruct.go | 3 +- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/internal/lib/internal/bytealg/bytealg.go b/internal/lib/internal/bytealg/bytealg.go index c7cf2ac3..bf35e55c 100644 --- a/internal/lib/internal/bytealg/bytealg.go +++ b/internal/lib/internal/bytealg/bytealg.go @@ -21,6 +21,7 @@ import ( "unsafe" "github.com/goplus/llgo/c" + "github.com/goplus/llgo/internal/runtime" ) func IndexByte(b []byte, ch byte) int { @@ -40,3 +41,69 @@ func IndexByteString(s string, ch byte) int { } return -1 } + +func Count(b []byte, c byte) int { + n := 0 + for _, x := range b { + if x == c { + n++ + } + } + return n +} + +func CountString(s string, c byte) int { + n := 0 + for i := 0; i < len(s); i++ { + if s[i] == c { + n++ + } + } + return n +} + +func Index(a, b []byte) int { + for i := 0; i <= len(b)-len(a); i++ { + if equal(a, b[i:i+len(a)]) { + return i + } + } + return -1 +} + +// IndexString returns the index of the first instance of b in a, or -1 if b is not present in a. +// Requires 2 <= len(b) <= MaxLen. +func IndexString(a, b string) int { + for i := 0; i <= len(a)-len(b); i++ { + if a[i:i+len(b)] == b { + return i + } + } + return -1 +} + +// MakeNoZero makes a slice of length and capacity n without zeroing the bytes. +// It is the caller's responsibility to ensure uninitialized bytes +// do not leak to the end user. +func MakeNoZero(n int) (r []byte) { + s := (*sliceHead)(unsafe.Pointer(&r)) + s.data = runtime.AllocU(uintptr(n)) + s.len = n + s.cap = n + return +} + +func equal(a, b []byte) bool { + s1 := (*sliceHead)(unsafe.Pointer(&a)) + s2 := (*sliceHead)(unsafe.Pointer(&b)) + if s1.len == s2.len { + return c.Memcmp(s1.data, s2.data, uintptr(s1.len)) == 0 + } + return false +} + +type sliceHead struct { + data unsafe.Pointer + len int + cap int +} diff --git a/ssa/datastruct.go b/ssa/datastruct.go index 82706e0a..7ec0e1ec 100644 --- a/ssa/datastruct.go +++ b/ssa/datastruct.go @@ -333,6 +333,7 @@ func (b Builder) Slice(x, low, high, max Expr) (ret Expr) { if debugInstr { log.Printf("Slice %v, %v, %v\n", x.impl, low.impl, high.impl) } + prog := b.Prog var nCap Expr var nEltSize Expr @@ -356,7 +357,7 @@ func (b Builder) Slice(x, low, high, max Expr) (ret Expr) { nEltSize = SizeOf(prog, prog.Index(x.Type)) nCap = b.SliceCap(x) if high.IsNil() { - high = b.SliceCap(x) + high = b.SliceLen(x) } ret.Type = x.Type base = b.SliceData(x)