8

Is there any typesafe way to create a string in D, using information only available at runtime, without allocating memory?

A simple example of what I might want to do:

void renderText(string text) { ... }

void renderScore(int score)
{
    char[16] text;
    int n = sprintf(text.ptr, "Score: %d", score);
    renderText(text[0..n]); // ERROR
}

Using this, you'd get an error because the slice of text is not immutable, and is therefore not a string (i.e. immutable(char)[])

I can only think of three ways around this:

  1. Cast the slice to a string. It works, but is ugly.
  2. Allocate a new string using the slice. This works, but I'd rather not have to allocate memory.
  3. Change renderText to take a const(char)[]. This works here, but (a) it's ugly, and (b) many functions in Phobos require string, so if I want to use those in the same manner then this doesn't work.

None of these are particularly nice. Am I missing something? How does everyone else get around this problem?

2
  • 1
    Heresy, heresy! Use snprintf! :D
    – BCS
    Oct 1, 2011 at 16:50
  • 2
    I think #3 is actually the correct solution. string--> immutable(char)[] means that the data cannot change (as long as it's still referenced somewhere, otherwise the GC is allowed to collect it, AFAIK). I don't think you can ever make such a guarantee for stack-allocated data. But unless renderText actually needs to store text somewhere, it should use const(char)[]. As immutable is stronger than const it should only be used when necessary. I agree, however that many functions in phobos unnecessarily take strings instead of const(char)[], that should be fixed in phobos.
    – jpf
    Oct 1, 2011 at 18:09

4 Answers 4

6

You have static array of char. You want to pass it to a function that takes immutable(char)[]. The only way to do that without any allocation is to cast. Think about it. What you want is one type to act like it's another. That's what casting does. You could choose to use assumeUnique to do it, since that does exactly the cast that you're looking for, but whether that really gains you anything is debatable. Its main purpose is to document that what you're doing by the cast is to make the value being cast be treated as immutable and that there are no other references to it. Looking at your example, that's essentially true, since it's the last thing in the function, but whether you want to do that in general is up to you. Given that it's a static array which risks memory problems if you screw up and you pass it to a function that allows a reference to it to leak, I'm not sure that assumeUnique is the best choice. But again, it's up to you.

Regardless, if you're doing a cast (be it explicitly or with assumeUnique), you need to be certain that the function that you're passing it to is not going to leak references to the data that you're passing to it. If it does, then you're asking for trouble.

The other solution, of course, is to change the function so that it takes const(char)[], but that still runs the risk of leaking references to the data that you're passing in. So, you still need to be certain of what the function is actually going to do. If it's pure, doesn't return const(char)[] (or anything that could contain a const(char)[]), and there's no way that it could leak through any of the function's other arguments, then you're safe, but if any of those aren't true, then you're going to have to be careful. So, ultimately, I believe that all that using const(char)[] instead of casting to string really buys you is that you don't have to cast. That's still better, since it avoids the risk of screwing up the cast (and it's just better in general to avoid casting when you can), but you still have all of the same things to worry about with regards to escaping references.

Of course, that also requires that you be able to change the function to have the signature that you want. If you can't do that, then you're going to have to cast. I believe that at this point, most of Phobos' string-based functions have been changed so that they're templated on the string type. So, this should be less of a problem now with Phobos than it used to be. Some functions (in particular, those in std.file), still need to be templatized, but ultimately, functions in Phobos that require string specifically should be fairly rare and will have a good reason for requiring it.

Ultimately however, the problem is that you're trying to treat a static array as if it were a dynamic array, and while D definitely lets you do that, you're taking a definite risk in doing so, and you need to be certain that the functions that you're using don't leak any references to the local data that you're passing to them.

3
  • How about making renderText take a "scope const(char)[]"? "The scope storage class means that references in the parameter cannot be escaped (e.g. assigned to a global variable)."
    – jpf
    Oct 2, 2011 at 9:48
  • @jpf: Are you sure about that? DMD allows it. Oct 2, 2011 at 10:55
  • That was a quote from the D2 language reference: digitalmars.com/d/2.0/function.html Section "Function Parameters". I can't find something similar in TDPL though. But I wouldn't be surprised if it's just not implemented properly yet ;-)
    – jpf
    Oct 2, 2011 at 11:18
2

Check out assumeUnique from std.exception Jonathan's answer.

3
  • How will that interact with assumeUnique taking a ref argument (in this case to a slice expression which IIRC is not an r-value)?
    – BCS
    Oct 1, 2011 at 16:48
  • I don't think using assumeUnique with stack allocated space is valid. Stack space is not unique, when the renderScore has returned and another function is called, it can reuse the same space on the stack. --> not unique and also not immutable. Remember that immutable also implicitly means shared: Do you really want code to be able to pass stack allocated data to another thread?
    – jpf
    Oct 1, 2011 at 18:17
  • You'd have to do: auto text2 = text[0..n]; renderText(assumeUnique(text2)); although as jpf says, it's very nasty as you still have write access to text, which defeats the purpose of immutable. Oct 1, 2011 at 18:42
0

No, you cannot create a string without allocation. Did you mean access? To avoid allocation, you have to either use slice or pointer to access a previously created string. Not sure about cast though, it may or may not allocate new memory space for the new string.

1
  • The OP seems willing to use stack allocation so I'd assume he's only trying to avoid heap allocation.
    – BCS
    Oct 1, 2011 at 16:44
0

One way to get around this would be to copy the mutable chars into a new immutable version then slice that:

void renderScore(int score)
{
    char[16] text;
    int n = sprintf(text.ptr, "Score: %d", score);
    immutable(char)[16] itext = text;
    renderText(itext[0..n]);
}

However:

  1. DMD currently doesn't allow this due to a bug.
  2. You're creating an unnecessary copy (better than a GC allocation, but still not great).
3
  • Are you sure this should work? Cite TDPL: "An immutable value is cast in Stone:... It will never change throughout the execution of the program". I'd still argue this requirement is never met for stack-allocated data. It can work for local variables, but only if those are initialized at compile time so that they can be put in the static data segment instead of the stack. But your example still has to set itext at runtime --> stack space.
    – jpf
    Oct 1, 2011 at 19:03
  • @jpf: immutability and lifetime are orthogonal issues. Immutability guarantees that it won't change during its lifetime, but doesn't guarantee infinite lifetime. If you reference something with finite lifetime then it is up to you to ensure you don't use it beyond desctruction. Oct 1, 2011 at 19:28
  • Seems like you're right. TDPL is a little inconsistent there, on Page 288 it clearly says "as soon as it's initialized, you may as well consider it has been burned forever into the memory storing it. It will never change throughout the execution of the program", which imho also means infinite lifetime. But on page 401 it says "an immutable value is guaranteed never to change throughout its lifetime"
    – jpf
    Oct 1, 2011 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.