D Programming Language
Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

# std.conv

A one-stop shop for converting values from one type to another.

License:
Boost License 1.0.

Authors:
Walter Bright, Andrei Alexandrescu, Shin Fujishiro, Adam D. Ruppe, Kenji Hara

Source:
std/conv.d

class ConvException: object.Exception;
  Thrown on conversion errors.

class ConvOverflowException: std.conv.ConvException;
  Thrown on conversion overflow errors.

template to(T)
  The to family of functions converts a value from type Source to type Target. The source type is deduced and the target type must be specified, for example the expression to!int(42.0) converts the number 42 from double to int. The conversion is "safe", i.e., it checks for overflow; to!int(4.2e10) would throw the ConvOverflowException exception. Overflow checks are only inserted when necessary, e.g., to!double(42) does not do any checking because any int fits in a double.

  Converting a value to its own type (useful mostly for generic code) simply returns its argument.

  Example:

      int a = 42;
      auto b = to!int(a); // b is int with value 42
      auto c = to!double(3.14); // c is double with value 3.14

  Converting among numeric types is a safe way to cast them around.

  Conversions from floating-point types to integral types allow loss of precision (the fractional part of a floating-point number). The conversion is truncating towards zero, the same way a cast would truncate. (To round a floating point value when casting to an integral, use roundTo.)

  Examples:

      int a = 420;
      auto b = to!long(a); // same as long b = a;
      auto c = to!byte(a / 10); // fine, c = 42
      auto d = to!byte(a); // throw ConvOverflowException
      double e = 4.2e6;
      auto f = to!int(e); // f == 4200000
      e = -3.14;
      auto g = to!uint(e); // fails: floating-to-integral negative overflow
      e = 3.14;
      auto h = to!uint(e); // h = 3
      e = 3.99;
      h = to!uint(a); // h = 3
      e = -3.99;
      f = to!int(a); // f = -3

  Conversions from integral types to floating-point types always succeed, but might lose accuracy. The largest integers with a predecessor representable in floating-point format are 2^24-1 for float, 2^53-1 for double, and 2^64-1 for real (when real is 80-bit, e.g. on Intel machines).

  Example:

      int a = 16_777_215; // 2^24 - 1, largest proper integer representable as float
      assert(to!int(to!float(a)) == a);
      assert(to!int(to!float(-a)) == -a);
      a += 2;
      assert(to!int(to!float(a)) == a); // fails!

  Conversions from string to numeric types differ from the C equivalents atoi() and atol() by checking for overflow and not allowing whitespace.

  For conversion of strings to signed types, the grammar recognized is:

      Integer: Sign UnsignedInteger
      UnsignedInteger
      Sign:
          +
          -

  For conversion to unsigned types, the grammar recognized is:

      UnsignedInteger:
          DecimalDigit
          DecimalDigit UnsignedInteger

  Converting an array to another array type works by converting each element in turn. Associative arrays can be converted to associative arrays as long as keys and values can in turn be converted.

  Example:

      int[] a = ([1, 2, 3]).dup;
      auto b = to!(float[])(a);
      assert(b == [1.0f, 2, 3]);
      string str = "1 2 3 4 5 6";
      auto numbers = to!(double[])(split(str));
      assert(numbers == [1.0, 2, 3, 4, 5, 6]);
      int[string] c;
      c["a"] = 1;
      c["b"] = 2;
      auto d = to!(double[wstring])(c);
      assert(d["a"w] == 1 && d["b"w] == 2);

  Conversions operate transitively, meaning that they work on arrays and associative arrays of any complexity:

      int[string][double[int[]]] a;
      ...
      auto b = to!(short[wstring][string[double[]]])(a);

  This conversion works because to!short applies to an int, to!wstring applies to a string, to!string applies to a double, and to!(double[]) applies to an int[]. The conversion might throw an exception because to!short might fail the range check.

  Entry point that dispatches to the appropriate conversion primitive. Client code normally calls to!TargetType(value) (and not some variant of toImpl).

T toImpl(T, S)(S value) if (isImplicitlyConvertible!(S, T) && !isEnumStrToStr!(S, T) && !isNullToStr!(S, T));
  If the source type is implicitly convertible to the target type, to simply performs the implicit conversion.

T toImpl(T, S)(S value) if (!isImplicitlyConvertible!(S, T) && is(typeof(S.init.opCast!T()) : T) && !isExactSomeString!T);
  When source type supports member template function opCast, is is used.

T toImpl(T, S)(S value) if (!isImplicitlyConvertible!(S, T) && is(T == struct) && is(typeof(T(value))));
T toImpl(T, S)(S value) if (!isImplicitlyConvertible!(S, T) && is(T == class) && is(typeof(new T(value))));
  When target type supports 'converting construction', it is used.
  - If target type is struct, T(value) is used.
  - If target type is class, new T(value) is used.

T toImpl(T, S)(S value) if (!isImplicitlyConvertible!(S, T) && (is(S == class) || is(S == interface)) && !is(typeof(value.opCast!T()) : T) && (is(T == class) || is(T == interface)) && !is(typeof(new T(value))));
  Object-to-object conversions by dynamic casting throw exception when the source is non-null and the target is null.

T toImpl(T, S)(S value) if (!(isImplicitlyConvertible!(S, T) && !isEnumStrToStr!(S, T) && !isNullToStr!(S, T)) && isExactSomeString!T);
T toImpl(T, S)(S value, uint radix, LetterCase letterCase = LetterCase.upper) if (isIntegral!S && isExactSomeString!T);
  Stringize conversion from all types is supported.
  - String to string conversion works for any two string types having (char, wchar, dchar) character widths and any combination of qualifiers (mutable, const, or immutable).
  - Converts array (other than strings) to string. Each element is converted by calling to!T.
  - Associative array to string conversion. Each element is printed by calling to!T.
  - Object to string conversion calls toString against the object or returns "null" if the object is null.
  - Struct to string conversion calls toString against the struct if it is defined.
  - For structs that do not define toString, the conversion to string produces the list of fields.
  - Enumerated types are converted to strings as their symbolic names.
  - Boolean values are printed as "true" or "false".
  - char, wchar, dchar to a string type.
  - Unsigned or signed integers to strings.
    [special case]
      Convert integral value to string in radix radix. radix must be a value from 2 to 36. value is treated as a signed value only if radix is 10. The characters A through Z are used to represent values 10 through 36 and their case is determined by the letterCase parameter.
  - All floating point types to all string types.
  - Pointer to string conversions prints the pointer as a size_t value. If pointer is char*, treat it as C-style strings. In that case, this function is @system.

T toImpl(T, S)(S value) if (!isImplicitlyConvertible!(S, T) && (isNumeric!S || isSomeChar!S || isBoolean!S) && (isNumeric!T || isSomeChar!T || isBoolean!T) && !is(T == enum));
  Narrowing numeric-numeric conversions throw when the value does not fit in the narrower type.

T toImpl(T, S)(S value) if (!isImplicitlyConvertible!(S, T) && !isSomeString!S && isDynamicArray!S && !isExactSomeString!T && isArray!T);
  Array-to-array conversion (except when target is a string type) converts each element in turn by using to.

T toImpl(T, S)(S value) if (isAssociativeArray!S && isAssociativeArray!T && !is(T == enum));
  Associative array to associative array conversion converts each key and each value in turn.

T toImpl(T, S)(S value) if (isExactSomeString!S && isDynamicArray!S && !isExactSomeString!T && is(typeof(parse!T(value))));
T toImpl(T, S)(S value, uint radix) if (isExactSomeString!S && isDynamicArray!S && !isExactSomeString!T && is(typeof(parse!T(value, radix))));
  String to non-string conversion runs parsing.
  - When the source is a wide string, it is first converted to a narrow string and then parsed.
  - When the source is a narrow string, normal text parsing occurs.

T toImpl(T, S)(S value) if (is(T == enum) && !is(S == enum) && is(typeof(value == OriginalType!T.init)) && !isFloatingPoint!(OriginalType!T) && !isSomeString!(OriginalType!T));
  Convert a value that is implicitly convertible to the enum base type into an Enum value. If the value does not match any enum member values a ConvException is thrown. Enums with floating-point or string base types are not supported.

template roundTo(Target)
  Rounded conversion from floating point to integral.

  Example:

      assert(roundTo!int(3.14) == 3);
      assert(roundTo!int(3.49) == 3);
      assert(roundTo!int(3.5) == 4);
      assert(roundTo!int(3.999) == 4);
      assert(roundTo!int(-3.14) == -3);
      assert(roundTo!int(-3.49) == -3);
      assert(roundTo!int(-3.5) == -4);
      assert(roundTo!int(-3.999) == -4);

  Rounded conversions do not work with non-integral target types.

Target parse(Target, Source)(ref Source s) if (isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target == enum));
Target parse(Target, Source)(ref Source s, uint radix) if (isSomeChar!(ElementType!Source) && isIntegral!Target && !is(Target == enum));
  The parse family of functions works quite like the to family, except that (1) it only works with character ranges as input, (2) takes the input by reference and advances it to the position following the conversion, and (3) does not throw if it could not convert the entire input. It still throws if an overflow occurred during conversion or if no character of the input was meaningfully converted.

  Example:

      string test = "123 \t  76.14";
      auto a = parse!uint(test);
      assert(a == 123);
      assert(test == " \t  76.14"); // parse bumps string
      munch(test, " \t\n\r"); // skip ws
      assert(test == "76.14");
      auto b = parse!double(test);
      assert(b == 76.14);
      assert(test == "");

Target parse(Target, Source)(ref Source s) if (isExactSomeString!Source && staticIndexOf!(Unqual!Target, dchar, Unqual!(ElementEncodingType!Source)) >= 0);
  Parsing one character off a string returns the character and bumps the string up one position.

Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',') if (isExactSomeString!Source && isDynamicArray!Target && !is(Target == enum));
Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar comma = ',') if (isExactSomeString!Source && isStaticArray!Target && !is(Target == enum));
  Parses an array from a string given the left bracket (default '['), right bracket (default ']'), and element separator (by default ',').

Target parse(Target, Source)(ref Source s, dchar lbracket = '[', dchar rbracket = ']', dchar keyval = ':', dchar comma = ',') if (isExactSomeString!Source && isAssociativeArray!Target && !is(Target == enum));
  Parses an associative array from a string given the left bracket (default '['), right bracket (default ']'), key-value separator (default ':'), and element seprator (by default ',').

string text(T...)(T args);
wstring wtext(T...)(T args);
dstring dtext(T...)(T args);
  Convenience functions for converting any number and types of arguments into text (the three character widths).

int octal(string num)() if (octalFitsInInt!num && !literalIsLong!num && !literalIsUnsigned!num);
long octal(string num)() if ((!octalFitsInInt!num || literalIsLong!num) && !literalIsUnsigned!num);
uint octal(string num)() if (octalFitsInInt!num && !literalIsLong!num && literalIsUnsigned!num);
ulong octal(string num)() if ((!octalFitsInInt!num || literalIsLong!num) && literalIsUnsigned!num);
template octal(alias s) if (isIntegral!(typeof(s)))
  The octal facility is intended as an experimental facility to replace octal literals starting with '0', which many find confusing. Using octal!177 or octal!"177" instead of 0177 as an octal literal makes code clearer and the intent more visible. If use of this facility becomes preponderent, a future version of the language may deem old-style octal literals deprecated.

  The rules for strings are the usual for literals: If it can fit in an int, it is an int. Otherwise, it is a long. But, if the user specifically asks for a long with the L suffix, always give the long. Give an unsigned iff it is asked for with the U or u suffix. Octals created from integers preserve the type of the passed-in integral.

  Example:

      // same as 0177
      auto x = octal!177;
      // octal is a compile-time device
      enum y = octal!160;
      // Create an unsigned octal
      auto z = octal!"1_000_000u";

pure nothrow @safe T* emplace(T)(T* chunk);
  Given a pointer chunk to uninitialized memory (but already typed as T), constructs an object of non-class type T at that address.

  Returns:
  A pointer to the newly constructed object (which is the same as chunk).

T* emplace(T, Args...)(T* chunk, auto ref Args args) if (!is(T == struct) && Args.length == 1);
T* emplace(T, Args...)(T* chunk, auto ref Args args) if (is(T == struct));
  Given a pointer chunk to uninitialized memory (but already typed as a non-class type T), constructs an object of type T at that address from arguments args.

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object (which is the same as chunk).

T emplace(T, Args...)(void[] chunk, auto ref Args args) if (is(T == class));
  Given a raw memory area chunk, constructs an object of class type T at that address. The constructor is passed the arguments Args. The chunk must be as least as large as T needs and should have an alignment multiple of T's alignment. (The size of a class instance is obtained by using _traits(classInstanceSize, T)).

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object.

T* emplace(T, Args...)(void[] chunk, auto ref Args args) if (!is(T == class));
  Given a raw memory area chunk, constructs an object of non-class type T at that address. The constructor is passed the arguments args, if any. The chunk must be as least as large as T needs and should have an alignment multiple of T's alignment.

  This function can be @trusted if the corresponding constructor of T is @safe.

  Returns:
  A pointer to the newly constructed object.

auto unsigned(T)(T x) if (isIntegral!T);
  Returns the corresponding unsigned value for x (e.g. if x has type int, it returns cast(uint) x). The advantage compared to the cast is that you do not need to rewrite the cast if x later changes type (e.g from int to long).

  Note that the result is always mutable even if the original type was const or immutable. In order to retain the constness, use std.traits.Unsigned.

  Examples:

      uint s = 42;
      auto u1 = unsigned(s); //not qualified
      Unsigned!(typeof(s)) u2 = unsigned(s); //same qualification
      immutable u3 = unsigned(s); //totally qualified

auto signed(T)(T x) if (isIntegral!T);
  Returns the corresponding signed value for x (e.g. if x has type uint, it returns cast(int) x). The advantage compared to the cast is that you do not need to rewrite the cast if x later changes type (e.g from uint to ulong).

  Note that the result is always mutable even if the original type was const or immutable. In order to retain the constness, use std.traits.Signed.

  Examples:

      uint u = 42;
      auto s1 = unsigned(u); //not qualified
      Unsigned!(typeof(u)) s2 = unsigned(u); //same qualification
      immutable s3 = unsigned(u); //totally qualified

Copyright Digital Mars 2007-. | Page generated by Ddoc.