On Wednesday, 20 November 2013 at 17:45:43 UTC, Simen Kjærås wrote:
On 20.11.2013 12:49, Jacob Carlborg wrote:
On 2013-11-20 12:16, Jonathan M Davis wrote:

You'd do it the other way around by having something like

ValidatedString!char s = validateString("hello world");

Right.

ValidatedString would then avoid any extra validation when iterating
over the
characters, though I don't know how much of an efficiency gain that would actually be given that much of the validation occurs naturally when
decoding
or using stride. It would have the downside that any function which
specializes on strings would likely have to then specialize on
ValidatedString
as well. So, while I agree with the idea in concept, I'd propose that we benchmark the difference in decoding and striding without the checks
and see if
there actually is much difference. Because if there isn't, then I
don't think
that it's worth going to the trouble of adding something like
ValidatedString.

If not just if the string is valid UTF-8. There can be many other types of valid strings. Or rather other functions that have additional requirements. Like sanitized filenames, HTML/SQL escaped strings and so on.

May I suggest:

struct Validated(alias fn, T) {
    private T value;
    @property inout
    T get() {
        return value;
    }
}

Validated!(fn, T) validate(alias fn, T)(T value) {
    Validated!(fn, T) result;
    fn(value);
    result.value = value;
    return result;
}

void functionThatTakesSanitizedFileNames(Validated!(sanitizeFileName, string) path) {
   // Do stuff
}

What if you have more that just one validation, e.g. Positive and LessThan42? Is Positive!LessThan42!int the same type as LessThan42!Positive!int? Implicitly convertible?

I feel that it might be better to use @attributes here instead. Something like:

@positive int validatePositive(int value) {
  assert(value > 0);
  return value;
}

@lessThan42 validateLessThan42(int value) {
  assert(value < 42);
  return value;
}

Now you can have @positive @lessThan42 int value = validatePositive(validateLessThan42(x));

It also doesn't involve creating new types.

Reply via email to