mem
Copy raw bytes between memory regions, including overlapping regions.
Copy bytes#
Import mem and call mem.Copy(src, dest, bytes) to copy exactly bytes bytes from source to destination. The signature is func Copy(src *void, dest *void, bytes int). Source comes first and destination second. Copy returns no value and does not allocate memory.
Pass pointers to addressable values or array elements, or use an array’s .data to point to its payload. The count is in bytes; an array’s .size gives its payload size in bytes, while len counts elements.
package main;
import "mem";
func main() {
source: u8[4] = {0, 128, 255, 42};
dest: u8[6] = {9, 9, 9, 9, 9, 9};
mem.Copy(source.data, &dest[1], source.size);
if (dest != u8[6]{9, 0, 128, 255, 42, 9}) {
panic "unexpected copied bytes";
}
}
Overlapping regions#
Source and destination may overlap in either direction. The result is the same as copying the requested source bytes through a temporary snapshot, without allocating that snapshot. Bytes outside the destination region stay unchanged. Copying a region onto itself leaves it unchanged.
package main;
import "mem";
func main() {
data: u8[4] = {1, 2, 3, 4};
mem.Copy(&data[0], &data[1], 3);
// data is now {1, 1, 2, 3}.
mem.Copy(&data[1], &data[0], 3);
// data is now {1, 2, 3, 3}.
if (data != u8[4]{1, 2, 3, 3}) {
panic "unexpected overlapping copy";
}
}
Storage and byte counts#
The caller must provide readable source storage and writable destination storage for the requested byte count. Copy does not check allocation boundaries or extend the destination. Both regions must remain valid throughout the call.
A zero byte count accesses neither pointer, so mem.Copy(null, null, 0) is valid. A negative byte count panics, including when both pointers are equal.
Copy transfers raw bytes without copying ownership or adjusting references. Use ordinary Ocean assignment to copy values containing owned strings, dynamic arrays, maps, or other owned data.