I found this function which encodes a stream as a Base64 string. I'm using this string inside JSON. The problem is that the output of this function has line breaks, which is not acceptable in JSON without escaping it. How do I get around this?
const
Base64Codes:array[0..63] of char=
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function Base64Encode(AStream: TStream): string;
const
dSize=57*100;//must be multiple of 3
var
d:array[0..dSize-1] of byte;
i,l:integer;
begin
Result:='';
l:=dSize;
while l=dSize do
begin
l:=AStream.Read(d[0],dSize);
i:=0;
while i<l do
begin
if i+1=l then
Result:=Result+
Base64Codes[ d[i ] shr 2]+
Base64Codes[((d[i ] and $3) shl 4)]+
'=='
else if i+2=l then
Result:=Result+
Base64Codes[ d[i ] shr 2]+
Base64Codes[((d[i ] and $3) shl 4) or (d[i+1] shr 4)]+
Base64Codes[((d[i+1] and $F) shl 2)]+
'='
else
Result:=Result+
Base64Codes[ d[i ] shr 2]+
Base64Codes[((d[i ] and $3) shl 4) or (d[i+1] shr 4)]+
Base64Codes[((d[i+1] and $F) shl 2) or (d[i+2] shr 6)]+
Base64Codes[ d[i+2] and $3F];
inc(i,3);
if ((i mod 57)=0) then Result:=Result+#13#10;
end;
end;
end;
Of course all line breaks need to be escaped for JSON, but the question is what to do with these line breaks... Should I escape them and keep them in the encoded string, or should I discard them? I'm not sure if it's a relevant part of Base64, or if this particular piece of code is putting line breaks just to make it easier to read.