XO0541: a view of a reused buffer kept past the next read
A Bytes or Str slice is a view of its parent (decision 0330), not a copy. A receive buffer (raw.bytes_buf) read into on every pass of a loop changes under every view kept from an earlier pass: a message list built from buf[a..b] ends up showing the last read’s bytes. xo vet reports such a slice when the loop passes the buffer to a call and the slice, or a local bound to it, is pushed to or stored in a collection or variable declared outside the loop, or returned. Copy what outlives the buffer with .clone(); // xo:allow XO0541 reason when nothing writes the buffer again.
Example
let buf = raw.bytes_buf(4096)
var msgs: List[Bytes] = []
while true {
let n = recv(fd, buf)
if n <= 0 { break }
msgs.push(buf[0..n])
}Fix
let buf = raw.bytes_buf(4096)
var msgs: List[Bytes] = []
while true {
let n = recv(fd, buf)
if n <= 0 { break }
msgs.push(buf[0..n].clone())
}Run xo explain XO0541 for this text in a terminal, or see
section 10.6 of the specification.