Skip to content

Conversation

squeek502
Copy link
Collaborator

@squeek502 squeek502 commented Sep 14, 2025

This is just clarifying the current behavior of std.mem.replace.

Test case showing the behavior when input/output overlap (adapted from here):

const std = @import("std");

test "mem.replace overlap" {
    var buf: [256]u8 = undefined;
    const original = "Sweet apple cake. Sour crabapple pie.";
    const expected = "Sweet orange cake. Sour craborange pie.";
    buf[0..original.len].* = original.*;
    const str = buf[0..original.len];

    const needed_size = std.mem.replacementSize(u8, str, "apple", "orange");
    const output = buf[0..needed_size];
    _ = std.mem.replace(u8, str, "apple", "orange", output);
    try std.testing.expectEqualStrings(expected, output);
}
====== expected this output: =========
Sweet orange cake. Sour craborange pie.␃

======== instead found this: =========
Sweet orangeeeeeeeeeeeeeeeeeeeeeeeeeee�␃

======================================
First difference occurs on line 1:
expected:
Sweet orange cake. Sour craborange pie.
            ^ ('\x20')
found:
Sweet orangeeeeeeeeeeeeeeeeeeeeeeeeeee�
            ^ ('\x65')

@jeffective
Copy link
Contributor

is this not a usecase for the noalias keyword? Unfortunately its undocumented in the langref.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants