| 1 | /*
|
|---|
| 2 | * To change this template, choose Tools | Templates
|
|---|
| 3 | * and open the template in the editor.
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | package com.kitfox.svg.xml;
|
|---|
| 7 |
|
|---|
| 8 | import java.io.FilterInputStream;
|
|---|
| 9 | import java.io.IOException;
|
|---|
| 10 | import java.io.InputStream;
|
|---|
| 11 |
|
|---|
| 12 | /**
|
|---|
| 13 | *
|
|---|
| 14 | * @author kitfox
|
|---|
| 15 | */
|
|---|
| 16 | public class Base64InputStream extends FilterInputStream
|
|---|
| 17 | {
|
|---|
| 18 | int buf; //Cached bytes to read
|
|---|
| 19 | int bufSize; //Number of bytes waiting to be read from buffer
|
|---|
| 20 | boolean drain = false; //After set, read no more chunks
|
|---|
| 21 |
|
|---|
| 22 | public Base64InputStream(InputStream in)
|
|---|
| 23 | {
|
|---|
| 24 | super(in);
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | public int read() throws IOException
|
|---|
| 28 | {
|
|---|
| 29 | if (drain && bufSize == 0)
|
|---|
| 30 | {
|
|---|
| 31 | return -1;
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | if (bufSize == 0)
|
|---|
| 35 | {
|
|---|
| 36 | //Read next chunk into 4 byte buffer
|
|---|
| 37 | int chunk = in.read();
|
|---|
| 38 | if (chunk == -1)
|
|---|
| 39 | {
|
|---|
| 40 | drain = true;
|
|---|
| 41 | return -1;
|
|---|
| 42 | }
|
|---|
| 43 |
|
|---|
| 44 | //get remaining 3 bytes
|
|---|
| 45 | for (int i = 0; i < 3; ++i)
|
|---|
| 46 | {
|
|---|
| 47 | int value = in.read();
|
|---|
| 48 | if (value == -1)
|
|---|
| 49 | {
|
|---|
| 50 | throw new IOException("Early termination of base64 stream");
|
|---|
| 51 | }
|
|---|
| 52 | chunk = (chunk << 8) | (value & 0xff);
|
|---|
| 53 | }
|
|---|
| 54 |
|
|---|
| 55 | //Check for special termination characters
|
|---|
| 56 | if ((chunk & 0xffff) == (((byte)'=' << 8) | (byte)'='))
|
|---|
| 57 | {
|
|---|
| 58 | bufSize = 1;
|
|---|
| 59 | drain = true;
|
|---|
| 60 | }
|
|---|
| 61 | else if ((chunk & 0xff) == (byte)'=')
|
|---|
| 62 | {
|
|---|
| 63 | bufSize = 2;
|
|---|
| 64 | drain = true;
|
|---|
| 65 | }
|
|---|
| 66 | else
|
|---|
| 67 | {
|
|---|
| 68 | bufSize = 3;
|
|---|
| 69 | }
|
|---|
| 70 |
|
|---|
| 71 | //Fill buffer with decoded characters
|
|---|
| 72 | for (int i = 0; i < bufSize + 1; ++i)
|
|---|
| 73 | {
|
|---|
| 74 | buf = (buf << 6) | Base64Util.decodeByte((chunk >> 24) & 0xff);
|
|---|
| 75 | chunk <<= 8;
|
|---|
| 76 | }
|
|---|
| 77 | }
|
|---|
| 78 |
|
|---|
| 79 | //Return nth remaing bte & decrement counter
|
|---|
| 80 | return (buf >> (--bufSize * 8)) & 0xff;
|
|---|
| 81 | }
|
|---|
| 82 | }
|
|---|