1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package ascii85 implements the ascii85 data encoding
6 // as used in the btoa tool and Adobe's PostScript and PDF document formats.
19 // Encode encodes src into at most MaxEncodedLen(len(src))
20 // bytes of dst, returning the actual number of bytes written.
22 // The encoding handles 4-byte chunks, using a special encoding
23 // for the last fragment, so Encode is not appropriate for use on
24 // individual blocks of a large data stream. Use NewEncoder() instead.
26 // Often, ascii85-encoded data is wrapped in <~ and ~> symbols.
27 // Encode does not add these.
28 func Encode(dst, src []byte) int {
41 // Unpack 4 bytes into uint32 to repack into base 85 5-byte.
48 v |= uint32(src[2]) << 8
51 v |= uint32(src[1]) << 16
54 v |= uint32(src[0]) << 24
57 // Special case: zero (!!!!!) shortens to z.
58 if v == 0 && len(src) >= 4 {
65 // Otherwise, 5 base 85 digits starting at !.
66 for i := 4; i >= 0; i-- {
67 dst[i] = '!' + byte(v%85)
71 // If src was short, discard the low destination bytes.
85 // MaxEncodedLen returns the maximum length of an encoding of n source bytes.
86 func MaxEncodedLen(n int) int { return (n + 3) / 4 * 5 }
88 // NewEncoder returns a new ascii85 stream encoder. Data written to
89 // the returned writer will be encoded and then written to w.
90 // Ascii85 encodings operate in 32-bit blocks; when finished
91 // writing, the caller must Close the returned encoder to flush any
92 // trailing partial block.
93 func NewEncoder(w io.Writer) io.WriteCloser { return &encoder{w: w} }
98 buf [4]byte // buffered data waiting to be encoded
99 nbuf int // number of bytes in buf
100 out [1024]byte // output buffer
103 func (e *encoder) Write(p []byte) (n int, err os.Error) {
111 for i = 0; i < len(p) && e.nbuf < 4; i++ {
120 nout := Encode(e.out[0:], e.buf[0:])
121 if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil {
127 // Large interior chunks.
129 nn := len(e.out) / 5 * 4
135 nout := Encode(e.out[0:], p[0:nn])
136 if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil {
145 for i := 0; i < len(p); i++ {
153 // Close flushes any pending output from the encoder.
154 // It is an error to call Write after calling Close.
155 func (e *encoder) Close() os.Error {
156 // If there's anything left in the buffer, flush it out
157 if e.err == nil && e.nbuf > 0 {
158 nout := Encode(e.out[0:], e.buf[0:e.nbuf])
160 _, e.err = e.w.Write(e.out[0:nout])
169 type CorruptInputError int64
171 func (e CorruptInputError) String() string {
172 return "illegal ascii85 data at input byte " + strconv.Itoa64(int64(e))
175 // Decode decodes src into dst, returning both the number
176 // of bytes written to dst and the number consumed from src.
177 // If src contains invalid ascii85 data, Decode will return the
178 // number of bytes successfully written and a CorruptInputError.
179 // Decode ignores space and control characters in src.
180 // Often, ascii85-encoded data is wrapped in <~ and ~> symbols.
181 // Decode expects these to have been stripped by the caller.
183 // If flush is true, Decode assumes that src represents the
184 // end of the input stream and processes it completely rather
185 // than wait for the completion of another 32-bit block.
187 // NewDecoder wraps an io.Reader interface around Decode.
189 func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err os.Error) {
192 for i, b := range src {
193 if len(dst)-ndst < 4 {
199 case b == 'z' && nb == 0:
202 case '!' <= b && b <= 'u':
203 v = v*85 + uint32(b-'!')
206 return 0, 0, CorruptInputError(i)
210 dst[ndst] = byte(v >> 24)
211 dst[ndst+1] = byte(v >> 16)
212 dst[ndst+2] = byte(v >> 8)
213 dst[ndst+3] = byte(v)
222 // The number of output bytes in the last fragment
223 // is the number of leftover input bytes - 1:
224 // the extra byte provides enough bits to cover
225 // the inefficiency of the encoding for the block.
227 return 0, 0, CorruptInputError(len(src))
229 for i := nb; i < 5; i++ {
230 // The short encoding truncated the output value.
231 // We have to assume the worst case values (digit 84)
232 // in order to ensure that the top bits are correct.
235 for i := 0; i < nb-1; i++ {
236 dst[ndst] = byte(v >> 24)
245 // NewDecoder constructs a new ascii85 stream decoder.
246 func NewDecoder(r io.Reader) io.Reader { return &decoder{r: r} }
248 type decoder struct {
252 end bool // saw end of message
253 buf [1024]byte // leftover input
255 out []byte // leftover decoded output
259 func (d *decoder) Read(p []byte) (n int, err os.Error) {
268 // Copy leftover output from last decode.
275 // Decode leftover input from last read.
276 var nn, nsrc, ndst int
278 ndst, nsrc, d.err = Decode(d.outbuf[0:], d.buf[0:d.nbuf], d.readErr != nil)
280 d.out = d.outbuf[0:ndst]
281 d.nbuf = copy(d.buf[0:], d.buf[nsrc:d.nbuf])
282 continue // copy out and return
286 // Out of input, out of decoded output. Check errors.
290 if d.readErr != nil {
296 nn, d.readErr = d.r.Read(d.buf[d.nbuf:])