Checking function parameters in Phobos
Simen Kjærås
simen.kjaras at gmail.com
Wed Nov 20 09:45:35 PST 2013
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
}
--
Simen
More information about the Digitalmars-d
mailing list