Commit a1646fd5 authored by Russ Cox's avatar Russ Cox

make bytes.Copy both src- and dst- limited

and return the number of bytes copied.

R=r
DELTA=18  (6 added, 0 deleted, 12 changed)
OCL=30693
CL=30712
parent 354e61cc
...@@ -41,10 +41,14 @@ func Equal(a, b []byte) bool { ...@@ -41,10 +41,14 @@ func Equal(a, b []byte) bool {
return true return true
} }
// Copy copies the source to the destination, stopping when the source // Copy copies bytes from src to dst,
// is all transferred. The caller must guarantee that there is enough // stopping when either all of src has been copied
// room in the destination. It returns the number of bytes copied // or all of dst has been filled.
// It returns the number of bytes copied.
func Copy(dst, src []byte) int { func Copy(dst, src []byte) int {
if len(src) > len(dst) {
src = src[0:len(dst)];
}
for i, x := range src { for i, x := range src {
dst[i] = x dst[i] = x
} }
......
...@@ -132,25 +132,27 @@ func TestSplit(t *testing.T) { ...@@ -132,25 +132,27 @@ func TestSplit(t *testing.T) {
type CopyTest struct { type CopyTest struct {
a string; a string;
b string; b string;
n int;
res string; res string;
} }
var copytests = []CopyTest { var copytests = []CopyTest {
CopyTest{ "", "", "" }, CopyTest{ "", "", 0, "" },
CopyTest{ "a", "", "a" }, CopyTest{ "a", "", 0, "a" },
CopyTest{ "a", "a", "a" }, CopyTest{ "a", "a", 1, "a" },
CopyTest{ "a", "b", "b" }, CopyTest{ "a", "b", 1, "b" },
CopyTest{ "xyz", "abc", "abc" }, CopyTest{ "xyz", "abc", 3, "abc" },
CopyTest{ "wxyz", "abc", "abcz" }, CopyTest{ "wxyz", "abc", 3, "abcz" },
CopyTest{ "xyz", "abcd", 3, "abc" },
} }
func TestCopy(t *testing.T) { func TestCopy(t *testing.T) {
for i := 0; i < len(copytests); i++ { for i := 0; i < len(copytests); i++ {
tt := copytests[i]; tt := copytests[i];
dst := io.StringBytes(tt.a); dst := io.StringBytes(tt.a);
Copy(dst, io.StringBytes(tt.b)); n := Copy(dst, io.StringBytes(tt.b));
result := string(dst); result := string(dst);
if result != tt.res { if result != tt.res || n != tt.n {
t.Errorf(`Copy("%s", "%s") = "%s"; want "%s"`, tt.a, tt.b, result, tt.res); t.Errorf(`Copy(%q, %q) = %d, %q; want %d, %q`, tt.a, tt.b, n, result, tt.n, tt.res);
continue; continue;
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment