github.com/rsc/tmp@v0.0.0-20240517235954-6deaab19748b/git85/git.go (about)

     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.
     4  
     5  // Package git85 implements the radix 85 data encoding
     6  // used in the Git version control system.
     7  package git85
     8  
     9  import (
    10  	"bytes"
    11  	"io"
    12  	"strconv"
    13  )
    14  
    15  type CorruptInputError int64
    16  
    17  func (e CorruptInputError) Error() string {
    18  	return "illegal git85 data at input byte " + strconv.FormatInt(int64(e), 10)
    19  }
    20  
    21  const encode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
    22  
    23  // The decodings are 1+ the actual value, so that the
    24  // default zero value can be used to mean "not valid".
    25  var decode = [256]uint8{
    26  	'0': 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    27  	'A': 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
    28  	24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
    29  	'a': 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
    30  	50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
    31  	'!': 63,
    32  	'#': 64, 65, 66, 67,
    33  	'(': 68, 69, 70, 71,
    34  	'-': 72,
    35  	';': 73,
    36  	'<': 74, 75, 76, 77,
    37  	'@': 78,
    38  	'^': 79, 80, 81,
    39  	'{': 82, 83, 84, 85,
    40  }
    41  
    42  // Encode encodes src into EncodedLen(len(src))
    43  // bytes of dst.  As a convenience, it returns the number
    44  // of bytes written to dst, but this value is always EncodedLen(len(src)).
    45  // Encode implements the radix 85 encoding used in the
    46  // Git version control tool.
    47  //
    48  // The encoding splits src into chunks of at most 52 bytes
    49  // and encodes each chunk on its own line.
    50  func Encode(dst, src []byte) int {
    51  	ndst := 0
    52  	for len(src) > 0 {
    53  		n := len(src)
    54  		if n > 52 {
    55  			n = 52
    56  		}
    57  		if n <= 27 {
    58  			dst[ndst] = byte('A' + n - 1)
    59  		} else {
    60  			dst[ndst] = byte('a' + n - 26 - 1)
    61  		}
    62  		ndst++
    63  		for i := 0; i < n; i += 4 {
    64  			var v uint32
    65  			for j := 0; j < 4 && i+j < n; j++ {
    66  				v |= uint32(src[i+j]) << uint(24-j*8)
    67  			}
    68  			for j := 4; j >= 0; j-- {
    69  				dst[ndst+j] = encode[v%85]
    70  				v /= 85
    71  			}
    72  			ndst += 5
    73  		}
    74  		dst[ndst] = '\n'
    75  		ndst++
    76  		src = src[n:]
    77  	}
    78  	return ndst
    79  }
    80  
    81  // EncodedLen returns the length of an encoding of n source bytes.
    82  func EncodedLen(n int) int {
    83  	if n == 0 {
    84  		return 0
    85  	}
    86  	// 5 bytes per 4 bytes of input, rounded up.
    87  	// 2 extra bytes for each line of 52 src bytes, rounded up.
    88  	return (n+3)/4*5 + (n+51)/52*2
    89  }
    90  
    91  var newline = []byte{'\n'}
    92  
    93  // Decode decodes src into at most MaxDecodedLen(len(src))
    94  // bytes, returning the actual number of bytes written to dst.
    95  //
    96  // If Decode encounters invalid input, it returns a CorruptInputError.
    97  //
    98  func Decode(dst, src []byte) (n int, err error) {
    99  	ndst := 0
   100  	nsrc := 0
   101  	for nsrc < len(src) {
   102  		var l int
   103  		switch ch := int(src[nsrc]); {
   104  		case 'A' <= ch && ch <= 'Z':
   105  			l = ch - 'A' + 1
   106  		case 'a' <= ch && ch <= 'z':
   107  			l = ch - 'a' + 26 + 1
   108  		default:
   109  			return ndst, CorruptInputError(nsrc)
   110  		}
   111  		if nsrc+1+l > len(src) {
   112  			return ndst, CorruptInputError(nsrc)
   113  		}
   114  		el := (l + 3) / 4 * 5 // encoded len
   115  		if nsrc+1+el+1 > len(src) || src[nsrc+1+el] != '\n' {
   116  			return ndst, CorruptInputError(nsrc)
   117  		}
   118  		line := src[nsrc+1 : nsrc+1+el]
   119  		for i := 0; i < el; i += 5 {
   120  			var v uint32
   121  			for j := 0; j < 5; j++ {
   122  				ch := decode[line[i+j]]
   123  				if ch == 0 {
   124  					return ndst, CorruptInputError(nsrc + 1 + i + j)
   125  				}
   126  				v = v*85 + uint32(ch-1)
   127  			}
   128  			for j := 0; j < 4; j++ {
   129  				dst[ndst] = byte(v >> 24)
   130  				v <<= 8
   131  				ndst++
   132  			}
   133  		}
   134  		// Last fragment may have run too far (but there was room in dst).
   135  		// Back up.
   136  		if l%4 != 0 {
   137  			ndst -= 4 - l%4
   138  		}
   139  		nsrc += 1 + el + 1
   140  	}
   141  	return ndst, nil
   142  }
   143  
   144  func MaxDecodedLen(n int) int { return n / 5 * 4 }
   145  
   146  // NewEncoder returns a new Git base85 stream encoder.  Data written to
   147  // the returned writer will be encoded and then written to w.
   148  // The Git encoding operates on 52-byte blocks; when finished
   149  // writing, the caller must Close the returned encoder to flush any
   150  // partially written blocks.
   151  func NewEncoder(w io.Writer) io.WriteCloser { return &encoder{w: w} }
   152  
   153  type encoder struct {
   154  	w    io.Writer
   155  	err  error
   156  	buf  [52]byte
   157  	nbuf int
   158  	out  [1024]byte
   159  	nout int
   160  }
   161  
   162  func (e *encoder) Write(p []byte) (n int, err error) {
   163  	if e.err != nil {
   164  		return 0, e.err
   165  	}
   166  
   167  	// Leading fringe.
   168  	if e.nbuf > 0 {
   169  		var i int
   170  		for i = 0; i < len(p) && e.nbuf < 52; i++ {
   171  			e.buf[e.nbuf] = p[i]
   172  			e.nbuf++
   173  		}
   174  		n += i
   175  		p = p[i:]
   176  		if e.nbuf < 52 {
   177  			return
   178  		}
   179  		nout := Encode(e.out[0:], e.buf[0:])
   180  		if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil {
   181  			return n, e.err
   182  		}
   183  		e.nbuf = 0
   184  	}
   185  
   186  	// Large interior chunks.
   187  	for len(p) >= 52 {
   188  		nn := len(e.out) / (1 + 52/4*5 + 1) * 52
   189  		if nn > len(p) {
   190  			nn = len(p) / 52 * 52
   191  		}
   192  		if nn > 0 {
   193  			nout := Encode(e.out[0:], p[0:nn])
   194  			if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil {
   195  				return n, e.err
   196  			}
   197  		}
   198  		n += nn
   199  		p = p[nn:]
   200  	}
   201  
   202  	// Trailing fringe.
   203  	for i := 0; i < len(p); i++ {
   204  		e.buf[i] = p[i]
   205  	}
   206  	e.nbuf = len(p)
   207  	n += len(p)
   208  	return
   209  }
   210  
   211  func (e *encoder) Close() error {
   212  	// If there's anything left in the buffer, flush it out
   213  	if e.err == nil && e.nbuf > 0 {
   214  		nout := Encode(e.out[0:], e.buf[0:e.nbuf])
   215  		e.nbuf = 0
   216  		_, e.err = e.w.Write(e.out[0:nout])
   217  	}
   218  	return e.err
   219  }
   220  
   221  // NewDecoder returns a new Git base85 stream decoder.
   222  func NewDecoder(r io.Reader) io.Reader { return &decoder{r: r} }
   223  
   224  type decoder struct {
   225  	r       io.Reader
   226  	err     error
   227  	readErr error
   228  	buf     [1024]byte
   229  	nbuf    int
   230  	out     []byte
   231  	outbuf  [1024]byte
   232  	off     int64
   233  }
   234  
   235  func (d *decoder) Read(p []byte) (n int, err error) {
   236  	if len(p) == 0 {
   237  		return 0, nil
   238  	}
   239  
   240  	for {
   241  		// Copy leftover output from last decode.
   242  		if len(d.out) > 0 {
   243  			n = copy(p, d.out)
   244  			d.out = d.out[n:]
   245  			return
   246  		}
   247  
   248  		// Out of decoded output.  Check errors.
   249  		if d.err != nil {
   250  			return 0, d.err
   251  		}
   252  		if d.readErr != nil {
   253  			d.err = d.readErr
   254  			return 0, d.err
   255  		}
   256  
   257  		// Read and decode more input.
   258  		var nn int
   259  		nn, d.readErr = d.r.Read(d.buf[d.nbuf:])
   260  		d.nbuf += nn
   261  
   262  		// Send complete lines to Decode.
   263  		nl := bytes.LastIndex(d.buf[0:d.nbuf], newline)
   264  		if nl < 0 {
   265  			continue
   266  		}
   267  		nn, d.err = Decode(d.outbuf[0:], d.buf[0:nl+1])
   268  		if e, ok := d.err.(CorruptInputError); ok {
   269  			d.err = CorruptInputError(int64(e) + d.off)
   270  		}
   271  		d.out = d.outbuf[0:nn]
   272  		d.nbuf = copy(d.buf[0:], d.buf[nl+1:d.nbuf])
   273  		d.off += int64(nl + 1)
   274  	}
   275  	panic("unreachable")
   276  }