doc: Update list of user web service according to spec. 2009-10-30
[libisds.git] / src / cencode.c
blob6a62fcf111832a6381a0c12ffe820fe643a8fe08
1 /*
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
6 */
8 #include "cencode.h"
9 #include "utils.h"
11 const int CHARS_PER_LINE = 72;
13 _hidden void base64_init_encodestate(base64_encodestate* state_in)
15 state_in->step = step_A;
16 state_in->result = 0;
17 state_in->stepcount = 0;
20 _hidden char base64_encode_value(char value_in)
22 static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23 if (value_in > 63) return '=';
24 return encoding[(int)value_in];
27 _hidden int base64_encode_block(const char* plaintext_in, int length_in,
28 char* code_out, base64_encodestate* state_in)
30 const char* plainchar = plaintext_in;
31 const char* const plaintextend = plaintext_in + length_in;
32 char* codechar = code_out;
33 char result;
34 char fragment;
36 result = state_in->result;
38 switch (state_in->step)
40 while (1)
42 case step_A:
43 if (plainchar == plaintextend)
45 state_in->result = result;
46 state_in->step = step_A;
47 return codechar - code_out;
49 fragment = *plainchar++;
50 result = (fragment & 0x0fc) >> 2;
51 *codechar++ = base64_encode_value(result);
52 result = (fragment & 0x003) << 4;
53 case step_B:
54 if (plainchar == plaintextend)
56 state_in->result = result;
57 state_in->step = step_B;
58 return codechar - code_out;
60 fragment = *plainchar++;
61 result |= (fragment & 0x0f0) >> 4;
62 *codechar++ = base64_encode_value(result);
63 result = (fragment & 0x00f) << 2;
64 case step_C:
65 if (plainchar == plaintextend)
67 state_in->result = result;
68 state_in->step = step_C;
69 return codechar - code_out;
71 fragment = *plainchar++;
72 result |= (fragment & 0x0c0) >> 6;
73 *codechar++ = base64_encode_value(result);
74 result = (fragment & 0x03f) >> 0;
75 *codechar++ = base64_encode_value(result);
77 ++(state_in->stepcount);
78 if (state_in->stepcount == CHARS_PER_LINE/4)
80 *codechar++ = '\n';
81 state_in->stepcount = 0;
85 /* control should not reach here */
86 return codechar - code_out;
89 _hidden int base64_encode_blockend(char* code_out, base64_encodestate* state_in)
91 char* codechar = code_out;
93 switch (state_in->step)
95 case step_B:
96 *codechar++ = base64_encode_value(state_in->result);
97 *codechar++ = '=';
98 *codechar++ = '=';
99 break;
100 case step_C:
101 *codechar++ = base64_encode_value(state_in->result);
102 *codechar++ = '=';
103 break;
104 case step_A:
105 break;
107 *codechar++ = '\n';
109 return codechar - code_out;