How is std.regex.replaceAllInto more efficient?

Dmitry Olshansky via Digitalmars-d digitalmars-d at puremagic.com
Sun Oct 18 22:25:05 PDT 2015


On 18-Oct-2015 21:16, Shriramana Sharma wrote:
> Dmitry Olshansky wrote:
>
>> I guess the idiomatic way is:
>>
>> foreach (pos; iota(0, sink.data.length, 4).retro)
>
> Mmm no that throws an assertion failure, since the guarantee of the regex is
> only to insert commas before every third digit *from the end*, but doing
> retro on an *ascending* iota fixes the end point at index zero, and start
> point at some multiple of four *from the beginning*, which isn't compatible
> with the regex's promise.
>
> Thus the correct approach would be to do a *descending* iota:
>
>          foreach (pos; iota(sink.data.length - 4, 0, -4))
>              assert(sink.data[pos] == ',');
>

That would miss the zero. iota is half-open [) interval.
How about doing a bit of math and going for:

iota(sink.data.length % 4, sink.data.length, 4)

It really doesn't matter which way we go (forward/backward) but we must 
hit the right spots.


> Pull: https://github.com/D-Programming-Language/phobos/pull/3731
>
> I am not much experienced with GitHub pull requests, so I hope I did that
> correctly. IIUC after you pull, it will be back in my fork and its clone
> once I pull back from you, then I can delete my local branch, right?
>

Cool, will comment there.

> BTW since I still didn't like that wraparound thing, (and it would fail in
> some extreme corner cases where sink.data.length is > size_t.max - 3 or
> such, I think) I thought of it much and arrived at the much more convoluted:
>
>          for (size_t pos = sink.data.length; pos > 3; )
>              { pos -= 4; assert(sink.data[pos] == ','); }
>
> which is still not easy for one's mind to "wraparound"! So the descending
> iota solution we arrived above is the most elegant.
>
> As I said, I'm still getting my "D-legs"...

Welcome on board ;)

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list