Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Downloads
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Calendar
  - Forums
  - IRC
  - Wiki
  - GitHub
  - Issues
  - Get involved
  - Contributors
  - Foundation
  - Security Team
  - Donate
  - Sponsors
- Resources
  - Tour
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - run.dlang.io
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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 a local clone.

# std.base64

Support for Base64 encoding and decoding.
This module provides two default implementations of Base64 encoding, Base64 with a standard encoding alphabet, and a variant Base64URL that has a modified encoding alphabet designed to be safe for embedding in URLs and filenames.
Both variants are implemented as instantiations of the template Base64Impl. Most users will not need to use this template directly; however, it can be used to create customized Base64 encodings, such as one that omits padding characters, or one that is safe to embed inside a regular expression.

Example

    ubyte[] data = [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e];

    const(char)[] encoded = Base64.encode(data);
    assert(encoded == "FPucA9l+");

    ubyte[] decoded = Base64.decode("FPucA9l+");
    assert(decoded == [0x14, 0xfb, 0x9c, 0x03, 0xd9, 0x7e]);

The range API is supported for both encoding and decoding:

Example

    // Create MIME Base64 with CRLF, per line 76.
    File f = File("./text.txt", "r");
    scope(exit) f.close();

    Appender!string mime64 = appender!string;

    foreach (encoded; Base64.encoder(f.byChunk(57)))
    {
        mime64.put(encoded);
        mime64.put("\r\n");
    }

    writeln(mime64.data);

References RFC 4648 - The Base16, Base32, and Base64 Data Encodings

License:
Boost License 1.0.
Authors:
Masahiro Nakagawa, Daniel Murphy (Single value Encoder and Decoder)

Source std/base64.d

alias `Base64` = Base64Impl!('+', '/', '=');
  Implementation of standard Base64 encoding.
  See Base64Impl for a description of available methods.
  Examples:

      ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
      writeln(Base64.encode(data)); // "g9cwegE/"
      writeln(Base64.decode("g9cwegE/")); // data

alias `Base64URL` = Base64Impl!('-', '_', '=');
  Variation of Base64 encoding that is safe for use in URLs and filenames.
  See Base64Impl for a description of available methods.
  Examples:

      ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
      writeln(Base64URL.encode(data)); // "g9cwegE_"
      writeln(Base64URL.decode("g9cwegE_")); // data

alias `Base64URLNoPadding` = Base64Impl!('-', '_', '\x00');
  Unpadded variation of Base64 encoding that is safe for use in URLs and filenames, as used in RFCs 4648 and 7515 (JWS/JWT/JWE).
  See Base64Impl for a description of available methods.
  Examples:

      ubyte[] data = [0x83, 0xd7, 0x30, 0x7b, 0xef];
      writeln(Base64URLNoPadding.encode(data)); // "g9cwe-8"
      writeln(Base64URLNoPadding.decode("g9cwe-8")); // data

template `Base64Impl`(char Map62th, char Map63th, char Padding = '=')
  Template for implementing Base64 encoding and decoding.
  For most purposes, direct usage of this template is not necessary; instead, this module provides default implementations: Base64, implementing basic Base64 encoding, and Base64URL and Base64URLNoPadding, that implement the Base64 variant for use in URLs and filenames, with and without padding, respectively.
  Customized Base64 encoding schemes can be implemented by instantiating this template with the appropriate arguments. For example:

      // Non-standard Base64 format for embedding in regular expressions.
      alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding);

  NOTE Encoded strings will not have any padding if the Padding parameter is set to NoPadding.

  Examples:

      import std.string : representation;

      // pre-defined: alias Base64 = Base64Impl!('+', '/');
      ubyte[] emptyArr;
      writeln(Base64.encode(emptyArr)); // ""
      writeln(Base64.encode("f".representation)); // "Zg=="
      writeln(Base64.encode("foo".representation)); // "Zm9v"

      alias Base64Re = Base64Impl!('!', '=', Base64.NoPadding);
      writeln(Base64Re.encode("f".representation)); // "Zg"
      writeln(Base64Re.encode("foo".representation)); // "Zm9v"

  enum auto `NoPadding`;
    represents no-padding encoding
  pure nothrow @safe size_t `encodeLength`(in size_t `sourceLength`);
    Calculates the length needed to store the encoded string corresponding to an input of the given length.
    Parameters:

    size_t `sourceLength` | Length of the source array.

    Returns:
    The length of a Base64 encoding of an array of the given length.
    Examples:

        ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];

        // Allocate a buffer large enough to hold the encoded string.
        auto buf = new char[Base64.encodeLength(data.length)];

        Base64.encode(data, buf);
        writeln(buf); // "Gis8TV1u"

  pure @trusted char[] `encode`(R1, R2)(in R1 `source`, R2 `buffer`)
  if (isArray!R1 && is(ElementType!R1 : ubyte) && is(R2 == char[]));
  char[] `encode`(R1, R2)(R1 `source`, R2 `buffer`)
  if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && is(R2 == char[]));
    Encode source into a char[] buffer using Base64 encoding.
    Parameters:

    R1 `source` | The input range to encode.
    R2 `buffer` | The char[] buffer to store the encoded result.

    Returns:
    The slice of buffer that contains the encoded string.
    Examples:

        ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
        char[32] buffer;    // much bigger than necessary

        // Just to be sure...
        auto encodedLength = Base64.encodeLength(data.length);
        assert(buffer.length >= encodedLength);

        // encode() returns a slice to the provided buffer.
        auto encoded = Base64.encode(data, buffer[]);
        assert(encoded is buffer[0 .. encodedLength]);
        writeln(encoded); // "g9cwegE/"

  size_t `encode`(E, R)(scope const(E)[] `source`, auto ref R `range`)
  if (is(E : ubyte) && isOutputRange!(R, char) && !is(R == char[]));
  size_t `encode`(R1, R2)(R1 `source`, auto ref R2 `range`)
  if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && !is(R2 == char[]) && isOutputRange!(R2, char));
    Encodes source into an output range using Base64 encoding.
    Parameters:

    const(E)[] `source` | The input range to encode.
    R `range` | The output range to store the encoded result.

    Returns:
    The number of times the output range's put method was invoked.
    Examples:

        import std.array : appender;

        auto output = appender!string();
        ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];

        // This overload of encode() returns the number of calls to the output
        // range's put method.
        writeln(Base64.encode(data, output)); // 8
        writeln(output.data); // "Gis8TV1u"

  pure @safe char[] `encode`(Range)(Range `source`)
  if (isArray!Range && is(ElementType!Range : ubyte));
  char[] `encode`(Range)(Range `source`)
  if (!isArray!Range && isInputRange!Range && is(ElementType!Range : ubyte) && hasLength!Range);
    Encodes source to newly-allocated buffer.
    This convenience method alleviates the need to manually manage output buffers.
    Parameters:

    Range `source` | The input range to encode.

    Returns:
    A newly-allocated char[] buffer containing the encoded string.
    Examples:

        ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];
        writeln(Base64.encode(data)); // "Gis8TV1u"

  struct `Encoder`(Range) if (isInputRange!Range && (is(ElementType!Range : const(ubyte)[]) || is(ElementType!Range : const(char)[])));
    An input range that iterates over the respective Base64 encodings of a range of data items.
    This range will be a forward range if the underlying data source is at least a forward range.

    Note This struct is not intended to be created in user code directly; use the encoder function instead.

    @property @trusted bool `empty`();
      Returns:
      true if there is no more encoded data left.
    nothrow @property @safe char[] `front`();
      Returns:
      The current chunk of encoded data.
    void `popFront`();
      Advance the range to the next chunk of encoded data.
      Throws:
      Base64Exception If invoked when `empty` returns true.
    @property typeof(this) `save`();
      Save the current iteration state of the range.
      This method is only available if the underlying range is a forward range.
      Returns:
      A copy of this.
  struct `Encoder`(Range) if (isInputRange!Range && is(ElementType!Range : ubyte));
    An input range that iterates over the encoded bytes of the given source data.
    It will be a forward range if the underlying data source is at least a forward range.

    Note This struct is not intended to be created in user code directly; use the encoder function instead.

    const nothrow @property @safe bool `empty`();
      Returns:
      true if there are no more encoded characters to be iterated.
    nothrow @property @safe ubyte `front`();
      Returns:
      The current encoded character.
    void `popFront`();
      Advance to the next encoded character.
      Throws:
      Base64Exception If invoked when ` empty` returns true.
    @property typeof(this) `save`();
      Save the current iteration state of the range.
      This method is only available if the underlying range is a forward range.
      Returns:
      A copy of this.
  Encoder!Range `encoder`(Range)(Range `range`)
  if (isInputRange!Range);
    Construct an Encoder that iterates over the Base64 encoding of the given input range.
    Parameters:

    Range `range` | An input range over the data to be encoded.

    Returns:
    If range is a range of bytes, an Encoder that iterates over the bytes of the corresponding Base64 encoding.
    If range is a range of ranges of bytes, an Encoder that iterates over the Base64 encoded strings of each element of the range.
    In both cases, the returned Encoder will be a forward range if the given `range` is at least a forward range, otherwise it will be only an input range.

    Example This example encodes the input one line at a time.

        File f = File("text.txt", "r");
        scope(exit) f.close();

        uint line = 0;
        foreach (encoded; Base64.encoder(f.byLine()))
        {
            writeln(++line, ". ", encoded);
        }

    Example This example encodes the input data one byte at a time.

        ubyte[] data = cast(ubyte[]) "0123456789";

        // The ElementType of data is not aggregation type
        foreach (encoded; Base64.encoder(data))
        {
            writeln(encoded);
        }

  pure nothrow @safe size_t `decodeLength`(in size_t `sourceLength`);
    Given a Base64 encoded string, calculates the length of the decoded string.
    Parameters:

    size_t `sourceLength` | The length of the Base64 encoding.

    Returns:
    The length of the decoded string corresponding to a Base64 encoding of length sourceLength.
    Examples:

        auto encoded = "Gis8TV1u";

        // Allocate a sufficiently large buffer to hold to decoded result.
        auto buffer = new ubyte[Base64.decodeLength(encoded.length)];

        Base64.decode(encoded, buffer);
        writeln(buffer); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

  pure @trusted ubyte[] `decode`(R1, R2)(in R1 `source`, R2 `buffer`)
  if (isArray!R1 && is(ElementType!R1 : dchar) && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));
  ubyte[] `decode`(R1, R2)(R1 `source`, R2 `buffer`)
  if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));
    Decodes source into the given buffer.
    Parameters:

    R1 `source` | The input range to decode.
    R2 `buffer` | The buffer to store decoded result.

    Returns:
    The slice of buffer containing the decoded result.
    Throws:
    Base64Exception if source contains characters outside the base alphabet of the current Base64 encoding scheme.
    Examples:

        auto encoded = "Gis8TV1u";
        ubyte[32] buffer;   // much bigger than necessary

        // Just to be sure...
        auto decodedLength = Base64.decodeLength(encoded.length);
        assert(buffer.length >= decodedLength);

        // decode() returns a slice of the given buffer.
        auto decoded = Base64.decode(encoded, buffer[]);
        assert(decoded is buffer[0 .. decodedLength]);
        writeln(decoded); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

  size_t `decode`(R1, R2)(in R1 `source`, auto ref R2 `range`)
  if (isArray!R1 && is(ElementType!R1 : dchar) && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));
  size_t `decode`(R1, R2)(R1 `source`, auto ref R2 `range`)
  if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));
    Decodes source into a given output range.
    Parameters:

    R1 `source` | The input range to decode.
    R2 `range` | The output range to store the decoded result.

    Returns:
    The number of times the output range's put method was invoked.
    Throws:
    Base64Exception if source contains characters outside the base alphabet of the current Base64 encoding scheme.
    Examples:

        struct OutputRange
        {
            ubyte[] result;
            void put(ubyte b) { result ~= b; }
        }
        OutputRange output;

        // This overload of decode() returns the number of calls to put().
        writeln(Base64.decode("Gis8TV1u", output)); // 6
        writeln(output.result); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

  pure @safe ubyte[] `decode`(Range)(Range `source`)
  if (isArray!Range && is(ElementType!Range : dchar));
  ubyte[] `decode`(Range)(Range `source`)
  if (!isArray!Range && isInputRange!Range && is(ElementType!Range : dchar) && hasLength!Range);
    Decodes source into newly-allocated buffer.
    This convenience method alleviates the need to manually manage decoding buffers.
    Parameters:

    Range `source` | The input range to decode.

    Returns:
    A newly-allocated ubyte[] buffer containing the decoded string.
    Examples:

        auto data = "Gis8TV1u";
        writeln(Base64.decode(data)); // [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]

  struct `Decoder`(Range) if (isInputRange!Range && (is(ElementType!Range : const(char)[]) || is(ElementType!Range : const(ubyte)[])));
    An input range that iterates over the decoded data of a range of Base64 encodings.
    This range will be a forward range if the underlying data source is at least a forward range.

    Note This struct is not intended to be created in user code directly; use the decoder function instead.

    @property @trusted bool `empty`();
      Returns:
      true if there are no more elements to be iterated.
    nothrow @property @safe ubyte[] `front`();
      Returns:
      The decoding of the current element in the input.
    void `popFront`();
      Advance to the next element in the input to be decoded.
      Throws:
      Base64Exception if invoked when ` empty` returns true.
    @property typeof(this) `save`();
      Saves the current iteration state.
      This method is only available if the underlying range is a forward range
      Returns:
      A copy of this.
  struct `Decoder`(Range) if (isInputRange!Range && is(ElementType!Range : char));
    An input range that iterates over the bytes of data decoded from a Base64 encoded string.
    This range will be a forward range if the underlying data source is at least a forward range.

    Note This struct is not intended to be created in user code directly; use the decoder function instead.

    const nothrow @property @safe bool `empty`();
      Returns:
      true if there are no more elements to be iterated.
    nothrow @property @safe ubyte `front`();
      Returns:
      The current decoded byte.
    void `popFront`();
      Advance to the next decoded byte.
      Throws:
      Base64Exception if invoked when ` empty` returns true.
    @property typeof(this) `save`();
      Saves the current iteration state.
      This method is only available if the underlying range is a forward range
      Returns:
      A copy of this.
  Decoder!Range `decoder`(Range)(Range `range`)
  if (isInputRange!Range);
    Construct a Decoder that iterates over the decoding of the given Base64 encoded data.
    Parameters:

    Range `range` | An input range over the data to be decoded.

    Returns:
    If range is a range of characters, a Decoder that iterates over the bytes of the corresponding Base64 decoding.
    If range is a range of ranges of characters, a Decoder that iterates over the decoded strings corresponding to each element of the range. In this case, the length of each subrange must be a multiple of 4; the returned decoder does not keep track of Base64 decoding state across subrange boundaries.
    In both cases, the returned Decoder will be a forward range if the given `range` is at least a forward range, otherwise it will be only an input range.
    If the input data contains characters not found in the base alphabet of the current Base64 encoding scheme, the returned range may throw a Base64Exception.

    Example This example shows decoding over a range of input data lines.

        foreach (decoded; Base64.decoder(stdin.byLine()))
        {
            writeln(decoded);
        }

    Example This example shows decoding one byte at a time.

        auto encoded = Base64.encoder(cast(ubyte[])"0123456789");
        foreach (n; map!q{a - '0'}(Base64.decoder(encoded)))
        {
            writeln(n);
        }

class `Base64Exception`: object.Exception;
  Exception thrown upon encountering Base64 encoding or decoding errors.
  Examples:

      import std.exception : assertThrown;
      assertThrown!Base64Exception(Base64.decode("ab|c"));

Copyright © 1999-2019 by the D Language Foundation | Page generated by Ddoc on Fri Oct 11 06:43:50 2019