source: josm/trunk/src/com/kitfox/svg/xml/Base64InputStream.java@ 4739

Last change on this file since 4739 was 4256, checked in by bastiK, 14 years ago

see #6560 - basic svg support, includes kitfox svgsalamander, r 98, patched

  • Property svn:executable set to *
File size: 2.0 KB
Line 
1/*
2 * To change this template, choose Tools | Templates
3 * and open the template in the editor.
4 */
5
6package com.kitfox.svg.xml;
7
8import java.io.FilterInputStream;
9import java.io.IOException;
10import java.io.InputStream;
11
12/**
13 *
14 * @author kitfox
15 */
16public 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}
Note: See TracBrowser for help on using the repository browser.