-
-
Notifications
You must be signed in to change notification settings - Fork 709
/
Copy pathbase64.d
2080 lines (1764 loc) · 63.6 KB
/
base64.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Written in the D programming language.
/**
* Support for Base64 encoding and decoding.
*
* This module provides two default implementations of Base64 encoding,
* $(LREF Base64) with a standard encoding alphabet, and a variant
* $(LREF 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
* $(LREF 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:
* $(LINK2 https://tools.ietf.org/html/rfc4648, RFC 4648 - The Base16, Base32, and Base64
* Data Encodings)
*
* Copyright: Masahiro Nakagawa 2010-.
* License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Masahiro Nakagawa, Daniel Murphy (Single value Encoder and Decoder)
* Source: $(PHOBOSSRC std/base64.d)
* Macros:
* LREF2=<a href="#$1">`$2`</a>
*/
module std.base64;
import std.exception : enforce;
import std.range.primitives : empty, front, isInputRange, isOutputRange,
isForwardRange, ElementType, hasLength, popFront, put, save;
import std.traits : isArray;
// Make sure module header code examples work correctly.
@safe unittest
{
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]);
}
/**
* Implementation of standard _Base64 encoding.
*
* See $(LREF Base64Impl) for a description of available methods.
*/
alias Base64 = Base64Impl!('+', '/');
///
@safe unittest
{
ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
assert(Base64.encode(data) == "g9cwegE/");
assert(Base64.decode("g9cwegE/") == data);
}
/**
* Variation of Base64 encoding that is safe for use in URLs and filenames.
*
* See $(LREF Base64Impl) for a description of available methods.
*/
alias Base64URL = Base64Impl!('-', '_');
///
@safe unittest
{
ubyte[] data = [0x83, 0xd7, 0x30, 0x7a, 0x01, 0x3f];
assert(Base64URL.encode(data) == "g9cwegE_");
assert(Base64URL.decode("g9cwegE_") == data);
}
/**
* 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 $(LREF Base64Impl) for a description of available methods.
*/
alias Base64URLNoPadding = Base64Impl!('-', '_', Base64.NoPadding);
///
@safe unittest
{
ubyte[] data = [0x83, 0xd7, 0x30, 0x7b, 0xef];
assert(Base64URLNoPadding.encode(data) == "g9cwe-8");
assert(Base64URLNoPadding.decode("g9cwe-8") == data);
}
/**
* Template for implementing Base64 encoding and decoding.
*
* For most purposes, direct usage of this template is not necessary; instead,
* this module provides default implementations: $(LREF Base64), implementing
* basic Base64 encoding, and $(LREF Base64URL) and $(LREF 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`.
*/
template Base64Impl(char Map62th, char Map63th, char Padding = '=')
{
enum NoPadding = '\0'; /// represents no-padding encoding
// Verify Base64 characters
static assert(Map62th < 'A' || Map62th > 'Z', "Character '" ~ Map62th ~ "' cannot be used twice");
static assert(Map63th < 'A' || Map63th > 'Z', "Character '" ~ Map63th ~ "' cannot be used twice");
static assert(Padding < 'A' || Padding > 'Z', "Character '" ~ Padding ~ "' cannot be used twice");
static assert(Map62th < 'a' || Map62th > 'z', "Character '" ~ Map62th ~ "' cannot be used twice");
static assert(Map63th < 'a' || Map63th > 'z', "Character '" ~ Map63th ~ "' cannot be used twice");
static assert(Padding < 'a' || Padding > 'z', "Character '" ~ Padding ~ "' cannot be used twice");
static assert(Map62th < '0' || Map62th > '9', "Character '" ~ Map62th ~ "' cannot be used twice");
static assert(Map63th < '0' || Map63th > '9', "Character '" ~ Map63th ~ "' cannot be used twice");
static assert(Padding < '0' || Padding > '9', "Character '" ~ Padding ~ "' cannot be used twice");
static assert(Map62th != Map63th, "Character '" ~ Map63th ~ "' cannot be used twice");
static assert(Map62th != Padding, "Character '" ~ Padding ~ "' cannot be used twice");
static assert(Map63th != Padding, "Character '" ~ Padding ~ "' cannot be used twice");
static assert(Map62th != NoPadding, "'\\0' is not a valid Base64character");
static assert(Map63th != NoPadding, "'\\0' is not a valid Base64character");
/* Encode functions */
private immutable EncodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ~ Map62th ~ Map63th;
/**
* Calculates the length needed to store the encoded string corresponding
* to an input of the given length.
*
* Params:
* sourceLength = Length of the source array.
*
* Returns:
* The length of a Base64 encoding of an array of the given length.
*/
@safe
pure nothrow size_t encodeLength(in size_t sourceLength)
{
static if (Padding == NoPadding)
return (sourceLength / 3) * 4 + (sourceLength % 3 == 0 ? 0 : sourceLength % 3 == 1 ? 2 : 3);
else
return (sourceLength / 3 + (sourceLength % 3 ? 1 : 0)) * 4;
}
///
@safe unittest
{
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);
assert(buf == "Gis8TV1u");
}
// ubyte[] to char[]
/**
* Encode $(D_PARAM source) into a `char[]` buffer using Base64
* encoding.
*
* Params:
* source = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
* to _encode.
* buffer = The `char[]` buffer to store the encoded result.
*
* Returns:
* The slice of $(D_PARAM buffer) that contains the encoded string.
*/
@trusted
pure char[] encode(R1, R2)(in R1 source, R2 buffer) if (isArray!R1 && is(ElementType!R1 : ubyte) &&
is(R2 == char[]))
in
{
assert(buffer.length >= encodeLength(source.length), "Insufficient buffer for encoding");
}
out(result)
{
assert(result.length == encodeLength(source.length), "The length of result is different from Base64");
}
do
{
immutable srcLen = source.length;
if (srcLen == 0)
return [];
immutable blocks = srcLen / 3;
immutable remain = srcLen % 3;
auto bufptr = buffer.ptr;
auto srcptr = source.ptr;
foreach (Unused; 0 .. blocks)
{
immutable val = srcptr[0] << 16 | srcptr[1] << 8 | srcptr[2];
*bufptr++ = EncodeMap[val >> 18 ];
*bufptr++ = EncodeMap[val >> 12 & 0x3f];
*bufptr++ = EncodeMap[val >> 6 & 0x3f];
*bufptr++ = EncodeMap[val & 0x3f];
srcptr += 3;
}
if (remain)
{
immutable val = srcptr[0] << 16 | (remain == 2 ? srcptr[1] << 8 : 0);
*bufptr++ = EncodeMap[val >> 18 ];
*bufptr++ = EncodeMap[val >> 12 & 0x3f];
final switch (remain)
{
case 2:
*bufptr++ = EncodeMap[val >> 6 & 0x3f];
static if (Padding != NoPadding)
*bufptr++ = Padding;
break;
case 1:
static if (Padding != NoPadding)
{
*bufptr++ = Padding;
*bufptr++ = Padding;
}
break;
}
}
// encode method can't assume buffer length. So, slice needed.
return buffer[0 .. bufptr - buffer.ptr];
}
///
@safe unittest
{
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]);
assert(encoded == "g9cwegE/");
}
// InputRange to char[]
/**
* ditto
*/
char[] encode(R1, R2)(R1 source, R2 buffer) if (!isArray!R1 && isInputRange!R1 &&
is(ElementType!R1 : ubyte) && hasLength!R1 &&
is(R2 == char[]))
in
{
assert(buffer.length >= encodeLength(source.length), "Insufficient buffer for encoding");
}
out(result)
{
// @@@BUG@@@ D's DbC can't caputre an argument of function and store the result of precondition.
//assert(result.length == encodeLength(source.length), "The length of result is different from Base64");
}
do
{
immutable srcLen = source.length;
if (srcLen == 0)
return [];
immutable blocks = srcLen / 3;
immutable remain = srcLen % 3;
auto bufptr = buffer.ptr;
foreach (Unused; 0 .. blocks)
{
immutable v1 = source.front; source.popFront();
immutable v2 = source.front; source.popFront();
immutable v3 = source.front; source.popFront();
immutable val = v1 << 16 | v2 << 8 | v3;
*bufptr++ = EncodeMap[val >> 18 ];
*bufptr++ = EncodeMap[val >> 12 & 0x3f];
*bufptr++ = EncodeMap[val >> 6 & 0x3f];
*bufptr++ = EncodeMap[val & 0x3f];
}
if (remain)
{
size_t val = source.front << 16;
if (remain == 2)
{
source.popFront();
val |= source.front << 8;
}
*bufptr++ = EncodeMap[val >> 18 ];
*bufptr++ = EncodeMap[val >> 12 & 0x3f];
final switch (remain)
{
case 2:
*bufptr++ = EncodeMap[val >> 6 & 0x3f];
static if (Padding != NoPadding)
*bufptr++ = Padding;
break;
case 1:
static if (Padding != NoPadding)
{
*bufptr++ = Padding;
*bufptr++ = Padding;
}
break;
}
}
// @@@BUG@@@ Workaround for DbC problem. See comment on 'out'.
version (StdUnittest)
assert(
bufptr - buffer.ptr == encodeLength(srcLen),
"The length of result is different from Base64"
);
// encode method can't assume buffer length. So, slice needed.
return buffer[0 .. bufptr - buffer.ptr];
}
// ubyte[] to OutputRange
/**
* Encodes $(D_PARAM source) into an
* $(REF_ALTTEXT output range, isOutputRange, std,range,primitives) using
* Base64 encoding.
*
* Params:
* source = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
* to _encode.
* range = The $(REF_ALTTEXT output range, isOutputRange, std,range,primitives)
* to store the encoded result.
*
* Returns:
* The number of times the output range's `put` method was invoked.
*/
size_t encode(E, R)(scope const(E)[] source, auto ref R range)
if (is(E : ubyte) && isOutputRange!(R, char) && !is(R == char[]))
out(result)
{
assert(result == encodeLength(source.length), "The number of put is different from the length of Base64");
}
do
{
immutable srcLen = source.length;
if (srcLen == 0)
return 0;
immutable blocks = srcLen / 3;
immutable remain = srcLen % 3;
auto s = source; // copy for out contract length check
size_t pcount;
foreach (Unused; 0 .. blocks)
{
immutable val = s[0] << 16 | s[1] << 8 | s[2];
put(range, EncodeMap[val >> 18 ]);
put(range, EncodeMap[val >> 12 & 0x3f]);
put(range, EncodeMap[val >> 6 & 0x3f]);
put(range, EncodeMap[val & 0x3f]);
s = s[3 .. $];
pcount += 4;
}
if (remain)
{
immutable val = s[0] << 16 | (remain == 2 ? s[1] << 8 : 0);
put(range, EncodeMap[val >> 18 ]);
put(range, EncodeMap[val >> 12 & 0x3f]);
pcount += 2;
final switch (remain)
{
case 2:
put(range, EncodeMap[val >> 6 & 0x3f]);
pcount++;
static if (Padding != NoPadding)
{
put(range, Padding);
pcount++;
}
break;
case 1:
static if (Padding != NoPadding)
{
put(range, Padding);
put(range, Padding);
pcount += 2;
}
break;
}
}
return pcount;
}
///
@safe pure nothrow unittest
{
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.
assert(Base64.encode(data, output) == 8);
assert(output.data == "Gis8TV1u");
}
// InputRange to OutputRange
/**
* ditto
*/
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))
{
immutable srcLen = source.length;
if (srcLen == 0)
return 0;
immutable blocks = srcLen / 3;
immutable remain = srcLen % 3;
size_t pcount;
foreach (Unused; 0 .. blocks)
{
immutable v1 = source.front; source.popFront();
immutable v2 = source.front; source.popFront();
immutable v3 = source.front; source.popFront();
immutable val = v1 << 16 | v2 << 8 | v3;
put(range, EncodeMap[val >> 18 ]);
put(range, EncodeMap[val >> 12 & 0x3f]);
put(range, EncodeMap[val >> 6 & 0x3f]);
put(range, EncodeMap[val & 0x3f]);
pcount += 4;
}
if (remain)
{
size_t val = source.front << 16;
if (remain == 2)
{
source.popFront();
val |= source.front << 8;
}
put(range, EncodeMap[val >> 18 ]);
put(range, EncodeMap[val >> 12 & 0x3f]);
pcount += 2;
final switch (remain)
{
case 2:
put(range, EncodeMap[val >> 6 & 0x3f]);
pcount++;
static if (Padding != NoPadding)
{
put(range, Padding);
pcount++;
}
break;
case 1:
static if (Padding != NoPadding)
{
put(range, Padding);
put(range, Padding);
pcount += 2;
}
break;
}
}
// @@@BUG@@@ Workaround for DbC problem.
version (StdUnittest)
assert(
pcount == encodeLength(srcLen),
"The number of put is different from the length of Base64"
);
return pcount;
}
/**
* Encodes $(D_PARAM source) to newly-allocated buffer.
*
* This convenience method alleviates the need to manually manage output
* buffers.
*
* Params:
* source = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
* to _encode.
*
* Returns:
* A newly-allocated `char[]` buffer containing the encoded string.
*/
@safe
pure char[] encode(Range)(Range source) if (isArray!Range && is(ElementType!Range : ubyte))
{
return encode(source, new char[encodeLength(source.length)]);
}
///
@safe unittest
{
ubyte[] data = [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e];
assert(Base64.encode(data) == "Gis8TV1u");
}
/**
* ditto
*/
char[] encode(Range)(Range source) if (!isArray!Range && isInputRange!Range &&
is(ElementType!Range : ubyte) && hasLength!Range)
{
return encode(source, new char[encodeLength(source.length)]);
}
/**
* An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) that
* iterates over the respective Base64 encodings of a range of data items.
*
* This range will be a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
* 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 $(LREF encoder) function instead.
*/
struct Encoder(Range) if (isInputRange!Range && (is(ElementType!Range : const(ubyte)[]) ||
is(ElementType!Range : const(char)[])))
{
private:
Range range_;
char[] buffer_, encoded_;
public:
this(Range range)
{
range_ = range;
doEncoding();
}
/**
* Returns:
* true if there is no more encoded data left.
*/
@property @trusted
bool empty()
{
return range_.empty;
}
/**
* Returns: The current chunk of encoded data.
*/
@property @safe
nothrow char[] front()
{
return encoded_;
}
/**
* Advance the range to the next chunk of encoded data.
*
* Throws:
* `Base64Exception` If invoked when
* $(LREF2 .Base64Impl.Encoder.empty, empty) returns `true`.
*/
void popFront()
{
enforce(!empty, new Base64Exception("Cannot call popFront on Encoder with no data remaining"));
range_.popFront();
/*
* This check is very ugly. I think this is a Range's flaw.
* I very strongly want the Range guideline for unified implementation.
*
* In this case, Encoder becomes a beautiful implementation if 'front' performs Base64 encoding.
*/
if (!empty)
doEncoding();
}
static if (isForwardRange!Range)
{
/**
* Save the current iteration state of the range.
*
* This method is only available if the underlying range is a
* $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives).
*
* Returns:
* A copy of `this`.
*/
@property
typeof(this) save()
{
typeof(return) encoder;
encoder.range_ = range_.save;
encoder.buffer_ = buffer_.dup;
encoder.encoded_ = encoder.buffer_[0 .. encoded_.length];
return encoder;
}
}
private:
void doEncoding()
{
auto data = cast(const(ubyte)[])range_.front;
auto size = encodeLength(data.length);
if (size > buffer_.length)
buffer_.length = size;
encoded_ = encode(data, buffer_);
}
}
/**
* An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) that
* iterates over the encoded bytes of the given source data.
*
* It will be a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
* 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 $(LREF encoder) function instead.
*/
struct Encoder(Range) if (isInputRange!Range && is(ElementType!Range : ubyte))
{
private:
Range range_;
ubyte first;
int pos, padding;
public:
this(Range range)
{
range_ = range;
static if (isForwardRange!Range)
range_ = range_.save;
if (range_.empty)
pos = -1;
else
popFront();
}
/**
* Returns:
* true if there are no more encoded characters to be iterated.
*/
@property @safe
nothrow bool empty() const
{
static if (Padding == NoPadding)
return pos < 0;
else
return pos < 0 && !padding;
}
/**
* Returns: The current encoded character.
*/
@property @safe
nothrow ubyte front()
{
return first;
}
/**
* Advance to the next encoded character.
*
* Throws:
* `Base64Exception` If invoked when $(LREF2 .Base64Impl.Encoder.empty.2,
* empty) returns `true`.
*/
void popFront()
{
enforce(!empty, new Base64Exception("Cannot call popFront on Encoder with no data remaining"));
static if (Padding != NoPadding)
if (padding)
{
first = Padding;
pos = -1;
padding--;
return;
}
if (range_.empty)
{
pos = -1;
return;
}
final switch (pos)
{
case 0:
first = EncodeMap[range_.front >> 2];
break;
case 1:
immutable t = (range_.front & 0b11) << 4;
range_.popFront();
if (range_.empty)
{
first = EncodeMap[t];
padding = 3;
}
else
{
first = EncodeMap[t | (range_.front >> 4)];
}
break;
case 2:
immutable t = (range_.front & 0b1111) << 2;
range_.popFront();
if (range_.empty)
{
first = EncodeMap[t];
padding = 2;
}
else
{
first = EncodeMap[t | (range_.front >> 6)];
}
break;
case 3:
first = EncodeMap[range_.front & 0b111111];
range_.popFront();
break;
}
++pos %= 4;
}
static if (isForwardRange!Range)
{
/**
* Save the current iteration state of the range.
*
* This method is only available if the underlying range is a
* $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives).
*
* Returns:
* A copy of `this`.
*/
@property
typeof(this) save()
{
auto encoder = this;
encoder.range_ = encoder.range_.save;
return encoder;
}
}
}
/**
* Construct an `Encoder` that iterates over the Base64 encoding of the
* given $(REF_ALTTEXT input range, isInputRange, std,range,primitives).
*
* Params:
* range = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
* over the data to be encoded.
*
* Returns:
* If $(D_PARAM range) is a range of bytes, an `Encoder` that iterates
* over the bytes of the corresponding Base64 encoding.
*
* If $(D_PARAM 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
* $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) 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);
* }
* -----
*/
Encoder!(Range) encoder(Range)(Range range) if (isInputRange!Range)
{
return typeof(return)(range);
}
/* Decode functions */
private immutable int[char.max + 1] DecodeMap = [
'A':0b000000, 'B':0b000001, 'C':0b000010, 'D':0b000011, 'E':0b000100,
'F':0b000101, 'G':0b000110, 'H':0b000111, 'I':0b001000, 'J':0b001001,
'K':0b001010, 'L':0b001011, 'M':0b001100, 'N':0b001101, 'O':0b001110,
'P':0b001111, 'Q':0b010000, 'R':0b010001, 'S':0b010010, 'T':0b010011,
'U':0b010100, 'V':0b010101, 'W':0b010110, 'X':0b010111, 'Y':0b011000,
'Z':0b011001, 'a':0b011010, 'b':0b011011, 'c':0b011100, 'd':0b011101,
'e':0b011110, 'f':0b011111, 'g':0b100000, 'h':0b100001, 'i':0b100010,
'j':0b100011, 'k':0b100100, 'l':0b100101, 'm':0b100110, 'n':0b100111,
'o':0b101000, 'p':0b101001, 'q':0b101010, 'r':0b101011, 's':0b101100,
't':0b101101, 'u':0b101110, 'v':0b101111, 'w':0b110000, 'x':0b110001,
'y':0b110010, 'z':0b110011, '0':0b110100, '1':0b110101, '2':0b110110,
'3':0b110111, '4':0b111000, '5':0b111001, '6':0b111010, '7':0b111011,
'8':0b111100, '9':0b111101, Map62th:0b111110, Map63th:0b111111, Padding:-1
];
/**
* Given a Base64 encoded string, calculates the length of the decoded
* string.
*
* Params:
* sourceLength = The length of the Base64 encoding.
*
* Returns:
* The length of the decoded string corresponding to a Base64 encoding of
* length $(D_PARAM sourceLength).
*/
@safe
pure nothrow size_t decodeLength(in size_t sourceLength)
{
static if (Padding == NoPadding)
return (sourceLength / 4) * 3 + (sourceLength % 4 < 2 ? 0 : sourceLength % 4 == 2 ? 1 : 2);
else
return (sourceLength / 4) * 3;
}
///
@safe unittest
{
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);
assert(buffer == [0x1a, 0x2b, 0x3c, 0x4d, 0x5d, 0x6e]);
}
// Used in decode contracts. Calculates the actual size the decoded
// result should have, taking into account trailing padding.
@safe
pure nothrow private size_t realDecodeLength(R)(R source)
{
auto expect = decodeLength(source.length);
static if (Padding != NoPadding)
{
if (source.length % 4 == 0)
{
expect -= source.length == 0 ? 0 :
source[$ - 2] == Padding ? 2 :
source[$ - 1] == Padding ? 1 : 0;
}
}
return expect;
}
// char[] to ubyte[]
/**
* Decodes $(D_PARAM source) into the given buffer.
*
* Params:
* source = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
* to _decode.
* buffer = The buffer to store decoded result.
*
* Returns:
* The slice of $(D_PARAM buffer) containing the decoded result.
*
* Throws:
* `Base64Exception` if $(D_PARAM source) contains characters outside the
* base alphabet of the current Base64 encoding scheme.
*/
@trusted
pure ubyte[] decode(R1, R2)(in R1 source, R2 buffer) if (isArray!R1 && is(ElementType!R1 : dchar) &&
is(R2 == ubyte[]) && isOutputRange!(R2, ubyte))
in
{
assert(buffer.length >= realDecodeLength(source), "Insufficient buffer for decoding");
}
out(result)
{
immutable expect = realDecodeLength(source);
assert(result.length == expect, "The length of result is different from the expected length");
}
do
{
immutable srcLen = source.length;
if (srcLen == 0)
return [];
static if (Padding != NoPadding)
enforce(srcLen % 4 == 0, new Base64Exception("Invalid length of encoded data"));