nogc string concatenation?

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 13 18:32:05 PDT 2017


On Friday, 14 July 2017 at 00:40:38 UTC, FoxyBrown wrote:
> Anyone have an efficient implementation that is easy to use?

Not sure what you mean by efficient here, but a \theta(n+m) one 
is done idiomatically with Allocator+ranges like this (note that 
the casts to and from ubyte are necessary, because 
std.range.primitives.hasLength returns false for narrow strings, 
so we have to explicitly state that we want to work in code 
units):

---
char[] strcat(Allocator)(Allocator alloc, string a, string b)
{
	import std.experimental.allocator : makeArray;
	import std.range : chain;
	return cast(char[]) alloc.makeArray!ubyte(chain(cast(ubyte[]) a, 
cast(ubyte[]) b));
}
---

Usage example:
---
void main(string[] args)
{
	import std.stdio;

	import std.exception : enforce;
	enforce(args.length == 3);

	import std.experimental.allocator : dispose;
	import std.experimental.allocator.mallocator;
	alias alloc = Mallocator.instance;

	char[] concated = alloc.strcat(args[1], args[2]);
	scope (exit) alloc.dispose(concated);

	writeln(cast(string) concated);
}
---


More information about the Digitalmars-d-learn mailing list