Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

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 usinga 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 variantBase64URL that has a modified encoding alphabet designed to be safe for embedding in URLs and filenames.
Both variants are implemented as instantiations of the templateBase64Impl. 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);

ReferencesRFC 4648 - The Base16, Base32, and Base64 Data Encodings

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

Sourcestd/base64.d

aliasBase64 = Base64Impl!('+', '/', '=');
Implementation of standard Base64 encoding.
SeeBase64Impl 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
aliasBase64URL = Base64Impl!('-', '_', '=');
Variation of Base64 encoding that is safe for use in URLs and filenames.
SeeBase64Impl 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
aliasBase64URLNoPadding = Base64Impl!('-', '_', '\0');
Unpadded variation of Base64 encoding that is safe for use in URLs and filenames, as used in RFCs 4648 and 7515 (JWS/JWT/JWE).
SeeBase64Impl 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
templateBase64Impl(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, andBase64URL andBase64URLNoPadding, 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);

NOTEEncoded strings will not have any padding if thePadding parameter is set toNoPadding.

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 autoNoPadding;
represents no-padding encoding
pure nothrow @nogc @safe size_tencodeLength(in size_tsourceLength);
Calculates the length needed to store the encoded string corresponding to an input of the given length.
Parameters:
size_tsourceLengthLength 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 =newchar[Base64.encodeLength(data.length)];Base64.encode(data, buf);writeln(buf);// "Gis8TV1u"
pure @trusted char[]encode(R1, R2)(scope const R1source, return scope R2buffer)
if (isArray!R1 && is(ElementType!R1 : ubyte) && is(R2 == char[]));

char[]encode(R1, R2)(R1source, R2buffer)
if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && is(R2 == char[]));
Encodesource into achar[] buffer using Base64 encoding.
Parameters:
R1sourceTheinput range to encode.
R2bufferThechar[] buffer to store the encoded result.
Returns:
The slice ofbuffer that contains the encoded string.
Examples:
ubyte[6] 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(encodedisbuffer[0 .. encodedLength]);writeln(encoded);// "g9cwegE/"
size_tencode(E, R)(scope const(E)[]source, auto ref Rrange)
if (is(E : ubyte) && isOutputRange!(R, char) && !is(R == char[]));

size_tencode(R1, R2)(R1source, auto ref R2range)
if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : ubyte) && hasLength!R1 && !is(R2 == char[]) && isOutputRange!(R2, char));
Encodessource into anoutput range using Base64 encoding.
Parameters:
const(E)[]sourceTheinput range to encode.
RrangeTheoutput range to store the encoded result.
Returns:
The number of times the output range'sput 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));// 8writeln(output.data);// "Gis8TV1u"
pure @safe char[]encode(Range)(Rangesource)
if (isArray!Range && is(ElementType!Range : ubyte));

char[]encode(Range)(Rangesource)
if (!isArray!Range && isInputRange!Range && is(ElementType!Range : ubyte) && hasLength!Range);
Encodessource to newly-allocated buffer.
This convenience method alleviates the need to manually manage output buffers.
Parameters:
RangesourceTheinput range to encode.
Returns:
A newly-allocatedchar[] buffer containing the encoded string.
Examples:
ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];writeln(Base64.encode(data));// "Gis8TV1u"
structEncoder(Range) if (isInputRange!Range && (is(ElementType!Range : const(ubyte)[]) || is(ElementType!Range : const(char)[])));
Aninput range that iterates over the respective Base64 encodings of a range of data items.
This range will be aforward range if the underlying data source is at least a forward range.

NoteThis struct is not intended to be created in user code directly; use theencoder function instead.

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

NoteThis struct is not intended to be created in user code directly; use theencoder function instead.

nothrow @property @safe boolempty() const;
Returns:
true if there are no more encoded characters to be iterated.
nothrow @property @safe ubytefront();
Returns:
The current encoded character.
voidpopFront();
Advance to the next encoded character.
Throws:
Base64Exception If invoked when` empty` returnstrue.
@property typeof(this)save();
Save the current iteration state of the range.
This method is only available if the underlying range is aforward range.
Returns:
A copy ofthis.
Encoder!Rangeencoder(Range)(Rangerange)
if (isInputRange!Range);
Construct anEncoder that iterates over the Base64 encoding of the giveninput range.
Parameters:
RangerangeAninput range over the data to be encoded.
Returns:
Ifrange is a range of bytes, anEncoder that iterates over the bytes of the corresponding Base64 encoding.
Ifrange is a range of ranges of bytes, anEncoder that iterates over the Base64 encoded strings of each element of the range.
In both cases, the returnedEncoder will be aforward range if the givenrange 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 typeforeach (encoded; Base64.encoder(data)){    writeln(encoded);}

pure nothrow @nogc @safe size_tdecodeLength(in size_tsourceLength);
Given a Base64 encoded string, calculates the length of the decoded string.
Parameters:
size_tsourceLengthThe length of the Base64 encoding.
Returns:
The length of the decoded string corresponding to a Base64 encoding of lengthsourceLength.
Examples:
auto encoded ="Gis8TV1u";// Allocate a sufficiently large buffer to hold to decoded result.auto buffer =newubyte[Base64.decodeLength(encoded.length)];Base64.decode(encoded, buffer);writeln(buffer);// [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]
pure @trusted ubyte[]decode(R1, R2)(in R1source, return scope R2buffer)
if (isArray!R1 && is(ElementType!R1 : dchar) && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));

ubyte[]decode(R1, R2)(R1source, R2buffer)
if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));
Decodessource into the given buffer.
Parameters:
R1sourceTheinput range to decode.
R2bufferThe buffer to store decoded result.
Returns:
The slice ofbuffer containing the decoded result.
Throws:
Base64Exception ifsource 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(decodedisbuffer[0 .. decodedLength]);writeln(decoded);// [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]
size_tdecode(R1, R2)(in R1source, auto ref R2range)
if (isArray!R1 && is(ElementType!R1 : dchar) && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));

size_tdecode(R1, R2)(R1source, auto ref R2range)
if (!isArray!R1 && isInputRange!R1 && is(ElementType!R1 : dchar) && hasLength!R1 && !is(R2 == ubyte[]) && isOutputRange!(R2, ubyte));
Decodessource into a givenoutput range.
Parameters:
R1sourceTheinput range to decode.
R2rangeTheoutput range to store the decoded result.
Returns:
The number of times the output range'sput method was invoked.
Throws:
Base64Exception ifsource 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));// 6writeln(output.result);// [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]
pure @safe ubyte[]decode(Range)(Rangesource)
if (isArray!Range && is(ElementType!Range : dchar));

ubyte[]decode(Range)(Rangesource)
if (!isArray!Range && isInputRange!Range && is(ElementType!Range : dchar) && hasLength!Range);
Decodessource into newly-allocated buffer.
This convenience method alleviates the need to manually manage decoding buffers.
Parameters:
RangesourceTheinput range to decode.
Returns:
A newly-allocatedubyte[] buffer containing the decoded string.
Examples:
auto data ="Gis8TV1u";writeln(Base64.decode(data));// [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]
structDecoder(Range) if (isInputRange!Range && (is(ElementType!Range : const(char)[]) || is(ElementType!Range : const(ubyte)[])));
Aninput range that iterates over the decoded data of a range of Base64 encodings.
This range will be aforward range if the underlying data source is at least a forward range.

NoteThis struct is not intended to be created in user code directly; use thedecoder function instead.

@property @trusted boolempty();
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.
voidpopFront();
Advance to the next element in the input to be decoded.
Throws:
Base64Exception if invoked when` empty` returnstrue.
@property typeof(this)save();
Saves the current iteration state.
This method is only available if the underlying range is aforward range
Returns:
A copy ofthis.
structDecoder(Range) if (isInputRange!Range && is(ElementType!Range : char));
Aninput range that iterates over the bytes of data decoded from a Base64 encoded string.
This range will be aforward range if the underlying data source is at least a forward range.

NoteThis struct is not intended to be created in user code directly; use thedecoder function instead.

nothrow @property @safe boolempty() const;
Returns:
true if there are no more elements to be iterated.
nothrow @property @safe ubytefront();
Returns:
The current decoded byte.
voidpopFront();
Advance to the next decoded byte.
Throws:
Base64Exception if invoked when` empty` returnstrue.
@property typeof(this)save();
Saves the current iteration state.
This method is only available if the underlying range is aforward range
Returns:
A copy ofthis.
Decoder!Rangedecoder(Range)(Rangerange)
if (isInputRange!Range);

Decoder!(const(ubyte)[])decoder()(const(char)[]range);
Construct aDecoder that iterates over the decoding of the given Base64 encoded data.
Parameters:
RangerangeAninput range over the data to be decoded, or achar array. Will not acceptwchar[] nordchar[].
Returns:
Ifrange is a range or array ofchar, aDecoder that iterates over the bytes of the corresponding Base64 decoding.
Ifrange is a range of ranges of characters, aDecoder that iterates over the decoded strings corresponding to each element of the range.
In both cases, the returnedDecoder will be aforward range if the givenrange 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 aBase64Exception.

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

foreach (decoded; Base64.decoder(stdin.byLine())){    writeln(decoded);}
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);}

Examples:
import std.algorithm.comparison : equal;string encoded ="VGhvdSBzaGFsdCBuZXZlciBjb250aW51ZSBhZnRlciBhc3NlcnRpbmcgbnVsbA==";assert(Base64.decoder(encoded)    .equal("Thou shalt never continue after asserting null"));
classBase64Exception:object.Exception;
Exception thrown upon encountering Base64 encoding or decoding errors.
Examples:
import std.exception : assertThrown;assertThrown!Base64Exception(Base64.decode("ab|c"));
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 00:53:18 2026

[8]ページ先頭

©2009-2026 Movatter.jp