toChars buffer access?

bauss jj_1337 at live.dk
Thu Jun 9 20:31:53 UTC 2022


On Thursday, 9 June 2022 at 14:44:55 UTC, Salih Dincer wrote:
> On Sunday, 23 August 2020 at 19:18:51 UTC, Steven Schveighoffer 
> wrote:
>> I was about to reach for 
>> core.internal.string.signedToTempString [1] to convert a 
>> number into a temp string yet again. And I thought, maybe 
>> there's something in Phobos by now.
>>
>> And lo and behold! There's std.conv.toChars [2]
>>
>> But... it just gives me a range of char, and not an actual 
>> string. So my intended purpose (to use it as a string key for 
>> an associative array) means I have to copy it to a local 
>> buffer anyway.
>>
>> No matter, right? It probably just stores the number and gives 
>> me access to each character as it parses. Oh wait, no. It 
>> actually stores it as a char[20], but doesn't give me access.
>>
>> Which leaves me with the only option of doing:
>> ```d
>> auto s = someNumber.toChars;
>> char[20] buf;
>> import std.algorithm : copy;
>> copy(s.save, buf[0 .. s.length]);
>>
>> auto v = aa[buf[0 .. s.length]];
>> ```
>> But my goodness, it would just be so easy if it gave access to 
>> the buffer:
>> ```d
>> auto s = someNumber.toChars;
>> auto v = aa[s.data]; // @system access to buffer, unsafe!
>> ```
>> And this is discounting the fact that I not only am copying 
>> the buffer *again*, but doing it one character at a time.
>>
>> So would it be a problem to allow this accessor, even if it's 
>> @system? Or should I just keep importing core.internal?
>>
>> -Steve
>>
>> [1] 
>> https://github.com/dlang/druntime/blob/9f0f6e49fb379841c7934b6049f87dab0adfe53c/src/core/internal/string.d#L113
>>
>> [2] https://dlang.org/phobos/std_conv.html#toChars
>
> I also faced this problem. Anyone have a solution?
>
> SDB at 79

.array on the result from .toChars perhaps?

Or is there a specific reason that cannot be done?

```d
someNumber.toChars.array
```


More information about the Digitalmars-d mailing list