Integer parsing checked in

Monday, November 29, 2010
Tart programs can now convert strings to integer types:

let n = int8.parse("10");
let m = int32.parse("fff", 16);

Features:
  • The implementation is pure Tart - no calling C library functions. It is also efficient :)
  • Radix conversions from 2 to 35 are supported.
  • Overflow is properly handled, even for 64-bit ints - so for example if you attempt to convert 9223372036854775809 to a 64-bit signed int, it will throw an OverflowError.
  • Bad input strings throw an InputFormatError.
  • Currently supports all integer and boolean types.
Character and float types are not implemented yet. I probably won't be able to do a pure-Tart implementation of float parsing, because that's hard to get right. So I'll probably end up having to call strtod(). Unfortunately strtod() has much less restrictive input conditions that I'd like (allows junk characters at the end, for example.)

There's also a "tryParse" function in the "Strings" namespace for each numeric type that returns either a numeric value or a conversion error:

def tryParse[uint8](s:String, radix:int) -> uint8 or ConversionError;

Note that the reason for naming it 'tryParse[uint8]' instead of 'tryParseUint8' is to make it easier to work with templates.

0 comments:

Post a Comment