Skip to content

Commit

Permalink
Merge pull request #11 from qiniu/develop
Browse files Browse the repository at this point in the history
Release v7.0.5
  • Loading branch information
xushiwei committed Jul 13, 2015
2 parents 7687314 + 3a8250f commit 85a65f6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
21 changes: 13 additions & 8 deletions bytes.v7/replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,24 @@ import (

// ---------------------------------------------------

func ReplaceAt(b []byte, off int, src, dest []byte) []byte {
func ReplaceAt(b []byte, off, nsrc int, dest []byte) []byte {

nsrc, ndest := len(src), len(dest)
if nsrc >= ndest {
ndelta := len(dest) - nsrc
if ndelta < 0 {
left := b[off+nsrc:]
off += copy(b[off:], dest)
off += copy(b[off:], left)
return b[:off]
}
tailoff := len(b) - (ndest - nsrc)
b = append(b, b[tailoff:]...)
copy(b[off+ndest:], b[off+nsrc:len(b)])
copy(b[off:], dest)

if ndelta > 0 {
tailoff := len(b) - ndelta
b = append(b, b[tailoff:]...)
copy(b[off+len(dest):], b[off+nsrc:])
copy(b[off:], dest)
} else {
copy(b[off:], dest)
}
return b
}

Expand All @@ -30,7 +35,7 @@ func ReplaceOne(b []byte, from int, src, dest []byte) ([]byte, int) {
}

from += pos
return ReplaceAt(b, from, src, dest), from + len(dest)
return ReplaceAt(b, from, len(src), dest), from + len(dest)
}

func Replace(b []byte, src, dest []byte, n int) []byte {
Expand Down
15 changes: 15 additions & 0 deletions bytes.v7/replace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ func TestReplace(t *testing.T) {
cases := []replaceCase{
{"hello, world!", "world", "xsw", -1},
{"hello, world world world", "world", "xsw", 1},
{"hello, world world world", "world", "xsw", 2},
{"hello, world world world", "world", "xsw", -1},
{"hello, xsw!", "xsw", "world", -1},
{"hello, xsw xsw xsw", "xsw", "world", 1},
{"hello, xsw xsw xsw", "xsw", "world", 2},
{"hello, xsw xsw xsw", "xsw", "world", -1},
}

Expand All @@ -37,3 +39,16 @@ func TestReplace(t *testing.T) {
}
}

func stringInsertAt(b string, off int, text string) string {

return string(ReplaceAt([]byte(b), off, 0, []byte(text)))
}

func TestInsertAt(t *testing.T) {

ret := stringInsertAt("helloworld", 5, ", ")
if ret != "hello, world" {
t.Fatal("InsertAt failed:", ret)
}
}

0 comments on commit 85a65f6

Please sign in to comment.