2 cencoder.c - c source to a base64 encoding algorithm implementation
4 This is part of the libb64 project, and has been placed in the public domain.
5 For details, see http://sourceforge.net/projects/libb64
11 const int CHARS_PER_LINE
= 72;
14 _hidden
void _isds_base64_init_encodestate(base64_encodestate
* state_in
) {
15 state_in
->step
= step_A
;
17 state_in
->stepcount
= 0;
21 static int8_t base64_encode_value(int8_t value_in
) {
22 /* XXX: CHAR_BIT == 8 because of <stdint.h> */
23 static const int8_t encoding
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
24 if (value_in
> 63) return '=';
25 return encoding
[value_in
];
29 _hidden
size_t _isds_base64_encode_block(const int8_t* plaintext_in
,
30 size_t length_in
, int8_t *code_out
, base64_encodestate
* state_in
) {
31 const int8_t *plainchar
= plaintext_in
;
32 const int8_t* const plaintextend
= plaintext_in
+ length_in
;
33 int8_t *codechar
= code_out
;
37 result
= state_in
->result
;
39 switch (state_in
->step
) {
42 if (plainchar
== plaintextend
) {
43 state_in
->result
= result
;
44 state_in
->step
= step_A
;
45 return codechar
- code_out
;
47 fragment
= *plainchar
++;
48 result
= (fragment
& 0x0fc) >> 2;
49 *codechar
++ = base64_encode_value(result
);
50 result
= (fragment
& 0x003) << 4;
52 if (plainchar
== plaintextend
) {
53 state_in
->result
= result
;
54 state_in
->step
= step_B
;
55 return codechar
- code_out
;
57 fragment
= *plainchar
++;
58 result
|= (fragment
& 0x0f0) >> 4;
59 *codechar
++ = base64_encode_value(result
);
60 result
= (fragment
& 0x00f) << 2;
62 if (plainchar
== plaintextend
) {
63 state_in
->result
= result
;
64 state_in
->step
= step_C
;
65 return codechar
- code_out
;
67 fragment
= *plainchar
++;
68 result
|= (fragment
& 0x0c0) >> 6;
69 *codechar
++ = base64_encode_value(result
);
70 result
= (fragment
& 0x03f) >> 0;
71 *codechar
++ = base64_encode_value(result
);
73 ++(state_in
->stepcount
);
74 if (state_in
->stepcount
== CHARS_PER_LINE
/4) {
76 state_in
->stepcount
= 0;
81 /* control should not reach here */
82 return codechar
- code_out
;
86 _hidden
size_t _isds_base64_encode_blockend(int8_t *code_out
,
87 base64_encodestate
* state_in
) {
88 int8_t *codechar
= code_out
;
90 switch (state_in
->step
) {
92 *codechar
++ = base64_encode_value(state_in
->result
);
97 *codechar
++ = base64_encode_value(state_in
->result
);
105 return codechar
- code_out
;