Bug 5379 – std.array.replace fails on char[]s

Status
RESOLVED
Resolution
WONTFIX
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Mac OS X
Creation time
2010-12-27T00:42:00Z
Last change time
2011-01-03T05:55:54Z
Assigned to
nobody
Creator
oag

Comments

Comment #0 by oag — 2010-12-27T00:42:34Z
import std.stdio; import std.array; void main() { char[] s = "abcdef".dup; char[] t = "xxxx".dup; replace(s, 2, 4, t); writefln("s = %s", s); } /+ Gives me the following compile error: mymble:d oag$ dmd replace.d replace.d(7): Error: template std.array.replace(T,Range) if (is(ElementType!(Range) == T)) does not match any function template declaration replace.d(7): Error: template std.array.replace(T,Range) if (is(ElementType!(Range) == T)) cannot deduce template function from argument types !()(char[],int,int,char[]) It appears to think that ElementType!(char[]) is dchar. +/
Comment #1 by bugzilla — 2011-01-03T05:55:54Z
The thing is, char[] is assumed to be UTF-8 encoded, which means that one array element doesn't necessarily correspond to one symbol (or, more precisely, one code point may be composed of several code units). That's why (from a range point of view) the element type of char[] is dchar, which is UTF-32 encoded, or "decoded" in the sense that one element is one symbol. Here's an example to prove the point: char[] foo = "ångstrøm"; replace(foo, 0, 1, "a"); If this were allowed, foo would not contain "angstrøm" as one may expect, it would contain garbage. This is because the first character, "å", spans two array elements. You have two options: 1. If you want to use std.array.replace() like this with character arrays, you should use dchar[]. 2. Use std.string.replace(), which works with strings but always allocates. I am closing this as WONTFIX. There are several people who disagree with dchar being the range element type of char[], however, so feel free to reopen as an enhancement request if you wish.