aboutsummaryrefslogtreecommitdiff
path: root/src/pkg
diff options
context:
space:
mode:
Diffstat (limited to 'src/pkg')
-rw-r--r--src/pkg/archive/tar/common.go72
-rw-r--r--src/pkg/archive/tar/reader.go122
-rw-r--r--src/pkg/archive/tar/reader_test.go112
-rw-r--r--src/pkg/archive/tar/writer.go140
-rw-r--r--src/pkg/archive/tar/writer_test.go66
-rw-r--r--src/pkg/asn1/asn1.go454
-rw-r--r--src/pkg/asn1/asn1_test.go154
-rw-r--r--src/pkg/asn1/common.go72
-rw-r--r--src/pkg/asn1/marshal.go194
-rw-r--r--src/pkg/asn1/marshal_test.go34
-rw-r--r--src/pkg/big/arith.go250
-rw-r--r--src/pkg/big/arith_test.go148
-rw-r--r--src/pkg/big/int.go236
-rw-r--r--src/pkg/big/int_test.go242
-rw-r--r--src/pkg/big/nat.go352
-rw-r--r--src/pkg/big/nat_test.go100
-rw-r--r--src/pkg/bignum/arith.go72
-rw-r--r--src/pkg/bignum/bignum.go486
-rw-r--r--src/pkg/bignum/bignum_test.go594
-rw-r--r--src/pkg/bignum/integer.go150
-rw-r--r--src/pkg/bignum/nrdiv_test.go100
-rw-r--r--src/pkg/bignum/rational.go82
-rw-r--r--src/pkg/bufio/bufio.go294
-rw-r--r--src/pkg/bufio/bufio_test.go208
-rw-r--r--src/pkg/bytes/buffer.go120
-rw-r--r--src/pkg/bytes/buffer_test.go170
-rw-r--r--src/pkg/bytes/bytes.go200
-rw-r--r--src/pkg/bytes/bytes_test.go206
-rw-r--r--src/pkg/compress/flate/deflate.go304
-rw-r--r--src/pkg/compress/flate/deflate_test.go60
-rw-r--r--src/pkg/compress/flate/flate_test.go24
-rw-r--r--src/pkg/compress/flate/huffman_bit_writer.go376
-rw-r--r--src/pkg/compress/flate/huffman_code.go240
-rw-r--r--src/pkg/compress/flate/inflate.go340
-rw-r--r--src/pkg/compress/flate/token.go26
-rw-r--r--src/pkg/compress/flate/util.go14
-rw-r--r--src/pkg/compress/gzip/gunzip.go140
-rw-r--r--src/pkg/compress/gzip/gunzip_test.go54
-rw-r--r--src/pkg/compress/zlib/reader.go58
-rw-r--r--src/pkg/compress/zlib/reader_test.go34
-rw-r--r--src/pkg/compress/zlib/writer.go68
-rw-r--r--src/pkg/compress/zlib/writer_test.go86
-rw-r--r--src/pkg/container/heap/heap.go46
-rw-r--r--src/pkg/container/heap/heap_test.go96
-rw-r--r--src/pkg/container/list/list.go116
-rw-r--r--src/pkg/container/list/list_test.go128
-rw-r--r--src/pkg/container/ring/ring.go62
-rw-r--r--src/pkg/container/ring/ring_test.go166
-rw-r--r--src/pkg/container/vector/intvector.go34
-rw-r--r--src/pkg/container/vector/stringvector.go32
-rw-r--r--src/pkg/container/vector/vector.go110
-rw-r--r--src/pkg/container/vector/vector_test.go170
-rw-r--r--src/pkg/crypto/aes/aes_test.go132
-rw-r--r--src/pkg/crypto/aes/block.go134
-rw-r--r--src/pkg/crypto/aes/cipher.go24
-rw-r--r--src/pkg/crypto/aes/const.go2
-rw-r--r--src/pkg/crypto/block/cbc.go36
-rw-r--r--src/pkg/crypto/block/cbc_aes_test.go42
-rw-r--r--src/pkg/crypto/block/cfb.go38
-rw-r--r--src/pkg/crypto/block/cfb_aes_test.go44
-rw-r--r--src/pkg/crypto/block/cipher.go22
-rw-r--r--src/pkg/crypto/block/cmac.go54
-rw-r--r--src/pkg/crypto/block/cmac_aes_test.go32
-rw-r--r--src/pkg/crypto/block/ctr.go24
-rw-r--r--src/pkg/crypto/block/ctr_aes_test.go46
-rw-r--r--src/pkg/crypto/block/eax.go160
-rw-r--r--src/pkg/crypto/block/eax_aes_test.go46
-rw-r--r--src/pkg/crypto/block/ecb.go144
-rw-r--r--src/pkg/crypto/block/ecb_aes_test.go40
-rw-r--r--src/pkg/crypto/block/ecb_test.go96
-rw-r--r--src/pkg/crypto/block/ofb.go20
-rw-r--r--src/pkg/crypto/block/ofb_aes_test.go46
-rw-r--r--src/pkg/crypto/block/xor.go92
-rw-r--r--src/pkg/crypto/block/xor_test.go102
-rw-r--r--src/pkg/crypto/hmac/hmac.go58
-rw-r--r--src/pkg/crypto/hmac/hmac_test.go28
-rw-r--r--src/pkg/crypto/md4/md4.go98
-rw-r--r--src/pkg/crypto/md4/md4_test.go24
-rw-r--r--src/pkg/crypto/md4/md4block.go76
-rw-r--r--src/pkg/crypto/md5/md5.go98
-rw-r--r--src/pkg/crypto/md5/md5_test.go24
-rw-r--r--src/pkg/crypto/md5/md5block.go104
-rw-r--r--src/pkg/crypto/rc4/rc4.go30
-rw-r--r--src/pkg/crypto/rc4/rc4_test.go20
-rw-r--r--src/pkg/crypto/rsa/pkcs1v15.go152
-rw-r--r--src/pkg/crypto/rsa/pkcs1v15_test.go104
-rw-r--r--src/pkg/crypto/rsa/rsa.go298
-rw-r--r--src/pkg/crypto/rsa/rsa_test.go68
-rw-r--r--src/pkg/crypto/sha1/sha1.go102
-rw-r--r--src/pkg/crypto/sha1/sha1_test.go24
-rw-r--r--src/pkg/crypto/sha1/sha1block.go82
-rw-r--r--src/pkg/crypto/sha256/sha256.go114
-rw-r--r--src/pkg/crypto/sha256/sha256_test.go24
-rw-r--r--src/pkg/crypto/sha256/sha256block.go62
-rw-r--r--src/pkg/crypto/subtle/constant_time.go36
-rw-r--r--src/pkg/crypto/subtle/constant_time_test.go30
-rw-r--r--src/pkg/crypto/tls/alert.go52
-rw-r--r--src/pkg/crypto/tls/ca_set.go24
-rw-r--r--src/pkg/crypto/tls/common.go86
-rw-r--r--src/pkg/crypto/tls/handshake_client.go220
-rw-r--r--src/pkg/crypto/tls/handshake_messages.go280
-rw-r--r--src/pkg/crypto/tls/handshake_messages_test.go108
-rw-r--r--src/pkg/crypto/tls/handshake_server.go212
-rw-r--r--src/pkg/crypto/tls/handshake_server_test.go162
-rw-r--r--src/pkg/crypto/tls/prf.go142
-rw-r--r--src/pkg/crypto/tls/prf_test.go44
-rw-r--r--src/pkg/crypto/tls/record_process.go214
-rw-r--r--src/pkg/crypto/tls/record_process_test.go138
-rw-r--r--src/pkg/crypto/tls/record_read.go20
-rw-r--r--src/pkg/crypto/tls/record_read_test.go38
-rw-r--r--src/pkg/crypto/tls/record_write.go132
-rw-r--r--src/pkg/crypto/tls/tls.go140
-rw-r--r--src/pkg/crypto/x509/x509.go340
-rw-r--r--src/pkg/crypto/x509/x509_test.go40
-rw-r--r--src/pkg/crypto/xtea/block.go46
-rw-r--r--src/pkg/crypto/xtea/cipher.go40
-rw-r--r--src/pkg/crypto/xtea/xtea_test.go116
117 files changed, 6920 insertions, 6920 deletions
diff --git a/src/pkg/archive/tar/common.go b/src/pkg/archive/tar/common.go
index 792a3050b7..4d399e5fe9 100644
--- a/src/pkg/archive/tar/common.go
+++ b/src/pkg/archive/tar/common.go
@@ -12,39 +12,39 @@
package tar
const (
- blockSize = 512;
+ blockSize = 512
// Types
- TypeReg = '0';
- TypeRegA = '\x00';
- TypeLink = '1';
- TypeSymlink = '2';
- TypeChar = '3';
- TypeBlock = '4';
- TypeDir = '5';
- TypeFifo = '6';
- TypeCont = '7';
- TypeXHeader = 'x';
- TypeXGlobalHeader = 'g';
+ TypeReg = '0'
+ TypeRegA = '\x00'
+ TypeLink = '1'
+ TypeSymlink = '2'
+ TypeChar = '3'
+ TypeBlock = '4'
+ TypeDir = '5'
+ TypeFifo = '6'
+ TypeCont = '7'
+ TypeXHeader = 'x'
+ TypeXGlobalHeader = 'g'
)
// A Header represents a single header in a tar archive.
// Some fields may not be populated.
type Header struct {
- Name string;
- Mode int64;
- Uid int64;
- Gid int64;
- Size int64;
- Mtime int64;
- Typeflag byte;
- Linkname string;
- Uname string;
- Gname string;
- Devmajor int64;
- Devminor int64;
- Atime int64;
- Ctime int64;
+ Name string
+ Mode int64
+ Uid int64
+ Gid int64
+ Size int64
+ Mtime int64
+ Typeflag byte
+ Linkname string
+ Uname string
+ Gname string
+ Devmajor int64
+ Devminor int64
+ Atime int64
+ Ctime int64
}
var zeroBlock = make([]byte, blockSize)
@@ -55,21 +55,21 @@ func checksum(header []byte) (unsigned int64, signed int64) {
for i := 0; i < len(header); i++ {
if i == 148 {
// The chksum field (header[148:156]) is special: it should be treated as space bytes.
- unsigned += ' ' * 8;
- signed += ' ' * 8;
- i += 7;
- continue;
+ unsigned += ' ' * 8
+ signed += ' ' * 8
+ i += 7
+ continue
}
- unsigned += int64(header[i]);
- signed += int64(int8(header[i]));
+ unsigned += int64(header[i])
+ signed += int64(int8(header[i]))
}
- return;
+ return
}
type slicer []byte
func (sp *slicer) next(n int) (b []byte) {
- s := *sp;
- b, *sp = s[0:n], s[n:];
- return;
+ s := *sp
+ b, *sp = s[0:n], s[n:]
+ return
}
diff --git a/src/pkg/archive/tar/reader.go b/src/pkg/archive/tar/reader.go
index 50cda624bd..9d598361a4 100644
--- a/src/pkg/archive/tar/reader.go
+++ b/src/pkg/archive/tar/reader.go
@@ -8,14 +8,14 @@ package tar
// - pax extensions
import (
- "bytes";
- "io";
- "os";
- "strconv";
+ "bytes"
+ "io"
+ "os"
+ "strconv"
)
var (
- HeaderError os.Error = os.ErrorString("invalid tar header");
+ HeaderError os.Error = os.ErrorString("invalid tar header")
)
// A Reader provides sequential access to the contents of a tar archive.
@@ -37,35 +37,35 @@ var (
// io.Copy(data, tr);
// }
type Reader struct {
- r io.Reader;
- err os.Error;
- nb int64; // number of unread bytes for current file entry
- pad int64; // amount of padding (ignored) after current file entry
+ r io.Reader
+ err os.Error
+ nb int64 // number of unread bytes for current file entry
+ pad int64 // amount of padding (ignored) after current file entry
}
// NewReader creates a new Reader reading from r.
-func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
+func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
// Next advances to the next entry in the tar archive.
func (tr *Reader) Next() (*Header, os.Error) {
- var hdr *Header;
+ var hdr *Header
if tr.err == nil {
tr.skipUnread()
}
if tr.err == nil {
hdr = tr.readHeader()
}
- return hdr, tr.err;
+ return hdr, tr.err
}
// Parse bytes as a NUL-terminated C-style string.
// If a NUL byte is not found then the whole slice is returned as a string.
func cString(b []byte) string {
- n := 0;
+ n := 0
for n < len(b) && b[n] != 0 {
n++
}
- return string(b[0:n]);
+ return string(b[0:n])
}
func (tr *Reader) octal(b []byte) int64 {
@@ -77,11 +77,11 @@ func (tr *Reader) octal(b []byte) int64 {
for len(b) > 0 && (b[len(b)-1] == ' ' || b[len(b)-1] == '\x00') {
b = b[0 : len(b)-1]
}
- x, err := strconv.Btoui64(cString(b), 8);
+ x, err := strconv.Btoui64(cString(b), 8)
if err != nil {
tr.err = err
}
- return int64(x);
+ return int64(x)
}
type ignoreWriter struct{}
@@ -92,14 +92,14 @@ func (ignoreWriter) Write(b []byte) (n int, err os.Error) {
// Skip any unread bytes in the existing file entry, as well as any alignment padding.
func (tr *Reader) skipUnread() {
- nr := tr.nb + tr.pad; // number of bytes to skip
- tr.nb, tr.pad = 0, 0;
+ nr := tr.nb + tr.pad // number of bytes to skip
+ tr.nb, tr.pad = 0, 0
if sr, ok := tr.r.(io.Seeker); ok {
if _, err := sr.Seek(nr, 1); err == nil {
return
}
}
- _, tr.err = io.Copyn(ignoreWriter{}, tr.r, nr);
+ _, tr.err = io.Copyn(ignoreWriter{}, tr.r, nr)
}
func (tr *Reader) verifyChecksum(header []byte) bool {
@@ -107,13 +107,13 @@ func (tr *Reader) verifyChecksum(header []byte) bool {
return false
}
- given := tr.octal(header[148:156]);
- unsigned, signed := checksum(header);
- return given == unsigned || given == signed;
+ given := tr.octal(header[148:156])
+ unsigned, signed := checksum(header)
+ return given == unsigned || given == signed
}
func (tr *Reader) readHeader() *Header {
- header := make([]byte, blockSize);
+ header := make([]byte, blockSize)
if _, tr.err = io.ReadFull(tr.r, header); tr.err != nil {
return nil
}
@@ -126,64 +126,64 @@ func (tr *Reader) readHeader() *Header {
if bytes.Equal(header, zeroBlock[0:blockSize]) {
tr.err = os.EOF
} else {
- tr.err = HeaderError // zero block and then non-zero block
+ tr.err = HeaderError // zero block and then non-zero block
}
- return nil;
+ return nil
}
if !tr.verifyChecksum(header) {
- tr.err = HeaderError;
- return nil;
+ tr.err = HeaderError
+ return nil
}
// Unpack
- hdr := new(Header);
- s := slicer(header);
+ hdr := new(Header)
+ s := slicer(header)
- hdr.Name = cString(s.next(100));
- hdr.Mode = tr.octal(s.next(8));
- hdr.Uid = tr.octal(s.next(8));
- hdr.Gid = tr.octal(s.next(8));
- hdr.Size = tr.octal(s.next(12));
- hdr.Mtime = tr.octal(s.next(12));
- s.next(8); // chksum
- hdr.Typeflag = s.next(1)[0];
- hdr.Linkname = cString(s.next(100));
+ hdr.Name = cString(s.next(100))
+ hdr.Mode = tr.octal(s.next(8))
+ hdr.Uid = tr.octal(s.next(8))
+ hdr.Gid = tr.octal(s.next(8))
+ hdr.Size = tr.octal(s.next(12))
+ hdr.Mtime = tr.octal(s.next(12))
+ s.next(8) // chksum
+ hdr.Typeflag = s.next(1)[0]
+ hdr.Linkname = cString(s.next(100))
// The remainder of the header depends on the value of magic.
// The original (v7) version of tar had no explicit magic field,
// so its magic bytes, like the rest of the block, are NULs.
- magic := string(s.next(8)); // contains version field as well.
- var format string;
+ magic := string(s.next(8)) // contains version field as well.
+ var format string
switch magic {
- case "ustar\x0000": // POSIX tar (1003.1-1988)
+ case "ustar\x0000": // POSIX tar (1003.1-1988)
if string(header[508:512]) == "tar\x00" {
format = "star"
} else {
format = "posix"
}
- case "ustar \x00": // old GNU tar
+ case "ustar \x00": // old GNU tar
format = "gnu"
}
switch format {
case "posix", "gnu", "star":
- hdr.Uname = cString(s.next(32));
- hdr.Gname = cString(s.next(32));
- devmajor := s.next(8);
- devminor := s.next(8);
+ hdr.Uname = cString(s.next(32))
+ hdr.Gname = cString(s.next(32))
+ devmajor := s.next(8)
+ devminor := s.next(8)
if hdr.Typeflag == TypeChar || hdr.Typeflag == TypeBlock {
- hdr.Devmajor = tr.octal(devmajor);
- hdr.Devminor = tr.octal(devminor);
+ hdr.Devmajor = tr.octal(devmajor)
+ hdr.Devminor = tr.octal(devminor)
}
- var prefix string;
+ var prefix string
switch format {
case "posix", "gnu":
prefix = cString(s.next(155))
case "star":
- prefix = cString(s.next(131));
- hdr.Atime = tr.octal(s.next(12));
- hdr.Ctime = tr.octal(s.next(12));
+ prefix = cString(s.next(131))
+ hdr.Atime = tr.octal(s.next(12))
+ hdr.Ctime = tr.octal(s.next(12))
}
if len(prefix) > 0 {
hdr.Name = prefix + "/" + hdr.Name
@@ -191,16 +191,16 @@ func (tr *Reader) readHeader() *Header {
}
if tr.err != nil {
- tr.err = HeaderError;
- return nil;
+ tr.err = HeaderError
+ return nil
}
// Maximum value of hdr.Size is 64 GB (12 octal digits),
// so there's no risk of int64 overflowing.
- tr.nb = int64(hdr.Size);
- tr.pad = -tr.nb & (blockSize - 1); // blockSize is a power of two
+ tr.nb = int64(hdr.Size)
+ tr.pad = -tr.nb & (blockSize - 1) // blockSize is a power of two
- return hdr;
+ return hdr
}
// Read reads from the current entry in the tar archive.
@@ -215,12 +215,12 @@ func (tr *Reader) Read(b []byte) (n int, err os.Error) {
if int64(len(b)) > tr.nb {
b = b[0:tr.nb]
}
- n, err = tr.r.Read(b);
- tr.nb -= int64(n);
+ n, err = tr.r.Read(b)
+ tr.nb -= int64(n)
if err == os.EOF && tr.nb > 0 {
err = io.ErrUnexpectedEOF
}
- tr.err = err;
- return;
+ tr.err = err
+ return
}
diff --git a/src/pkg/archive/tar/reader_test.go b/src/pkg/archive/tar/reader_test.go
index f5a77dd385..719e3d87ec 100644
--- a/src/pkg/archive/tar/reader_test.go
+++ b/src/pkg/archive/tar/reader_test.go
@@ -5,20 +5,20 @@
package tar
import (
- "bytes";
- "crypto/md5";
- "fmt";
- "io";
- "os";
- "reflect";
- "strings";
- "testing";
+ "bytes"
+ "crypto/md5"
+ "fmt"
+ "io"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
)
type untarTest struct {
- file string;
- headers []*Header;
- cksums []string;
+ file string
+ headers []*Header
+ cksums []string
}
var gnuTarTest = &untarTest{
@@ -114,50 +114,50 @@ var untarTests = []*untarTest{
func TestReader(t *testing.T) {
testLoop:
for i, test := range untarTests {
- f, err := os.Open(test.file, os.O_RDONLY, 0444);
+ f, err := os.Open(test.file, os.O_RDONLY, 0444)
if err != nil {
- t.Errorf("test %d: Unexpected error: %v", i, err);
- continue;
+ t.Errorf("test %d: Unexpected error: %v", i, err)
+ continue
}
- tr := NewReader(f);
+ tr := NewReader(f)
for j, header := range test.headers {
- hdr, err := tr.Next();
+ hdr, err := tr.Next()
if err != nil || hdr == nil {
- t.Errorf("test %d, entry %d: Didn't get entry: %v", i, j, err);
- f.Close();
- continue testLoop;
+ t.Errorf("test %d, entry %d: Didn't get entry: %v", i, j, err)
+ f.Close()
+ continue testLoop
}
if !reflect.DeepEqual(hdr, header) {
t.Errorf("test %d, entry %d: Incorrect header:\nhave %+v\nwant %+v",
i, j, *hdr, *header)
}
}
- hdr, err := tr.Next();
+ hdr, err := tr.Next()
if err == os.EOF {
break
}
if hdr != nil || err != nil {
t.Errorf("test %d: Unexpected entry or error: hdr=%v err=%v", i, err)
}
- f.Close();
+ f.Close()
}
}
func TestPartialRead(t *testing.T) {
- f, err := os.Open("testdata/gnu.tar", os.O_RDONLY, 0444);
+ f, err := os.Open("testdata/gnu.tar", os.O_RDONLY, 0444)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
- defer f.Close();
+ defer f.Close()
- tr := NewReader(f);
+ tr := NewReader(f)
// Read the first four bytes; Next() should skip the last byte.
- hdr, err := tr.Next();
+ hdr, err := tr.Next()
if err != nil || hdr == nil {
t.Fatalf("Didn't get first file: %v", err)
}
- buf := make([]byte, 4);
+ buf := make([]byte, 4)
if _, err := io.ReadFull(tr, buf); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -166,11 +166,11 @@ func TestPartialRead(t *testing.T) {
}
// Second file
- hdr, err = tr.Next();
+ hdr, err = tr.Next()
if err != nil || hdr == nil {
t.Fatalf("Didn't get second file: %v", err)
}
- buf = make([]byte, 6);
+ buf = make([]byte, 6)
if _, err := io.ReadFull(tr, buf); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@@ -181,22 +181,22 @@ func TestPartialRead(t *testing.T) {
func TestIncrementalRead(t *testing.T) {
- test := gnuTarTest;
- f, err := os.Open(test.file, os.O_RDONLY, 0444);
+ test := gnuTarTest
+ f, err := os.Open(test.file, os.O_RDONLY, 0444)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
- defer f.Close();
+ defer f.Close()
- tr := NewReader(f);
+ tr := NewReader(f)
- headers := test.headers;
- cksums := test.cksums;
- nread := 0;
+ headers := test.headers
+ cksums := test.cksums
+ nread := 0
// loop over all files
for ; ; nread++ {
- hdr, err := tr.Next();
+ hdr, err := tr.Next()
if hdr == nil || err == os.EOF {
break
}
@@ -209,22 +209,22 @@ func TestIncrementalRead(t *testing.T) {
// read file contents in little chunks EOF,
// checksumming all the way
- h := md5.New();
- rdbuf := make([]uint8, 8);
+ h := md5.New()
+ rdbuf := make([]uint8, 8)
for {
- nr, err := tr.Read(rdbuf);
+ nr, err := tr.Read(rdbuf)
if err == os.EOF {
break
}
if err != nil {
- t.Errorf("Read: unexpected error %v\n", err);
- break;
+ t.Errorf("Read: unexpected error %v\n", err)
+ break
}
- h.Write(rdbuf[0:nr]);
+ h.Write(rdbuf[0:nr])
}
// verify checksum
- have := fmt.Sprintf("%x", h.Sum());
- want := cksums[nread];
+ have := fmt.Sprintf("%x", h.Sum())
+ want := cksums[nread]
if want != have {
t.Errorf("Bad checksum on file %s:\nhave %+v\nwant %+v", hdr.Name, have, want)
}
@@ -235,35 +235,35 @@ func TestIncrementalRead(t *testing.T) {
}
func TestNonSeekable(t *testing.T) {
- test := gnuTarTest;
- f, err := os.Open(test.file, os.O_RDONLY, 0444);
+ test := gnuTarTest
+ f, err := os.Open(test.file, os.O_RDONLY, 0444)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
- defer f.Close();
+ defer f.Close()
// pipe the data in
- r, w, err := os.Pipe();
+ r, w, err := os.Pipe()
if err != nil {
t.Fatalf("Unexpected error %s", err)
}
go func() {
- rdbuf := make([]uint8, 1<<16);
+ rdbuf := make([]uint8, 1<<16)
for {
- nr, err := f.Read(rdbuf);
- w.Write(rdbuf[0:nr]);
+ nr, err := f.Read(rdbuf)
+ w.Write(rdbuf[0:nr])
if err == os.EOF {
break
}
}
- w.Close();
- }();
+ w.Close()
+ }()
- tr := NewReader(r);
- nread := 0;
+ tr := NewReader(r)
+ nread := 0
for ; ; nread++ {
- hdr, err := tr.Next();
+ hdr, err := tr.Next()
if hdr == nil || err == os.EOF {
break
}
diff --git a/src/pkg/archive/tar/writer.go b/src/pkg/archive/tar/writer.go
index f3ce84afa4..88f9c72bd1 100644
--- a/src/pkg/archive/tar/writer.go
+++ b/src/pkg/archive/tar/writer.go
@@ -8,16 +8,16 @@ package tar
// - catch more errors (no first header, write after close, etc.)
import (
- "io";
- "os";
- "strconv";
- "strings";
+ "io"
+ "os"
+ "strconv"
+ "strings"
)
var (
- ErrWriteTooLong = os.NewError("write too long");
- ErrFieldTooLong = os.NewError("header field too long");
- ErrWriteAfterClose = os.NewError("write after close");
+ ErrWriteTooLong = os.NewError("write too long")
+ ErrFieldTooLong = os.NewError("header field too long")
+ ErrWriteAfterClose = os.NewError("write after close")
)
// A Writer provides sequential writing of a tar archive in POSIX.1 format.
@@ -36,32 +36,32 @@ var (
// io.Copy(tw, data);
// tw.Close();
type Writer struct {
- w io.Writer;
- err os.Error;
- nb int64; // number of unwritten bytes for current file entry
- pad int64; // amount of padding to write after current file entry
- closed bool;
- usedBinary bool; // whether the binary numeric field extension was used
+ w io.Writer
+ err os.Error
+ nb int64 // number of unwritten bytes for current file entry
+ pad int64 // amount of padding to write after current file entry
+ closed bool
+ usedBinary bool // whether the binary numeric field extension was used
}
// NewWriter creates a new Writer writing to w.
-func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
+func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
// Flush finishes writing the current file (optional).
func (tw *Writer) Flush() os.Error {
- n := tw.nb + tw.pad;
+ n := tw.nb + tw.pad
for n > 0 && tw.err == nil {
- nr := n;
+ nr := n
if nr > blockSize {
nr = blockSize
}
- var nw int;
- nw, tw.err = tw.w.Write(zeroBlock[0:nr]);
- n -= int64(nw);
+ var nw int
+ nw, tw.err = tw.w.Write(zeroBlock[0:nr])
+ n -= int64(nw)
}
- tw.nb = 0;
- tw.pad = 0;
- return tw.err;
+ tw.nb = 0
+ tw.pad = 0
+ return tw.err
}
// Write s into b, terminating it with a NUL if there is room.
@@ -70,7 +70,7 @@ func (tw *Writer) cString(b []byte, s string) {
if tw.err == nil {
tw.err = ErrFieldTooLong
}
- return;
+ return
}
for i, ch := range strings.Bytes(s) {
b[i] = ch
@@ -82,29 +82,29 @@ func (tw *Writer) cString(b []byte, s string) {
// Encode x as an octal ASCII string and write it into b with leading zeros.
func (tw *Writer) octal(b []byte, x int64) {
- s := strconv.Itob64(x, 8);
+ s := strconv.Itob64(x, 8)
// leading zeros, but leave room for a NUL.
for len(s)+1 < len(b) {
s = "0" + s
}
- tw.cString(b, s);
+ tw.cString(b, s)
}
// Write x into b, either as octal or as binary (GNUtar/star extension).
func (tw *Writer) numeric(b []byte, x int64) {
// Try octal first.
- s := strconv.Itob64(x, 8);
+ s := strconv.Itob64(x, 8)
if len(s) < len(b) {
- tw.octal(b, x);
- return;
+ tw.octal(b, x)
+ return
}
// Too big: use binary (big-endian).
- tw.usedBinary = true;
+ tw.usedBinary = true
for i := len(b) - 1; x > 0 && i >= 0; i-- {
- b[i] = byte(x);
- x >>= 8;
+ b[i] = byte(x)
+ x >>= 8
}
- b[0] |= 0x80; // highest bit indicates binary format
+ b[0] |= 0x80 // highest bit indicates binary format
}
// WriteHeader writes hdr and prepares to accept the file's contents.
@@ -121,28 +121,28 @@ func (tw *Writer) WriteHeader(hdr *Header) os.Error {
return tw.err
}
- tw.nb = int64(hdr.Size);
- tw.pad = -tw.nb & (blockSize - 1); // blockSize is a power of two
+ tw.nb = int64(hdr.Size)
+ tw.pad = -tw.nb & (blockSize - 1) // blockSize is a power of two
- header := make([]byte, blockSize);
- s := slicer(header);
+ header := make([]byte, blockSize)
+ s := slicer(header)
// TODO(dsymonds): handle names longer than 100 chars
- copy(s.next(100), strings.Bytes(hdr.Name));
+ copy(s.next(100), strings.Bytes(hdr.Name))
- tw.octal(s.next(8), hdr.Mode); // 100:108
- tw.numeric(s.next(8), hdr.Uid); // 108:116
- tw.numeric(s.next(8), hdr.Gid); // 116:124
- tw.numeric(s.next(12), hdr.Size); // 124:136
- tw.numeric(s.next(12), hdr.Mtime); // 136:148
- s.next(8); // chksum (148:156)
- s.next(1)[0] = hdr.Typeflag; // 156:157
- s.next(100); // linkname (157:257)
- copy(s.next(8), strings.Bytes("ustar\x0000")); // 257:265
- tw.cString(s.next(32), hdr.Uname); // 265:297
- tw.cString(s.next(32), hdr.Gname); // 297:329
- tw.numeric(s.next(8), hdr.Devmajor); // 329:337
- tw.numeric(s.next(8), hdr.Devminor); // 337:345
+ tw.octal(s.next(8), hdr.Mode) // 100:108
+ tw.numeric(s.next(8), hdr.Uid) // 108:116
+ tw.numeric(s.next(8), hdr.Gid) // 116:124
+ tw.numeric(s.next(12), hdr.Size) // 124:136
+ tw.numeric(s.next(12), hdr.Mtime) // 136:148
+ s.next(8) // chksum (148:156)
+ s.next(1)[0] = hdr.Typeflag // 156:157
+ s.next(100) // linkname (157:257)
+ copy(s.next(8), strings.Bytes("ustar\x0000")) // 257:265
+ tw.cString(s.next(32), hdr.Uname) // 265:297
+ tw.cString(s.next(32), hdr.Gname) // 297:329
+ tw.numeric(s.next(8), hdr.Devmajor) // 329:337
+ tw.numeric(s.next(8), hdr.Devminor) // 337:345
// Use the GNU magic instead of POSIX magic if we used any GNU extensions.
if tw.usedBinary {
@@ -151,18 +151,18 @@ func (tw *Writer) WriteHeader(hdr *Header) os.Error {
// The chksum field is terminated by a NUL and a space.
// This is different from the other octal fields.
- chksum, _ := checksum(header);
- tw.octal(header[148:155], chksum);
- header[155] = ' ';
+ chksum, _ := checksum(header)
+ tw.octal(header[148:155], chksum)
+ header[155] = ' '
if tw.err != nil {
// problem with header; probably integer too big for a field.
return tw.err
}
- _, tw.err = tw.w.Write(header);
+ _, tw.err = tw.w.Write(header)
- return tw.err;
+ return tw.err
}
// Write writes to the current entry in the tar archive.
@@ -170,22 +170,22 @@ func (tw *Writer) WriteHeader(hdr *Header) os.Error {
// hdr.Size bytes are written after WriteHeader.
func (tw *Writer) Write(b []byte) (n int, err os.Error) {
if tw.closed {
- err = ErrWriteTooLong;
- return;
+ err = ErrWriteTooLong
+ return
}
- overwrite := false;
+ overwrite := false
if int64(len(b)) > tw.nb {
- b = b[0:tw.nb];
- overwrite = true;
+ b = b[0:tw.nb]
+ overwrite = true
}
- n, err = tw.w.Write(b);
- tw.nb -= int64(n);
+ n, err = tw.w.Write(b)
+ tw.nb -= int64(n)
if err == nil && overwrite {
- err = ErrWriteTooLong;
- return;
+ err = ErrWriteTooLong
+ return
}
- tw.err = err;
- return;
+ tw.err = err
+ return
}
// Close closes the tar archive, flushing any unwritten
@@ -194,15 +194,15 @@ func (tw *Writer) Close() os.Error {
if tw.err != nil || tw.closed {
return tw.err
}
- tw.Flush();
- tw.closed = true;
+ tw.Flush()
+ tw.closed = true
// trailer: two zero blocks
for i := 0; i < 2; i++ {
- _, tw.err = tw.w.Write(zeroBlock);
+ _, tw.err = tw.w.Write(zeroBlock)
if tw.err != nil {
break
}
}
- return tw.err;
+ return tw.err
}
diff --git a/src/pkg/archive/tar/writer_test.go b/src/pkg/archive/tar/writer_test.go
index 0df0144b1c..f060efcbed 100644
--- a/src/pkg/archive/tar/writer_test.go
+++ b/src/pkg/archive/tar/writer_test.go
@@ -5,22 +5,22 @@
package tar
import (
- "bytes";
- "fmt";
- "io";
- "io/ioutil";
- "testing";
- "testing/iotest";
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "testing"
+ "testing/iotest"
)
type writerTestEntry struct {
- header *Header;
- contents string;
+ header *Header
+ contents string
}
type writerTest struct {
- file string; // filename of expected output
- entries []*writerTestEntry;
+ file string // filename of expected output
+ entries []*writerTestEntry
}
var writerTests = []*writerTest{
@@ -83,8 +83,8 @@ var writerTests = []*writerTest{
// Render byte array in a two-character hexadecimal string, spaced for easy visual inspection.
func bytestr(offset int, b []byte) string {
- const rowLen = 32;
- s := fmt.Sprintf("%04x ", offset);
+ const rowLen = 32
+ s := fmt.Sprintf("%04x ", offset)
for _, ch := range b {
switch {
case '0' <= ch && ch <= '9', 'A' <= ch && ch <= 'Z', 'a' <= ch && ch <= 'z':
@@ -93,59 +93,59 @@ func bytestr(offset int, b []byte) string {
s += fmt.Sprintf(" %02x", ch)
}
}
- return s;
+ return s
}
// Render a pseudo-diff between two blocks of bytes.
func bytediff(a []byte, b []byte) string {
- const rowLen = 32;
- s := fmt.Sprintf("(%d bytes vs. %d bytes)\n", len(a), len(b));
+ const rowLen = 32
+ s := fmt.Sprintf("(%d bytes vs. %d bytes)\n", len(a), len(b))
for offset := 0; len(a)+len(b) > 0; offset += rowLen {
- na, nb := rowLen, rowLen;
+ na, nb := rowLen, rowLen
if na > len(a) {
na = len(a)
}
if nb > len(b) {
nb = len(b)
}
- sa := bytestr(offset, a[0:na]);
- sb := bytestr(offset, b[0:nb]);
+ sa := bytestr(offset, a[0:na])
+ sb := bytestr(offset, b[0:nb])
if sa != sb {
s += fmt.Sprintf("-%v\n+%v\n", sa, sb)
}
- a = a[na:];
- b = b[nb:];
+ a = a[na:]
+ b = b[nb:]
}
- return s;
+ return s
}
func TestWriter(t *testing.T) {
testLoop:
for i, test := range writerTests {
- expected, err := ioutil.ReadFile(test.file);
+ expected, err := ioutil.ReadFile(test.file)
if err != nil {
- t.Errorf("test %d: Unexpected error: %v", i, err);
- continue;
+ t.Errorf("test %d: Unexpected error: %v", i, err)
+ continue
}
- buf := new(bytes.Buffer);
- tw := NewWriter(iotest.TruncateWriter(buf, 4<<10)); // only catch the first 4 KB
+ buf := new(bytes.Buffer)
+ tw := NewWriter(iotest.TruncateWriter(buf, 4<<10)) // only catch the first 4 KB
for j, entry := range test.entries {
if err := tw.WriteHeader(entry.header); err != nil {
- t.Errorf("test %d, entry %d: Failed writing header: %v", i, j, err);
- continue testLoop;
+ t.Errorf("test %d, entry %d: Failed writing header: %v", i, j, err)
+ continue testLoop
}
if _, err := io.WriteString(tw, entry.contents); err != nil {
- t.Errorf("test %d, entry %d: Failed writing contents: %v", i, j, err);
- continue testLoop;
+ t.Errorf("test %d, entry %d: Failed writing contents: %v", i, j, err)
+ continue testLoop
}
}
if err := tw.Close(); err != nil {
- t.Errorf("test %d: Failed closing archive: %v", err);
- continue testLoop;
+ t.Errorf("test %d: Failed closing archive: %v", err)
+ continue testLoop
}
- actual := buf.Bytes();
+ actual := buf.Bytes()
if !bytes.Equal(expected, actual) {
t.Errorf("test %d: Incorrect result: (-=expected, +=actual)\n%v",
i, bytediff(expected, actual))
diff --git a/src/pkg/asn1/asn1.go b/src/pkg/asn1/asn1.go
index 4a1ef7f5e9..a422f28ad0 100644
--- a/src/pkg/asn1/asn1.go
+++ b/src/pkg/asn1/asn1.go
@@ -20,26 +20,26 @@ package asn1
// everything by any means.
import (
- "fmt";
- "os";
- "reflect";
- "time";
+ "fmt"
+ "os"
+ "reflect"
+ "time"
)
// A StructuralError suggests that the ASN.1 data is valid, but the Go type
// which is receiving it doesn't match.
type StructuralError struct {
- Msg string;
+ Msg string
}
-func (e StructuralError) String() string { return "ASN.1 structure error: " + e.Msg }
+func (e StructuralError) String() string { return "ASN.1 structure error: " + e.Msg }
// A SyntaxError suggests that the ASN.1 data is invalid.
type SyntaxError struct {
- Msg string;
+ Msg string
}
-func (e SyntaxError) String() string { return "ASN.1 syntax error: " + e.Msg }
+func (e SyntaxError) String() string { return "ASN.1 syntax error: " + e.Msg }
// We start by dealing with each of the primitive types in turn.
@@ -47,11 +47,11 @@ func (e SyntaxError) String() string { return "ASN.1 syntax error: " + e.Msg }
func parseBool(bytes []byte) (ret bool, err os.Error) {
if len(bytes) != 1 {
- err = SyntaxError{"invalid boolean"};
- return;
+ err = SyntaxError{"invalid boolean"}
+ return
}
- return bytes[0] != 0, nil;
+ return bytes[0] != 0, nil
}
// INTEGER
@@ -61,31 +61,31 @@ func parseBool(bytes []byte) (ret bool, err os.Error) {
func parseInt64(bytes []byte) (ret int64, err os.Error) {
if len(bytes) > 8 {
// We'll overflow an int64 in this case.
- err = StructuralError{"integer too large"};
- return;
+ err = StructuralError{"integer too large"}
+ return
}
for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
- ret <<= 8;
- ret |= int64(bytes[bytesRead]);
+ ret <<= 8
+ ret |= int64(bytes[bytesRead])
}
// Shift up and down in order to sign extend the result.
- ret <<= 64 - uint8(len(bytes))*8;
- ret >>= 64 - uint8(len(bytes))*8;
- return;
+ ret <<= 64 - uint8(len(bytes))*8
+ ret >>= 64 - uint8(len(bytes))*8
+ return
}
// parseInt treats the given bytes as a big-endian, signed integer and returns
// the result.
func parseInt(bytes []byte) (int, os.Error) {
- ret64, err := parseInt64(bytes);
+ ret64, err := parseInt64(bytes)
if err != nil {
return 0, err
}
if ret64 != int64(int(ret64)) {
return 0, StructuralError{"integer too large"}
}
- return int(ret64), nil;
+ return int(ret64), nil
}
// BIT STRING
@@ -94,8 +94,8 @@ func parseInt(bytes []byte) (int, os.Error) {
// bit string is padded up to the nearest byte in memory and the number of
// valid bits is recorded. Padding bits will be zero.
type BitString struct {
- Bytes []byte; // bits packed into bytes.
- BitLength int; // length in bits.
+ Bytes []byte // bits packed into bytes.
+ BitLength int // length in bits.
}
// At returns the bit at the given index. If the index is out of range it
@@ -104,45 +104,45 @@ func (b BitString) At(i int) int {
if i < 0 || i >= b.BitLength {
return 0
}
- x := i / 8;
- y := 7 - uint(i%8);
- return int(b.Bytes[x]>>y) & 1;
+ x := i / 8
+ y := 7 - uint(i%8)
+ return int(b.Bytes[x]>>y) & 1
}
// RightAlign returns a slice where the padding bits are at the beginning. The
// slice may share memory with the BitString.
func (b BitString) RightAlign() []byte {
- shift := uint(8 - (b.BitLength % 8));
+ shift := uint(8 - (b.BitLength % 8))
if shift == 8 || len(b.Bytes) == 0 {
return b.Bytes
}
- a := make([]byte, len(b.Bytes));
- a[0] = b.Bytes[0] >> shift;
+ a := make([]byte, len(b.Bytes))
+ a[0] = b.Bytes[0] >> shift
for i := 1; i < len(b.Bytes); i++ {
- a[i] = b.Bytes[i-1] << (8 - shift);
- a[i] |= b.Bytes[i] >> shift;
+ a[i] = b.Bytes[i-1] << (8 - shift)
+ a[i] |= b.Bytes[i] >> shift
}
- return a;
+ return a
}
// parseBitString parses an ASN.1 bit string from the given byte array and returns it.
func parseBitString(bytes []byte) (ret BitString, err os.Error) {
if len(bytes) == 0 {
- err = SyntaxError{"zero length BIT STRING"};
- return;
+ err = SyntaxError{"zero length BIT STRING"}
+ return
}
- paddingBits := int(bytes[0]);
+ paddingBits := int(bytes[0])
if paddingBits > 7 ||
len(bytes) == 1 && paddingBits > 0 ||
bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 {
- err = SyntaxError{"invalid padding bits in BIT STRING"};
- return;
+ err = SyntaxError{"invalid padding bits in BIT STRING"}
+ return
}
- ret.BitLength = (len(bytes)-1)*8 - paddingBits;
- ret.Bytes = bytes[1:];
- return;
+ ret.BitLength = (len(bytes)-1)*8 - paddingBits
+ ret.Bytes = bytes[1:]
+ return
}
// OBJECT IDENTIFIER
@@ -155,54 +155,54 @@ type ObjectIdentifier []int
// that are assigned in a hierarachy.
func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) {
if len(bytes) == 0 {
- err = SyntaxError{"zero length OBJECT IDENTIFIER"};
- return;
+ err = SyntaxError{"zero length OBJECT IDENTIFIER"}
+ return
}
// In the worst case, we get two elements from the first byte (which is
// encoded differently) and then every varint is a single byte long.
- s = make([]int, len(bytes)+1);
+ s = make([]int, len(bytes)+1)
// The first byte is 40*value1 + value2:
- s[0] = int(bytes[0]) / 40;
- s[1] = int(bytes[0]) % 40;
- i := 2;
+ s[0] = int(bytes[0]) / 40
+ s[1] = int(bytes[0]) % 40
+ i := 2
for offset := 1; offset < len(bytes); i++ {
- var v int;
- v, offset, err = parseBase128Int(bytes, offset);
+ var v int
+ v, offset, err = parseBase128Int(bytes, offset)
if err != nil {
return
}
- s[i] = v;
+ s[i] = v
}
- s = s[0:i];
- return;
+ s = s[0:i]
+ return
}
// parseBase128Int parses a base-128 encoded int from the given offset in the
// given byte array. It returns the value and the new offset.
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Error) {
- offset = initOffset;
+ offset = initOffset
for shifted := 0; offset < len(bytes); shifted++ {
if shifted > 4 {
- err = StructuralError{"base 128 integer too large"};
- return;
+ err = StructuralError{"base 128 integer too large"}
+ return
}
- ret <<= 7;
- b := bytes[offset];
- ret |= int(b & 0x7f);
- offset++;
+ ret <<= 7
+ b := bytes[offset]
+ ret |= int(b & 0x7f)
+ offset++
if b&0x80 == 0 {
return
}
}
- err = SyntaxError{"truncated base 128 integer"};
- return;
+ err = SyntaxError{"truncated base 128 integer"}
+ return
}
// UTCTime
-func isDigit(b byte) bool { return '0' <= b && b <= '9' }
+func isDigit(b byte) bool { return '0' <= b && b <= '9' }
// twoDigits returns the value of two, base 10 digits.
func twoDigits(bytes []byte, max int) (int, bool) {
@@ -211,11 +211,11 @@ func twoDigits(bytes []byte, max int) (int, bool) {
return 0, false
}
}
- value := (int(bytes[0])-'0')*10 + int(bytes[1]-'0');
+ value := (int(bytes[0])-'0')*10 + int(bytes[1]-'0')
if value > max {
return 0, false
}
- return value, true;
+ return value, true
}
// parseUTCTime parses the UTCTime from the given byte array and returns the
@@ -233,13 +233,13 @@ func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
// YYMMDDhhmmss+hhmm
// YYMMDDhhmmss-hhmm
if len(bytes) < 11 {
- err = SyntaxError{"UTCTime too short"};
- return;
+ err = SyntaxError{"UTCTime too short"}
+ return
}
- ret = new(time.Time);
+ ret = new(time.Time)
- var ok1, ok2, ok3, ok4, ok5 bool;
- year, ok1 := twoDigits(bytes[0:2], 99);
+ var ok1, ok2, ok3, ok4, ok5 bool
+ year, ok1 := twoDigits(bytes[0:2], 99)
// RFC 5280, section 5.1.2.4 says that years 2050 or later use another date
// scheme.
if year >= 50 {
@@ -247,24 +247,24 @@ func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
} else {
ret.Year = 2000 + int64(year)
}
- ret.Month, ok2 = twoDigits(bytes[2:4], 12);
- ret.Day, ok3 = twoDigits(bytes[4:6], 31);
- ret.Hour, ok4 = twoDigits(bytes[6:8], 23);
- ret.Minute, ok5 = twoDigits(bytes[8:10], 59);
+ ret.Month, ok2 = twoDigits(bytes[2:4], 12)
+ ret.Day, ok3 = twoDigits(bytes[4:6], 31)
+ ret.Hour, ok4 = twoDigits(bytes[6:8], 23)
+ ret.Minute, ok5 = twoDigits(bytes[8:10], 59)
if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 {
goto Error
}
- bytes = bytes[10:];
+ bytes = bytes[10:]
switch bytes[0] {
case '0', '1', '2', '3', '4', '5', '6':
if len(bytes) < 3 {
goto Error
}
- ret.Second, ok1 = twoDigits(bytes[0:2], 60); // 60, not 59, because of leap seconds.
+ ret.Second, ok1 = twoDigits(bytes[0:2], 60) // 60, not 59, because of leap seconds.
if !ok1 {
goto Error
}
- bytes = bytes[2:];
+ bytes = bytes[2:]
}
if len(bytes) == 0 {
goto Error
@@ -274,29 +274,29 @@ func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
if len(bytes) != 1 {
goto Error
}
- return;
+ return
case '-', '+':
if len(bytes) != 5 {
goto Error
}
- hours, ok1 := twoDigits(bytes[1:3], 12);
- minutes, ok2 := twoDigits(bytes[3:5], 59);
+ hours, ok1 := twoDigits(bytes[1:3], 12)
+ minutes, ok2 := twoDigits(bytes[3:5], 59)
if !ok1 || !ok2 {
goto Error
}
- sign := 1;
+ sign := 1
if bytes[0] == '-' {
sign = -1
}
- ret.ZoneOffset = sign * (60 * (hours*60 + minutes));
+ ret.ZoneOffset = sign * (60 * (hours*60 + minutes))
default:
goto Error
}
- return;
+ return
Error:
- err = SyntaxError{"invalid UTCTime"};
- return;
+ err = SyntaxError{"invalid UTCTime"}
+ return
}
// PrintableString
@@ -306,12 +306,12 @@ Error:
func parsePrintableString(bytes []byte) (ret string, err os.Error) {
for _, b := range bytes {
if !isPrintable(b) {
- err = SyntaxError{"PrintableString contains invalid character"};
- return;
+ err = SyntaxError{"PrintableString contains invalid character"}
+ return
}
}
- ret = string(bytes);
- return;
+ ret = string(bytes)
+ return
}
// isPrintable returns true iff the given b is in the ASN.1 PrintableString set.
@@ -334,19 +334,19 @@ func isPrintable(b byte) bool {
func parseIA5String(bytes []byte) (ret string, err os.Error) {
for _, b := range bytes {
if b >= 0x80 {
- err = SyntaxError{"IA5String contains invalid character"};
- return;
+ err = SyntaxError{"IA5String contains invalid character"}
+ return
}
}
- ret = string(bytes);
- return;
+ ret = string(bytes)
+ return
}
// A RawValue represents an undecoded ASN.1 object.
type RawValue struct {
- Class, Tag int;
- IsCompound bool;
- Bytes []byte;
+ Class, Tag int
+ IsCompound bool
+ Bytes []byte
}
// RawContent is used to signal that the undecoded, DER data needs to be
@@ -361,52 +361,52 @@ type RawContent []byte
// SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
// don't distinguish between ordered and unordered objects in this code.
func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err os.Error) {
- offset = initOffset;
- b := bytes[offset];
- offset++;
- ret.class = int(b >> 6);
- ret.isCompound = b&0x20 == 0x20;
- ret.tag = int(b & 0x1f);
+ offset = initOffset
+ b := bytes[offset]
+ offset++
+ ret.class = int(b >> 6)
+ ret.isCompound = b&0x20 == 0x20
+ ret.tag = int(b & 0x1f)
// If the bottom five bits are set, then the tag number is actually base 128
// encoded afterwards
if ret.tag == 0x1f {
- ret.tag, offset, err = parseBase128Int(bytes, offset);
+ ret.tag, offset, err = parseBase128Int(bytes, offset)
if err != nil {
return
}
}
if offset >= len(bytes) {
- err = SyntaxError{"truncated tag or length"};
- return;
+ err = SyntaxError{"truncated tag or length"}
+ return
}
- b = bytes[offset];
- offset++;
+ b = bytes[offset]
+ offset++
if b&0x80 == 0 {
// The length is encoded in the bottom 7 bits.
ret.length = int(b & 0x7f)
} else {
// Bottom 7 bits give the number of length bytes to follow.
- numBytes := int(b & 0x7f);
+ numBytes := int(b & 0x7f)
// We risk overflowing a signed 32-bit number if we accept more than 3 bytes.
if numBytes > 3 {
- err = StructuralError{"length too large"};
- return;
+ err = StructuralError{"length too large"}
+ return
}
if numBytes == 0 {
- err = SyntaxError{"indefinite length found (not DER)"};
- return;
+ err = SyntaxError{"indefinite length found (not DER)"}
+ return
}
- ret.length = 0;
+ ret.length = 0
for i := 0; i < numBytes; i++ {
if offset >= len(bytes) {
- err = SyntaxError{"truncated tag or length"};
- return;
+ err = SyntaxError{"truncated tag or length"}
+ return
}
- b = bytes[offset];
- offset++;
- ret.length <<= 8;
- ret.length |= int(b);
+ b = bytes[offset]
+ offset++
+ ret.length <<= 8
+ ret.length |= int(b)
}
}
@@ -415,57 +415,57 @@ func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset i
if ret.tag == tagSet {
ret.tag = tagSequence
}
- return;
+ return
}
// parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
// a number of ASN.1 values from the given byte array and returns them as a
// slice of Go values of the given type.
func parseSequenceOf(bytes []byte, sliceType *reflect.SliceType, elemType reflect.Type) (ret *reflect.SliceValue, err os.Error) {
- expectedTag, compoundType, ok := getUniversalType(elemType);
+ expectedTag, compoundType, ok := getUniversalType(elemType)
if !ok {
- err = StructuralError{"unknown Go type for slice"};
- return;
+ err = StructuralError{"unknown Go type for slice"}
+ return
}
// First we iterate over the input and count the number of elements,
// checking that the types are correct in each case.
- numElements := 0;
+ numElements := 0
for offset := 0; offset < len(bytes); {
- var t tagAndLength;
- t, offset, err = parseTagAndLength(bytes, offset);
+ var t tagAndLength
+ t, offset, err = parseTagAndLength(bytes, offset)
if err != nil {
return
}
if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag {
- err = StructuralError{"sequence tag mismatch"};
- return;
+ err = StructuralError{"sequence tag mismatch"}
+ return
}
if invalidLength(offset, t.length, len(bytes)) {
- err = SyntaxError{"truncated sequence"};
- return;
+ err = SyntaxError{"truncated sequence"}
+ return
}
- offset += t.length;
- numElements++;
+ offset += t.length
+ numElements++
}
- ret = reflect.MakeSlice(sliceType, numElements, numElements);
- params := fieldParameters{};
- offset := 0;
+ ret = reflect.MakeSlice(sliceType, numElements, numElements)
+ params := fieldParameters{}
+ offset := 0
for i := 0; i < numElements; i++ {
- offset, err = parseField(ret.Elem(i), bytes, offset, params);
+ offset, err = parseField(ret.Elem(i), bytes, offset, params)
if err != nil {
return
}
}
- return;
+ return
}
var (
- bitStringType = reflect.Typeof(BitString{});
- objectIdentifierType = reflect.Typeof(ObjectIdentifier{});
- timeType = reflect.Typeof(&time.Time{});
- rawValueType = reflect.Typeof(RawValue{});
- rawContentsType = reflect.Typeof(RawContent(nil));
+ bitStringType = reflect.Typeof(BitString{})
+ objectIdentifierType = reflect.Typeof(ObjectIdentifier{})
+ timeType = reflect.Typeof(&time.Time{})
+ rawValueType = reflect.Typeof(RawValue{})
+ rawContentsType = reflect.Typeof(RawContent(nil))
)
// invalidLength returns true iff offset + length > sliceLength, or if the
@@ -478,49 +478,49 @@ func invalidLength(offset, length, sliceLength int) bool {
// into the array, it will try to parse a suitable ASN.1 value out and store it
// in the given Value.
func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err os.Error) {
- offset = initOffset;
- fieldType := v.Type();
+ offset = initOffset
+ fieldType := v.Type()
// If we have run out of data, it may be that there are optional elements at the end.
if offset == len(bytes) {
if !setDefaultValue(v, params) {
err = SyntaxError{"sequence truncated"}
}
- return;
+ return
}
// Deal with raw values.
if fieldType == rawValueType {
- var t tagAndLength;
- t, offset, err = parseTagAndLength(bytes, offset);
+ var t tagAndLength
+ t, offset, err = parseTagAndLength(bytes, offset)
if err != nil {
return
}
if invalidLength(offset, t.length, len(bytes)) {
- err = SyntaxError{"data truncated"};
- return;
+ err = SyntaxError{"data truncated"}
+ return
}
- result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length]};
- offset += t.length;
- v.(*reflect.StructValue).Set(reflect.NewValue(result).(*reflect.StructValue));
- return;
+ result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length]}
+ offset += t.length
+ v.(*reflect.StructValue).Set(reflect.NewValue(result).(*reflect.StructValue))
+ return
}
// Deal with the ANY type.
if ifaceType, ok := fieldType.(*reflect.InterfaceType); ok && ifaceType.NumMethod() == 0 {
- ifaceValue := v.(*reflect.InterfaceValue);
- var t tagAndLength;
- t, offset, err = parseTagAndLength(bytes, offset);
+ ifaceValue := v.(*reflect.InterfaceValue)
+ var t tagAndLength
+ t, offset, err = parseTagAndLength(bytes, offset)
if err != nil {
return
}
if invalidLength(offset, t.length, len(bytes)) {
- err = SyntaxError{"data truncated"};
- return;
+ err = SyntaxError{"data truncated"}
+ return
}
var result interface{}
if !t.isCompound && t.class == classUniversal {
- innerBytes := bytes[offset : offset+t.length];
+ innerBytes := bytes[offset : offset+t.length]
switch t.tag {
case tagPrintableString:
result, err = parsePrintableString(innerBytes)
@@ -540,40 +540,40 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
// If we don't know how to handle the type, we just leave Value as nil.
}
}
- offset += t.length;
+ offset += t.length
if err != nil {
return
}
if result != nil {
ifaceValue.Set(reflect.NewValue(result))
}
- return;
+ return
}
- universalTag, compoundType, ok1 := getUniversalType(fieldType);
+ universalTag, compoundType, ok1 := getUniversalType(fieldType)
if !ok1 {
- err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)};
- return;
+ err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)}
+ return
}
- t, offset, err := parseTagAndLength(bytes, offset);
+ t, offset, err := parseTagAndLength(bytes, offset)
if err != nil {
return
}
if params.explicit {
if t.class == classContextSpecific && t.tag == *params.tag && t.isCompound {
- t, offset, err = parseTagAndLength(bytes, offset);
+ t, offset, err = parseTagAndLength(bytes, offset)
if err != nil {
return
}
} else {
// The tags didn't match, it might be an optional element.
- ok := setDefaultValue(v, params);
+ ok := setDefaultValue(v, params)
if ok {
offset = initOffset
} else {
err = StructuralError{"explicitly tagged member didn't match"}
}
- return;
+ return
}
}
@@ -585,128 +585,128 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
universalTag = tagIA5String
}
- expectedClass := classUniversal;
- expectedTag := universalTag;
+ expectedClass := classUniversal
+ expectedTag := universalTag
if !params.explicit && params.tag != nil {
- expectedClass = classContextSpecific;
- expectedTag = *params.tag;
+ expectedClass = classContextSpecific
+ expectedTag = *params.tag
}
// We have unwrapped any explicit tagging at this point.
if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType {
// Tags don't match. Again, it could be an optional element.
- ok := setDefaultValue(v, params);
+ ok := setDefaultValue(v, params)
if ok {
offset = initOffset
} else {
err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)}
}
- return;
+ return
}
if invalidLength(offset, t.length, len(bytes)) {
- err = SyntaxError{"data truncated"};
- return;
+ err = SyntaxError{"data truncated"}
+ return
}
- innerBytes := bytes[offset : offset+t.length];
+ innerBytes := bytes[offset : offset+t.length]
// We deal with the structures defined in this package first.
switch fieldType {
case objectIdentifierType:
- newSlice, err1 := parseObjectIdentifier(innerBytes);
- sliceValue := v.(*reflect.SliceValue);
- sliceValue.Set(reflect.MakeSlice(sliceValue.Type().(*reflect.SliceType), len(newSlice), len(newSlice)));
+ newSlice, err1 := parseObjectIdentifier(innerBytes)
+ sliceValue := v.(*reflect.SliceValue)
+ sliceValue.Set(reflect.MakeSlice(sliceValue.Type().(*reflect.SliceType), len(newSlice), len(newSlice)))
if err1 == nil {
reflect.ArrayCopy(sliceValue, reflect.NewValue(newSlice).(reflect.ArrayOrSliceValue))
}
- offset += t.length;
- err = err1;
- return;
+ offset += t.length
+ err = err1
+ return
case bitStringType:
- structValue := v.(*reflect.StructValue);
- bs, err1 := parseBitString(innerBytes);
- offset += t.length;
+ structValue := v.(*reflect.StructValue)
+ bs, err1 := parseBitString(innerBytes)
+ offset += t.length
if err1 == nil {
structValue.Set(reflect.NewValue(bs).(*reflect.StructValue))
}
- err = err1;
- return;
+ err = err1
+ return
case timeType:
- ptrValue := v.(*reflect.PtrValue);
- time, err1 := parseUTCTime(innerBytes);
- offset += t.length;
+ ptrValue := v.(*reflect.PtrValue)
+ time, err1 := parseUTCTime(innerBytes)
+ offset += t.length
if err1 == nil {
ptrValue.Set(reflect.NewValue(time).(*reflect.PtrValue))
}
- err = err1;
- return;
+ err = err1
+ return
}
switch val := v.(type) {
case *reflect.BoolValue:
- parsedBool, err1 := parseBool(innerBytes);
- offset += t.length;
+ parsedBool, err1 := parseBool(innerBytes)
+ offset += t.length
if err1 == nil {
val.Set(parsedBool)
}
- err = err1;
- return;
+ err = err1
+ return
case *reflect.IntValue:
- parsedInt, err1 := parseInt(innerBytes);
- offset += t.length;
+ parsedInt, err1 := parseInt(innerBytes)
+ offset += t.length
if err1 == nil {
val.Set(parsedInt)
}
- err = err1;
- return;
+ err = err1
+ return
case *reflect.Int64Value:
- parsedInt, err1 := parseInt64(innerBytes);
- offset += t.length;
+ parsedInt, err1 := parseInt64(innerBytes)
+ offset += t.length
if err1 == nil {
val.Set(parsedInt)
}
- err = err1;
- return;
+ err = err1
+ return
case *reflect.StructValue:
- structType := fieldType.(*reflect.StructType);
+ structType := fieldType.(*reflect.StructType)
if structType.NumField() > 0 &&
structType.Field(0).Type == rawContentsType {
- bytes := bytes[initOffset : offset+t.length];
- val.Field(0).SetValue(reflect.NewValue(RawContent(bytes)));
+ bytes := bytes[initOffset : offset+t.length]
+ val.Field(0).SetValue(reflect.NewValue(RawContent(bytes)))
}
- innerOffset := 0;
+ innerOffset := 0
for i := 0; i < structType.NumField(); i++ {
- field := structType.Field(i);
+ field := structType.Field(i)
if i == 0 && field.Type == rawContentsType {
continue
}
- innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag));
+ innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag))
if err != nil {
return
}
}
- offset += t.length;
+ offset += t.length
// We allow extra bytes at the end of the SEQUENCE because
// adding elements to the end has been used in X.509 as the
// version numbers have increased.
- return;
+ return
case *reflect.SliceValue:
- sliceType := fieldType.(*reflect.SliceType);
+ sliceType := fieldType.(*reflect.SliceType)
if _, ok := sliceType.Elem().(*reflect.Uint8Type); ok {
- val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)));
- reflect.ArrayCopy(val, reflect.NewValue(innerBytes).(reflect.ArrayOrSliceValue));
- return;
+ val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)))
+ reflect.ArrayCopy(val, reflect.NewValue(innerBytes).(reflect.ArrayOrSliceValue))
+ return
}
- newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem());
- offset += t.length;
+ newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem())
+ offset += t.length
if err1 == nil {
val.Set(newSlice)
}
- err = err1;
- return;
+ err = err1
+ return
case *reflect.StringValue:
- var v string;
+ var v string
switch universalTag {
case tagPrintableString:
v, err = parsePrintableString(innerBytes)
@@ -718,10 +718,10 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
if err == nil {
val.Set(v)
}
- return;
+ return
}
- err = StructuralError{"unknown Go type"};
- return;
+ err = StructuralError{"unknown Go type"}
+ return
}
// setDefaultValue is used to install a default value, from a tag string, into
@@ -731,7 +731,7 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
if !params.optional {
return
}
- ok = true;
+ ok = true
if params.defaultValue == nil {
return
}
@@ -741,7 +741,7 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
case *reflect.Int64Value:
val.Set(int64(*params.defaultValue))
}
- return;
+ return
}
// Unmarshal parses the DER-encoded ASN.1 data structure b
@@ -785,10 +785,10 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
// Other ASN.1 types are not supported; if it encounters them,
// Unmarshal returns a parse error.
func Unmarshal(val interface{}, b []byte) (rest []byte, err os.Error) {
- v := reflect.NewValue(val).(*reflect.PtrValue).Elem();
- offset, err := parseField(v, b, 0, fieldParameters{});
+ v := reflect.NewValue(val).(*reflect.PtrValue).Elem()
+ offset, err := parseField(v, b, 0, fieldParameters{})
if err != nil {
return nil, err
}
- return b[offset:], nil;
+ return b[offset:], nil
}
diff --git a/src/pkg/asn1/asn1_test.go b/src/pkg/asn1/asn1_test.go
index 6f677ffb69..5071facfc0 100644
--- a/src/pkg/asn1/asn1_test.go
+++ b/src/pkg/asn1/asn1_test.go
@@ -5,17 +5,17 @@
package asn1
import (
- "bytes";
- "reflect";
- "strings";
- "testing";
- "time";
+ "bytes"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
)
type int64Test struct {
- in []byte;
- ok bool;
- out int64;
+ in []byte
+ ok bool
+ out int64
}
var int64TestData = []int64Test{
@@ -33,7 +33,7 @@ var int64TestData = []int64Test{
func TestParseInt64(t *testing.T) {
for i, test := range int64TestData {
- ret, err := parseInt64(test.in);
+ ret, err := parseInt64(test.in)
if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok)
}
@@ -44,10 +44,10 @@ func TestParseInt64(t *testing.T) {
}
type bitStringTest struct {
- in []byte;
- ok bool;
- out []byte;
- bitLength int;
+ in []byte
+ ok bool
+ out []byte
+ bitLength int
}
var bitStringTestData = []bitStringTest{
@@ -61,7 +61,7 @@ var bitStringTestData = []bitStringTest{
func TestBitString(t *testing.T) {
for i, test := range bitStringTestData {
- ret, err := parseBitString(test.in);
+ ret, err := parseBitString(test.in)
if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok)
}
@@ -74,7 +74,7 @@ func TestBitString(t *testing.T) {
}
func TestBitStringAt(t *testing.T) {
- bs := BitString{[]byte{0x82, 0x40}, 16};
+ bs := BitString{[]byte{0x82, 0x40}, 16}
if bs.At(0) != 1 {
t.Error("#1: Failed")
}
@@ -90,9 +90,9 @@ func TestBitStringAt(t *testing.T) {
}
type bitStringRightAlignTest struct {
- in []byte;
- inlen int;
- out []byte;
+ in []byte
+ inlen int
+ out []byte
}
var bitStringRightAlignTests = []bitStringRightAlignTest{
@@ -106,8 +106,8 @@ var bitStringRightAlignTests = []bitStringRightAlignTest{
func TestBitStringRightAlign(t *testing.T) {
for i, test := range bitStringRightAlignTests {
- bs := BitString{test.in, test.inlen};
- out := bs.RightAlign();
+ bs := BitString{test.in, test.inlen}
+ out := bs.RightAlign()
if bytes.Compare(out, test.out) != 0 {
t.Errorf("#%d got: %x want: %x", i, out, test.out)
}
@@ -115,9 +115,9 @@ func TestBitStringRightAlign(t *testing.T) {
}
type objectIdentifierTest struct {
- in []byte;
- ok bool;
- out []int;
+ in []byte
+ ok bool
+ out []int
}
var objectIdentifierTestData = []objectIdentifierTest{
@@ -130,7 +130,7 @@ var objectIdentifierTestData = []objectIdentifierTest{
func TestObjectIdentifier(t *testing.T) {
for i, test := range objectIdentifierTestData {
- ret, err := parseObjectIdentifier(test.in);
+ ret, err := parseObjectIdentifier(test.in)
if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok)
}
@@ -143,9 +143,9 @@ func TestObjectIdentifier(t *testing.T) {
}
type timeTest struct {
- in string;
- ok bool;
- out *time.Time;
+ in string
+ ok bool
+ out *time.Time
}
var timeTestData = []timeTest{
@@ -165,7 +165,7 @@ var timeTestData = []timeTest{
func TestTime(t *testing.T) {
for i, test := range timeTestData {
- ret, err := parseUTCTime(strings.Bytes(test.in));
+ ret, err := parseUTCTime(strings.Bytes(test.in))
if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok)
}
@@ -178,9 +178,9 @@ func TestTime(t *testing.T) {
}
type tagAndLengthTest struct {
- in []byte;
- ok bool;
- out tagAndLength;
+ in []byte
+ ok bool
+ out tagAndLength
}
var tagAndLengthData = []tagAndLengthTest{
@@ -200,7 +200,7 @@ var tagAndLengthData = []tagAndLengthTest{
func TestParseTagAndLength(t *testing.T) {
for i, test := range tagAndLengthData {
- tagAndLength, _, err := parseTagAndLength(test.in, 0);
+ tagAndLength, _, err := parseTagAndLength(test.in, 0)
if (err == nil) != test.ok {
t.Errorf("#%d: Incorrect error result (did pass? %v, expected: %v)", i, err == nil, test.ok)
}
@@ -211,17 +211,17 @@ func TestParseTagAndLength(t *testing.T) {
}
type parseFieldParametersTest struct {
- in string;
- out fieldParameters;
+ in string
+ out fieldParameters
}
-func newInt(n int) *int { return &n }
+func newInt(n int) *int { return &n }
-func newInt64(n int64) *int64 { return &n }
+func newInt64(n int64) *int64 { return &n }
-func newString(s string) *string { return &s }
+func newString(s string) *string { return &s }
-func newBool(b bool) *bool { return &b }
+func newBool(b bool) *bool { return &b }
var parseFieldParametersTestData []parseFieldParametersTest = []parseFieldParametersTest{
parseFieldParametersTest{"", fieldParameters{false, false, nil, nil, 0}},
@@ -238,7 +238,7 @@ var parseFieldParametersTestData []parseFieldParametersTest = []parseFieldParame
func TestParseFieldParameters(t *testing.T) {
for i, test := range parseFieldParametersTestData {
- f := parseFieldParameters(test.in);
+ f := parseFieldParameters(test.in)
if !reflect.DeepEqual(f, test.out) {
t.Errorf("#%d: Bad result: %v (expected %v)", i, f, test.out)
}
@@ -246,21 +246,21 @@ func TestParseFieldParameters(t *testing.T) {
}
type unmarshalTest struct {
- in []byte;
- out interface{};
+ in []byte
+ out interface{}
}
type TestObjectIdentifierStruct struct {
- OID ObjectIdentifier;
+ OID ObjectIdentifier
}
type TestContextSpecificTags struct {
- A int "tag:1";
+ A int "tag:1"
}
type TestContextSpecificTags2 struct {
- A int "explicit,tag:1";
- B int;
+ A int "explicit,tag:1"
+ B int
}
var unmarshalTestData []unmarshalTest = []unmarshalTest{
@@ -281,11 +281,11 @@ var unmarshalTestData []unmarshalTest = []unmarshalTest{
func TestUnmarshal(t *testing.T) {
for i, test := range unmarshalTestData {
- pv := reflect.MakeZero(reflect.NewValue(test.out).Type());
- zv := reflect.MakeZero(pv.Type().(*reflect.PtrType).Elem());
- pv.(*reflect.PtrValue).PointTo(zv);
- val := pv.Interface();
- _, err := Unmarshal(val, test.in);
+ pv := reflect.MakeZero(reflect.NewValue(test.out).Type())
+ zv := reflect.MakeZero(pv.Type().(*reflect.PtrType).Elem())
+ pv.(*reflect.PtrValue).PointTo(zv)
+ val := pv.Interface()
+ _, err := Unmarshal(val, test.in)
if err != nil {
t.Errorf("Unmarshal failed at index %d %v", i, err)
}
@@ -296,23 +296,23 @@ func TestUnmarshal(t *testing.T) {
}
type Certificate struct {
- TBSCertificate TBSCertificate;
- SignatureAlgorithm AlgorithmIdentifier;
- SignatureValue BitString;
+ TBSCertificate TBSCertificate
+ SignatureAlgorithm AlgorithmIdentifier
+ SignatureValue BitString
}
type TBSCertificate struct {
- Version int "optional,explicit,default:0,tag:0";
- SerialNumber RawValue;
- SignatureAlgorithm AlgorithmIdentifier;
- Issuer RDNSequence;
- Validity Validity;
- Subject RDNSequence;
- PublicKey PublicKeyInfo;
+ Version int "optional,explicit,default:0,tag:0"
+ SerialNumber RawValue
+ SignatureAlgorithm AlgorithmIdentifier
+ Issuer RDNSequence
+ Validity Validity
+ Subject RDNSequence
+ PublicKey PublicKeyInfo
}
type AlgorithmIdentifier struct {
- Algorithm ObjectIdentifier;
+ Algorithm ObjectIdentifier
}
type RDNSequence []RelativeDistinguishedName
@@ -320,22 +320,22 @@ type RDNSequence []RelativeDistinguishedName
type RelativeDistinguishedName []AttributeTypeAndValue
type AttributeTypeAndValue struct {
- Type ObjectIdentifier;
- Value interface{};
+ Type ObjectIdentifier
+ Value interface{}
}
type Validity struct {
- NotBefore, NotAfter *time.Time;
+ NotBefore, NotAfter *time.Time
}
type PublicKeyInfo struct {
- Algorithm AlgorithmIdentifier;
- PublicKey BitString;
+ Algorithm AlgorithmIdentifier
+ PublicKey BitString
}
func TestCertificate(t *testing.T) {
// This is a minimal, self-signed certificate that should parse correctly.
- var cert Certificate;
+ var cert Certificate
if _, err := Unmarshal(&cert, derEncodedSelfSignedCertBytes); err != nil {
t.Errorf("Unmarshal failed: %v", err)
}
@@ -348,29 +348,29 @@ func TestCertificateWithNUL(t *testing.T) {
// This is the paypal NUL-hack certificate. It should fail to parse because
// NUL isn't a permitted character in a PrintableString.
- var cert Certificate;
+ var cert Certificate
if _, err := Unmarshal(&cert, derEncodedPaypalNULCertBytes); err == nil {
t.Error("Unmarshal succeeded, should not have")
}
}
type rawStructTest struct {
- Raw RawContent;
- A int;
+ Raw RawContent
+ A int
}
func TestRawStructs(t *testing.T) {
- var s rawStructTest;
- input := []byte{0x30, 0x03, 0x02, 0x01, 0x50};
+ var s rawStructTest
+ input := []byte{0x30, 0x03, 0x02, 0x01, 0x50}
- rest, err := Unmarshal(&s, input);
+ rest, err := Unmarshal(&s, input)
if len(rest) != 0 {
- t.Errorf("incomplete parse: %x", rest);
- return;
+ t.Errorf("incomplete parse: %x", rest)
+ return
}
if err != nil {
- t.Error(err);
- return;
+ t.Error(err)
+ return
}
if s.A != 0x50 {
t.Errorf("bad value for A: got %d want %d", s.A, 0x50)
diff --git a/src/pkg/asn1/common.go b/src/pkg/asn1/common.go
index bdc4c8abd6..a3278b6392 100644
--- a/src/pkg/asn1/common.go
+++ b/src/pkg/asn1/common.go
@@ -5,9 +5,9 @@
package asn1
import (
- "reflect";
- "strconv";
- "strings";
+ "reflect"
+ "strconv"
+ "strings"
)
// ASN.1 objects have metadata preceeding them:
@@ -19,28 +19,28 @@ import (
// Here are some standard tags and classes
const (
- tagBoolean = 1;
- tagInteger = 2;
- tagBitString = 3;
- tagOctetString = 4;
- tagOID = 6;
- tagSequence = 16;
- tagSet = 17;
- tagPrintableString = 19;
- tagIA5String = 22;
- tagUTCTime = 23;
+ tagBoolean = 1
+ tagInteger = 2
+ tagBitString = 3
+ tagOctetString = 4
+ tagOID = 6
+ tagSequence = 16
+ tagSet = 17
+ tagPrintableString = 19
+ tagIA5String = 22
+ tagUTCTime = 23
)
const (
- classUniversal = 0;
- classApplication = 1;
- classContextSpecific = 2;
- classPrivate = 3;
+ classUniversal = 0
+ classApplication = 1
+ classContextSpecific = 2
+ classPrivate = 3
)
type tagAndLength struct {
- class, tag, length int;
- isCompound bool;
+ class, tag, length int
+ isCompound bool
}
// ASN.1 has IMPLICIT and EXPLICIT tags, which can be translated as "instead
@@ -63,11 +63,11 @@ type tagAndLength struct {
// fieldParameters is the parsed representation of tag string from a structure field.
type fieldParameters struct {
- optional bool; // true iff the field is OPTIONAL
- explicit bool; // true iff and EXPLICIT tag is in use.
- defaultValue *int64; // a default value for INTEGER typed fields (maybe nil).
- tag *int; // the EXPLICIT or IMPLICIT tag (maybe nil).
- stringType int; // the string tag to use when marshaling.
+ optional bool // true iff the field is OPTIONAL
+ explicit bool // true iff and EXPLICIT tag is in use.
+ defaultValue *int64 // a default value for INTEGER typed fields (maybe nil).
+ tag *int // the EXPLICIT or IMPLICIT tag (maybe nil).
+ stringType int // the string tag to use when marshaling.
// Invariants:
// if explicit is set, tag is non-nil.
@@ -82,30 +82,30 @@ func parseFieldParameters(str string) (ret fieldParameters) {
case part == "optional":
ret.optional = true
case part == "explicit":
- ret.explicit = true;
+ ret.explicit = true
if ret.tag == nil {
- ret.tag = new(int);
- *ret.tag = 0;
+ ret.tag = new(int)
+ *ret.tag = 0
}
case part == "ia5":
ret.stringType = tagIA5String
case part == "printable":
ret.stringType = tagPrintableString
case strings.HasPrefix(part, "default:"):
- i, err := strconv.Atoi64(part[8:]);
+ i, err := strconv.Atoi64(part[8:])
if err == nil {
- ret.defaultValue = new(int64);
- *ret.defaultValue = i;
+ ret.defaultValue = new(int64)
+ *ret.defaultValue = i
}
case strings.HasPrefix(part, "tag:"):
- i, err := strconv.Atoi(part[4:]);
+ i, err := strconv.Atoi(part[4:])
if err == nil {
- ret.tag = new(int);
- *ret.tag = i;
+ ret.tag = new(int)
+ *ret.tag = i
}
}
}
- return;
+ return
}
// Given a reflected Go type, getUniversalType returns the default tag number
@@ -132,9 +132,9 @@ func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) {
if _, ok := t.(*reflect.SliceType).Elem().(*reflect.Uint8Type); ok {
return tagOctetString, false, true
}
- return tagSequence, true, true;
+ return tagSequence, true, true
case *reflect.StringType:
return tagPrintableString, false, true
}
- return 0, false, false;
+ return 0, false, false
}
diff --git a/src/pkg/asn1/marshal.go b/src/pkg/asn1/marshal.go
index 2e9aa14391..eec0ee8494 100644
--- a/src/pkg/asn1/marshal.go
+++ b/src/pkg/asn1/marshal.go
@@ -5,13 +5,13 @@
package asn1
import (
- "bytes";
- "fmt";
- "io";
- "os";
- "reflect";
- "strings";
- "time";
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "reflect"
+ "strings"
+ "time"
)
// A forkableWriter is an in-memory buffer that can be
@@ -20,8 +20,8 @@ import (
// pre, post := w.fork();
// the overall sequence of bytes represented is logically w+pre+post.
type forkableWriter struct {
- *bytes.Buffer;
- pre, post *forkableWriter;
+ *bytes.Buffer
+ pre, post *forkableWriter
}
func newForkableWriter() *forkableWriter {
@@ -29,65 +29,65 @@ func newForkableWriter() *forkableWriter {
}
func (f *forkableWriter) fork() (pre, post *forkableWriter) {
- f.pre = newForkableWriter();
- f.post = newForkableWriter();
- return f.pre, f.post;
+ f.pre = newForkableWriter()
+ f.post = newForkableWriter()
+ return f.pre, f.post
}
func (f *forkableWriter) Len() (l int) {
- l += f.Buffer.Len();
+ l += f.Buffer.Len()
if f.pre != nil {
l += f.pre.Len()
}
if f.post != nil {
l += f.post.Len()
}
- return;
+ return
}
func (f *forkableWriter) writeTo(out io.Writer) (n int, err os.Error) {
- n, err = out.Write(f.Bytes());
+ n, err = out.Write(f.Bytes())
if err != nil {
return
}
- var nn int;
+ var nn int
if f.pre != nil {
- nn, err = f.pre.writeTo(out);
- n += nn;
+ nn, err = f.pre.writeTo(out)
+ n += nn
if err != nil {
return
}
}
if f.pre != nil {
- nn, err = f.post.writeTo(out);
- n += nn;
+ nn, err = f.post.writeTo(out)
+ n += nn
}
- return;
+ return
}
func marshalBase128Int(out *forkableWriter, i int64) (err os.Error) {
if i == 0 {
- err = out.WriteByte(0);
- return;
+ err = out.WriteByte(0)
+ return
}
for i > 0 {
- next := i >> 7;
- o := byte(i & 0x7f);
+ next := i >> 7
+ o := byte(i & 0x7f)
if next > 0 {
o |= 0x80
}
- err = out.WriteByte(o);
+ err = out.WriteByte(o)
if err != nil {
return
}
- i = next;
+ i = next
}
- return nil;
+ return nil
}
func base128Length(i int) (numBytes int) {
@@ -96,63 +96,63 @@ func base128Length(i int) (numBytes int) {
}
for i > 0 {
- numBytes++;
- i >>= 7;
+ numBytes++
+ i >>= 7
}
- return;
+ return
}
func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) {
- b := uint8(t.class) << 6;
+ b := uint8(t.class) << 6
if t.isCompound {
b |= 0x20
}
if t.tag >= 31 {
- b |= 0x1f;
- err = out.WriteByte(b);
+ b |= 0x1f
+ err = out.WriteByte(b)
if err != nil {
return
}
- err = marshalBase128Int(out, int64(t.tag));
+ err = marshalBase128Int(out, int64(t.tag))
if err != nil {
return
}
} else {
- b |= uint8(t.tag);
- err = out.WriteByte(b);
+ b |= uint8(t.tag)
+ err = out.WriteByte(b)
if err != nil {
return
}
}
if t.length >= 128 {
- err = out.WriteByte(byte(base128Length(t.length)));
+ err = out.WriteByte(byte(base128Length(t.length)))
if err != nil {
return
}
- err = marshalBase128Int(out, int64(t.length));
+ err = marshalBase128Int(out, int64(t.length))
if err != nil {
return
}
} else {
- err = out.WriteByte(byte(t.length));
+ err = out.WriteByte(byte(t.length))
if err != nil {
return
}
}
- return nil;
+ return nil
}
func marshalBitString(out *forkableWriter, b BitString) (err os.Error) {
- paddingBits := byte((8 - b.BitLength%8) % 8);
- err = out.WriteByte(paddingBits);
+ paddingBits := byte((8 - b.BitLength%8) % 8)
+ err = out.WriteByte(paddingBits)
if err != nil {
return
}
- _, err = out.Write(b.Bytes);
- return;
+ _, err = out.Write(b.Bytes)
+ return
}
func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) {
@@ -160,50 +160,50 @@ func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) {
return StructuralError{"invalid object identifier"}
}
- err = out.WriteByte(byte(oid[0]*40 + oid[1]));
+ err = out.WriteByte(byte(oid[0]*40 + oid[1]))
if err != nil {
return
}
for i := 2; i < len(oid); i++ {
- err = marshalBase128Int(out, int64(oid[i]));
+ err = marshalBase128Int(out, int64(oid[i]))
if err != nil {
return
}
}
- return;
+ return
}
func marshalPrintableString(out *forkableWriter, s string) (err os.Error) {
- b := strings.Bytes(s);
+ b := strings.Bytes(s)
for _, c := range b {
if !isPrintable(c) {
return StructuralError{"PrintableString contains invalid character"}
}
}
- _, err = out.Write(b);
- return;
+ _, err = out.Write(b)
+ return
}
func marshalIA5String(out *forkableWriter, s string) (err os.Error) {
- b := strings.Bytes(s);
+ b := strings.Bytes(s)
for _, c := range b {
if c > 127 {
return StructuralError{"IA5String contains invalid character"}
}
}
- _, err = out.Write(b);
- return;
+ _, err = out.Write(b)
+ return
}
func marshalTwoDigits(out *forkableWriter, v int) (err os.Error) {
- err = out.WriteByte(byte('0' + (v/10)%10));
+ err = out.WriteByte(byte('0' + (v/10)%10))
if err != nil {
return
}
- return out.WriteByte(byte('0' + v%10));
+ return out.WriteByte(byte('0' + v%10))
}
func marshalUTCTime(out *forkableWriter, t *time.Time) (err os.Error) {
@@ -220,35 +220,35 @@ func marshalUTCTime(out *forkableWriter, t *time.Time) (err os.Error) {
return
}
- err = marshalTwoDigits(out, t.Month);
+ err = marshalTwoDigits(out, t.Month)
if err != nil {
return
}
- err = marshalTwoDigits(out, t.Day);
+ err = marshalTwoDigits(out, t.Day)
if err != nil {
return
}
- err = marshalTwoDigits(out, t.Hour);
+ err = marshalTwoDigits(out, t.Hour)
if err != nil {
return
}
- err = marshalTwoDigits(out, t.Minute);
+ err = marshalTwoDigits(out, t.Minute)
if err != nil {
return
}
- err = marshalTwoDigits(out, t.Second);
+ err = marshalTwoDigits(out, t.Second)
if err != nil {
return
}
switch {
case t.ZoneOffset/60 == 0:
- err = out.WriteByte('Z');
- return;
+ err = out.WriteByte('Z')
+ return
case t.ZoneOffset > 0:
err = out.WriteByte('+')
case t.ZoneOffset < 0:
@@ -259,18 +259,18 @@ func marshalUTCTime(out *forkableWriter, t *time.Time) (err os.Error) {
return
}
- offsetMinutes := t.ZoneOffset / 60;
+ offsetMinutes := t.ZoneOffset / 60
if offsetMinutes < 0 {
offsetMinutes = -offsetMinutes
}
- err = marshalTwoDigits(out, offsetMinutes/60);
+ err = marshalTwoDigits(out, offsetMinutes/60)
if err != nil {
return
}
- err = marshalTwoDigits(out, offsetMinutes%60);
- return;
+ err = marshalTwoDigits(out, offsetMinutes%60)
+ return
}
func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err os.Error) {
@@ -295,81 +295,81 @@ func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameter
case *reflect.Int64Value:
return marshalBase128Int(out, v.Get())
case *reflect.StructValue:
- t := v.Type().(*reflect.StructType);
+ t := v.Type().(*reflect.StructType)
for i := 0; i < t.NumField(); i++ {
- err = marshalField(out, v.Field(i), parseFieldParameters(t.Field(i).Tag));
+ err = marshalField(out, v.Field(i), parseFieldParameters(t.Field(i).Tag))
if err != nil {
return
}
}
- return;
+ return
case *reflect.SliceValue:
- sliceType := v.Type().(*reflect.SliceType);
+ sliceType := v.Type().(*reflect.SliceType)
if _, ok := sliceType.Elem().(*reflect.Uint8Type); ok {
- bytes := make([]byte, v.Len());
+ bytes := make([]byte, v.Len())
for i := 0; i < v.Len(); i++ {
bytes[i] = v.Elem(i).(*reflect.Uint8Value).Get()
}
- _, err = out.Write(bytes);
- return;
+ _, err = out.Write(bytes)
+ return
}
- var params fieldParameters;
+ var params fieldParameters
for i := 0; i < v.Len(); i++ {
- err = marshalField(out, v.Elem(i), params);
+ err = marshalField(out, v.Elem(i), params)
if err != nil {
return
}
}
- return;
+ return
case *reflect.StringValue:
if params.stringType == tagIA5String {
return marshalIA5String(out, v.Get())
} else {
return marshalPrintableString(out, v.Get())
}
- return;
+ return
}
- return StructuralError{"unknown Go type"};
+ return StructuralError{"unknown Go type"}
}
func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err os.Error) {
- tag, isCompound, ok := getUniversalType(v.Type());
+ tag, isCompound, ok := getUniversalType(v.Type())
if !ok {
- err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())};
- return;
+ err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())}
+ return
}
- class := classUniversal;
+ class := classUniversal
if params.stringType != 0 {
if tag != tagPrintableString {
return StructuralError{"Explicit string type given to non-string member"}
}
- tag = params.stringType;
+ tag = params.stringType
}
- tags, body := out.fork();
+ tags, body := out.fork()
- err = marshalBody(body, v, params);
+ err = marshalBody(body, v, params)
if err != nil {
return
}
- bodyLen := body.Len();
+ bodyLen := body.Len()
- var explicitTag *forkableWriter;
+ var explicitTag *forkableWriter
if params.explicit {
explicitTag, tags = tags.fork()
}
if !params.explicit && params.tag != nil {
// implicit tag.
- tag = *params.tag;
- class = classContextSpecific;
+ tag = *params.tag
+ class = classContextSpecific
}
- err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound});
+ err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound})
if err != nil {
return
}
@@ -383,18 +383,18 @@ func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters)
})
}
- return nil;
+ return nil
}
// Marshal serialises val as an ASN.1 structure and writes the result to out.
// In the case of an error, no output is produced.
func Marshal(out io.Writer, val interface{}) os.Error {
- v := reflect.NewValue(val);
- f := newForkableWriter();
- err := marshalField(f, v, fieldParameters{});
+ v := reflect.NewValue(val)
+ f := newForkableWriter()
+ err := marshalField(f, v, fieldParameters{})
if err != nil {
return err
}
- _, err = f.writeTo(out);
- return err;
+ _, err = f.writeTo(out)
+ return err
}
diff --git a/src/pkg/asn1/marshal_test.go b/src/pkg/asn1/marshal_test.go
index c2ce1e476a..2bb8a28d9c 100644
--- a/src/pkg/asn1/marshal_test.go
+++ b/src/pkg/asn1/marshal_test.go
@@ -5,44 +5,44 @@
package asn1
import (
- "bytes";
- "encoding/hex";
- "testing";
- "time";
+ "bytes"
+ "encoding/hex"
+ "testing"
+ "time"
)
type intStruct struct {
- A int;
+ A int
}
type nestedStruct struct {
- A intStruct;
+ A intStruct
}
type marshalTest struct {
- in interface{};
- out string; // hex encoded
+ in interface{}
+ out string // hex encoded
}
type implicitTagTest struct {
- A int "implicit,tag:5";
+ A int "implicit,tag:5"
}
type explicitTagTest struct {
- A int "explicit,tag:5";
+ A int "explicit,tag:5"
}
type ia5StringTest struct {
- A string "ia5";
+ A string "ia5"
}
type printableStringTest struct {
- A string "printable";
+ A string "printable"
}
func setPST(t *time.Time) *time.Time {
- t.ZoneOffset = -28800;
- return t;
+ t.ZoneOffset = -28800
+ return t
}
var marshalTests = []marshalTest{
@@ -65,12 +65,12 @@ var marshalTests = []marshalTest{
func TestMarshal(t *testing.T) {
for i, test := range marshalTests {
- buf := bytes.NewBuffer(nil);
- err := Marshal(buf, test.in);
+ buf := bytes.NewBuffer(nil)
+ err := Marshal(buf, test.in)
if err != nil {
t.Errorf("#%d failed: %s", i, err)
}
- out, _ := hex.DecodeString(test.out);
+ out, _ := hex.DecodeString(test.out)
if bytes.Compare(out, buf.Bytes()) != 0 {
t.Errorf("#%d got: %x want %x", i, buf.Bytes(), out)
}
diff --git a/src/pkg/big/arith.go b/src/pkg/big/arith.go
index 3dcbe637f5..81ce23a3a9 100644
--- a/src/pkg/big/arith.go
+++ b/src/pkg/big/arith.go
@@ -13,14 +13,14 @@ import "unsafe"
type Word uintptr
const (
- _S = uintptr(unsafe.Sizeof(Word(0))); // TODO(gri) should Sizeof return a uintptr?
- _logW = (0x650 >> _S) & 7;
- _W = 1 << _logW;
- _B = 1 << _W;
- _M = _B - 1;
- _W2 = _W / 2;
- _B2 = 1 << _W2;
- _M2 = _B2 - 1;
+ _S = uintptr(unsafe.Sizeof(Word(0))) // TODO(gri) should Sizeof return a uintptr?
+ _logW = (0x650 >> _S) & 7
+ _W = 1 << _logW
+ _B = 1 << _W
+ _M = _B - 1
+ _W2 = _W / 2
+ _B2 = 1 << _W2
+ _M2 = _B2 - 1
)
@@ -31,23 +31,23 @@ const (
// z1<<_W + z0 = x+y+c, with c == 0 or 1
func addWW_g(x, y, c Word) (z1, z0 Word) {
- yc := y + c;
- z0 = x + yc;
+ yc := y + c
+ z0 = x + yc
if z0 < x || yc < y {
z1 = 1
}
- return;
+ return
}
// z1<<_W + z0 = x-y-c, with c == 0 or 1
func subWW_g(x, y, c Word) (z1, z0 Word) {
- yc := y + c;
- z0 = x - yc;
+ yc := y + c
+ z0 = x - yc
if z0 > x || yc < y {
z1 = 1
}
- return;
+ return
}
@@ -65,62 +65,62 @@ func mulWW_g(x, y Word) (z1, z0 Word) {
// y < _B2 because y <= x
// sub-digits of x and y are (0, x) and (0, y)
// z = z[0] = x*y
- z0 = x * y;
- return;
+ z0 = x * y
+ return
}
if y < _B2 {
// sub-digits of x and y are (x1, x0) and (0, y)
// x = (x1*_B2 + x0)
// y = (y1*_B2 + y0)
- x1, x0 := x>>_W2, x&_M2;
+ x1, x0 := x>>_W2, x&_M2
// x*y = t2*_B2*_B2 + t1*_B2 + t0
- t0 := x0 * y;
- t1 := x1 * y;
+ t0 := x0 * y
+ t1 := x1 * y
// compute result digits but avoid overflow
// z = z[1]*_B + z[0] = x*y
- z0 = t1<<_W2 + t0;
- z1 = (t1 + t0>>_W2) >> _W2;
- return;
+ z0 = t1<<_W2 + t0
+ z1 = (t1 + t0>>_W2) >> _W2
+ return
}
// general case
// sub-digits of x and y are (x1, x0) and (y1, y0)
// x = (x1*_B2 + x0)
// y = (y1*_B2 + y0)
- x1, x0 := x>>_W2, x&_M2;
- y1, y0 := y>>_W2, y&_M2;
+ x1, x0 := x>>_W2, x&_M2
+ y1, y0 := y>>_W2, y&_M2
// x*y = t2*_B2*_B2 + t1*_B2 + t0
- t0 := x0 * y0;
+ t0 := x0 * y0
// t1 := x1*y0 + x0*y1;
- var c Word;
- t1 := x1 * y0;
- t1a := t1;
- t1 += x0 * y1;
+ var c Word
+ t1 := x1 * y0
+ t1a := t1
+ t1 += x0 * y1
if t1 < t1a {
c++
}
- t2 := x1*y1 + c*_B2;
+ t2 := x1*y1 + c*_B2
// compute result digits but avoid overflow
// z = z[1]*_B + z[0] = x*y
// This may overflow, but that's ok because we also sum t1 and t0 above
// and we take care of the overflow there.
- z0 = t1<<_W2 + t0;
+ z0 = t1<<_W2 + t0
// z1 = t2 + (t1 + t0>>_W2)>>_W2;
- var c3 Word;
- z1 = t1 + t0>>_W2;
+ var c3 Word
+ z1 = t1 + t0>>_W2
if z1 < t1 {
c3++
}
- z1 >>= _W2;
- z1 += c3 * _B2;
- z1 += t2;
- return;
+ z1 >>= _W2
+ z1 += c3 * _B2
+ z1 += t2
+ return
}
@@ -136,78 +136,78 @@ func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
// sub-digits of x, y, and c are (x1, x0), (y1, y0), (c1, c0)
// x = (x1*_B2 + x0)
// y = (y1*_B2 + y0)
- x1, x0 := x>>_W2, x&_M2;
- y1, y0 := y>>_W2, y&_M2;
- c1, c0 := c>>_W2, c&_M2;
+ x1, x0 := x>>_W2, x&_M2
+ y1, y0 := y>>_W2, y&_M2
+ c1, c0 := c>>_W2, c&_M2
// x*y + c = t2*_B2*_B2 + t1*_B2 + t0
// (1<<32-1)^2 == 1<<64 - 1<<33 + 1, so there's space to add c0 in here.
- t0 := x0*y0 + c0;
+ t0 := x0*y0 + c0
// t1 := x1*y0 + x0*y1 + c1;
- var c2 Word; // extra carry
- t1 := x1*y0 + c1;
- t1a := t1;
- t1 += x0 * y1;
- if t1 < t1a { // If the number got smaller then we overflowed.
+ var c2 Word // extra carry
+ t1 := x1*y0 + c1
+ t1a := t1
+ t1 += x0 * y1
+ if t1 < t1a { // If the number got smaller then we overflowed.
c2++
}
- t2 := x1*y1 + c2*_B2;
+ t2 := x1*y1 + c2*_B2
// compute result digits but avoid overflow
// z = z[1]*_B + z[0] = x*y
// z0 = t1<<_W2 + t0;
// This may overflow, but that's ok because we also sum t1 and t0 below
// and we take care of the overflow there.
- z0 = t1<<_W2 + t0;
+ z0 = t1<<_W2 + t0
- var c3 Word;
- z1 = t1 + t0>>_W2;
+ var c3 Word
+ z1 = t1 + t0>>_W2
if z1 < t1 {
c3++
}
- z1 >>= _W2;
- z1 += t2 + c3*_B2;
+ z1 >>= _W2
+ z1 += t2 + c3*_B2
- return;
+ return
}
// q = (x1<<_W + x0 - r)/y
// The most significant bit of y must be 1.
func divStep(x1, x0, y Word) (q, r Word) {
- d1, d0 := y>>_W2, y&_M2;
- q1, r1 := x1/d1, x1%d1;
- m := q1 * d0;
- r1 = r1*_B2 | x0>>_W2;
+ d1, d0 := y>>_W2, y&_M2
+ q1, r1 := x1/d1, x1%d1
+ m := q1 * d0
+ r1 = r1*_B2 | x0>>_W2
if r1 < m {
- q1--;
- r1 += y;
+ q1--
+ r1 += y
if r1 >= y && r1 < m {
- q1--;
- r1 += y;
+ q1--
+ r1 += y
}
}
- r1 -= m;
+ r1 -= m
- r0 := r1 % d1;
- q0 := r1 / d1;
- m = q0 * d0;
- r0 = r0*_B2 | x0&_M2;
+ r0 := r1 % d1
+ q0 := r1 / d1
+ m = q0 * d0
+ r0 = r0*_B2 | x0&_M2
if r0 < m {
- q0--;
- r0 += y;
+ q0--
+ r0 += y
if r0 >= y && r0 < m {
- q0--;
- r0 += y;
+ q0--
+ r0 += y
}
}
- r0 -= m;
+ r0 -= m
- q = q1*_B2 | q0;
- r = r0;
- return;
+ q = q1*_B2 | q0
+ r = r0
+ return
}
@@ -217,53 +217,53 @@ func leadingZeros(x Word) (n uint) {
return _W
}
for x&(1<<(_W-1)) == 0 {
- n++;
- x <<= 1;
+ n++
+ x <<= 1
}
- return;
+ return
}
// q = (x1<<_W + x0 - r)/y
func divWW_g(x1, x0, y Word) (q, r Word) {
if x1 == 0 {
- q, r = x0/y, x0%y;
- return;
+ q, r = x0/y, x0%y
+ return
}
- var q0, q1 Word;
- z := leadingZeros(y);
+ var q0, q1 Word
+ z := leadingZeros(y)
if y > x1 {
if z != 0 {
- y <<= z;
- x1 = (x1 << z) | (x0 >> (_W - z));
- x0 <<= z;
+ y <<= z
+ x1 = (x1 << z) | (x0 >> (_W - z))
+ x0 <<= z
}
- q0, x0 = divStep(x1, x0, y);
- q1 = 0;
+ q0, x0 = divStep(x1, x0, y)
+ q1 = 0
} else {
if z == 0 {
- x1 -= y;
- q1 = 1;
+ x1 -= y
+ q1 = 1
} else {
- z1 := _W - z;
- y <<= z;
- x2 := x1 >> z1;
- x1 = (x1 << z) | (x0 >> z1);
- x0 <<= z;
- q1, x1 = divStep(x2, x1, y);
+ z1 := _W - z
+ y <<= z
+ x2 := x1 >> z1
+ x1 = (x1 << z) | (x0 >> z1)
+ x0 <<= z
+ q1, x1 = divStep(x2, x1, y)
}
- q0, x0 = divStep(x1, x0, y);
+ q0, x0 = divStep(x1, x0, y)
}
- r = x0 >> z;
+ r = x0 >> z
if q1 != 0 {
panic("div out of range")
}
- return q0, r;
+ return q0, r
}
@@ -276,25 +276,25 @@ func divWW_g(x1, x0, y Word) (q, r Word) {
// f_s should be installed if they exist.
var (
// addVV sets z and returns c such that z+c = x+y.
- addVV func(z, x, y *Word, n int) (c Word) = addVV_g;
+ addVV func(z, x, y *Word, n int) (c Word) = addVV_g
// subVV sets z and returns c such that z-c = x-y.
- subVV func(z, x, y *Word, n int) (c Word) = subVV_g;
+ subVV func(z, x, y *Word, n int) (c Word) = subVV_g
// addVW sets z and returns c such that z+c = x-y.
- addVW func(z, x *Word, y Word, n int) (c Word) = addVW_g;
+ addVW func(z, x *Word, y Word, n int) (c Word) = addVW_g
// subVW sets z and returns c such that z-c = x-y.
- subVW func(z, x *Word, y Word, n int) (c Word) = subVW_g;
+ subVW func(z, x *Word, y Word, n int) (c Word) = subVW_g
// mulAddVWW sets z and returns c such that z+c = x*y + r.
- mulAddVWW func(z, x *Word, y, r Word, n int) (c Word) = mulAddVWW_g;
+ mulAddVWW func(z, x *Word, y, r Word, n int) (c Word) = mulAddVWW_g
// addMulVVW sets z and returns c such that z+c = z + x*y.
- addMulVVW func(z, x *Word, y Word, n int) (c Word) = addMulVVW_g;
+ addMulVVW func(z, x *Word, y Word, n int) (c Word) = addMulVVW_g
// divWVW sets z and returns r such that z-r = (xn<<(n*_W) + x) / y.
- divWVW func(z *Word, xn Word, x *Word, y Word, n int) (r Word) = divWVW_g;
+ divWVW func(z *Word, xn Word, x *Word, y Word, n int) (r Word) = divWVW_g
)
@@ -303,13 +303,13 @@ func init() {
//return;
// Install assembly routines.
- addVV = addVV_s;
- subVV = subVV_s;
- addVW = addVW_s;
- subVW = subVW_s;
- mulAddVWW = mulAddVWW_s;
- addMulVVW = addMulVVW_s;
- divWVW = divWVW_s;
+ addVV = addVV_s
+ subVV = subVV_s
+ addVW = addVW_s
+ subVW = subVW_s
+ mulAddVWW = mulAddVWW_s
+ addMulVVW = addMulVVW_s
+ divWVW = divWVW_s
}
@@ -323,7 +323,7 @@ func addVV_g(z, x, y *Word, n int) (c Word) {
for i := 0; i < n; i++ {
c, *z.at(i) = addWW_g(*x.at(i), *y.at(i), c)
}
- return;
+ return
}
@@ -332,56 +332,56 @@ func subVV_g(z, x, y *Word, n int) (c Word) {
for i := 0; i < n; i++ {
c, *z.at(i) = subWW_g(*x.at(i), *y.at(i), c)
}
- return;
+ return
}
func addVW_s(z, x *Word, y Word, n int) (c Word)
func addVW_g(z, x *Word, y Word, n int) (c Word) {
- c = y;
+ c = y
for i := 0; i < n; i++ {
c, *z.at(i) = addWW_g(*x.at(i), c, 0)
}
- return;
+ return
}
func subVW_s(z, x *Word, y Word, n int) (c Word)
func subVW_g(z, x *Word, y Word, n int) (c Word) {
- c = y;
+ c = y
for i := 0; i < n; i++ {
c, *z.at(i) = subWW_g(*x.at(i), c, 0)
}
- return;
+ return
}
func mulAddVWW_s(z, x *Word, y, r Word, n int) (c Word)
func mulAddVWW_g(z, x *Word, y, r Word, n int) (c Word) {
- c = r;
+ c = r
for i := 0; i < n; i++ {
c, *z.at(i) = mulAddWWW_g(*x.at(i), y, c)
}
- return;
+ return
}
func addMulVVW_s(z, x *Word, y Word, n int) (c Word)
func addMulVVW_g(z, x *Word, y Word, n int) (c Word) {
for i := 0; i < n; i++ {
- z1, z0 := mulAddWWW_g(*x.at(i), y, *z.at(i));
- c, *z.at(i) = addWW_g(z0, c, 0);
- c += z1;
+ z1, z0 := mulAddWWW_g(*x.at(i), y, *z.at(i))
+ c, *z.at(i) = addWW_g(z0, c, 0)
+ c += z1
}
- return;
+ return
}
func divWVW_s(z *Word, xn Word, x *Word, y Word, n int) (r Word)
func divWVW_g(z *Word, xn Word, x *Word, y Word, n int) (r Word) {
- r = xn;
+ r = xn
for i := n - 1; i >= 0; i-- {
*z.at(i), r = divWW_g(r, *x.at(i), y)
}
- return;
+ return
}
diff --git a/src/pkg/big/arith_test.go b/src/pkg/big/arith_test.go
index 41b91626a7..b0f6bf6f1f 100644
--- a/src/pkg/big/arith_test.go
+++ b/src/pkg/big/arith_test.go
@@ -9,7 +9,7 @@ import "testing"
type funWW func(x, y, c Word) (z1, z0 Word)
type argWW struct {
- x, y, c, z1, z0 Word;
+ x, y, c, z1, z0 Word
}
var sumWW = []argWW{
@@ -28,7 +28,7 @@ var sumWW = []argWW{
func testFunWW(t *testing.T, msg string, f funWW, a argWW) {
- z1, z0 := f(a.x, a.y, a.c);
+ z1, z0 := f(a.x, a.y, a.c)
if z1 != a.z1 || z0 != a.z0 {
t.Errorf("%s%+v\n\tgot z1:z0 = %#x:%#x; want %#x:%#x", msg, a, z1, z0, a.z1, a.z0)
}
@@ -37,17 +37,17 @@ func testFunWW(t *testing.T, msg string, f funWW, a argWW) {
func TestFunWW(t *testing.T) {
for _, a := range sumWW {
- arg := a;
- testFunWW(t, "addWW_g", addWW_g, arg);
+ arg := a
+ testFunWW(t, "addWW_g", addWW_g, arg)
- arg = argWW{a.y, a.x, a.c, a.z1, a.z0};
- testFunWW(t, "addWW_g symmetric", addWW_g, arg);
+ arg = argWW{a.y, a.x, a.c, a.z1, a.z0}
+ testFunWW(t, "addWW_g symmetric", addWW_g, arg)
- arg = argWW{a.z0, a.x, a.c, a.z1, a.y};
- testFunWW(t, "subWW_g", subWW_g, arg);
+ arg = argWW{a.z0, a.x, a.c, a.z1, a.y}
+ testFunWW(t, "subWW_g", subWW_g, arg)
- arg = argWW{a.z0, a.y, a.c, a.z1, a.x};
- testFunWW(t, "subWW_g symmetric", subWW_g, arg);
+ arg = argWW{a.z0, a.y, a.c, a.z1, a.x}
+ testFunWW(t, "subWW_g symmetric", subWW_g, arg)
}
}
@@ -56,14 +56,14 @@ func addr(x []Word) *Word {
if len(x) == 0 {
return nil
}
- return &x[0];
+ return &x[0]
}
type funVV func(z, x, y *Word, n int) (c Word)
type argVV struct {
- z, x, y []Word;
- c Word;
+ z, x, y []Word
+ c Word
}
var sumVV = []argVV{
@@ -80,13 +80,13 @@ var sumVV = []argVV{
func testFunVV(t *testing.T, msg string, f funVV, a argVV) {
- n := len(a.z);
- z := make([]Word, n);
- c := f(addr(z), addr(a.x), addr(a.y), n);
+ n := len(a.z)
+ z := make([]Word, n)
+ c := f(addr(z), addr(a.x), addr(a.y), n)
for i, zi := range z {
if zi != a.z[i] {
- t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i]);
- break;
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
}
}
if c != a.c {
@@ -97,30 +97,30 @@ func testFunVV(t *testing.T, msg string, f funVV, a argVV) {
func TestFunVV(t *testing.T) {
for _, a := range sumVV {
- arg := a;
- testFunVV(t, "addVV_g", addVV_g, arg);
- testFunVV(t, "addVV", addVV, arg);
+ arg := a
+ testFunVV(t, "addVV_g", addVV_g, arg)
+ testFunVV(t, "addVV", addVV, arg)
- arg = argVV{a.z, a.y, a.x, a.c};
- testFunVV(t, "addVV_g symmetric", addVV_g, arg);
- testFunVV(t, "addVV symmetric", addVV, arg);
+ arg = argVV{a.z, a.y, a.x, a.c}
+ testFunVV(t, "addVV_g symmetric", addVV_g, arg)
+ testFunVV(t, "addVV symmetric", addVV, arg)
- arg = argVV{a.x, a.z, a.y, a.c};
- testFunVV(t, "subVV_g", subVV_g, arg);
- testFunVV(t, "subVV", subVV, arg);
+ arg = argVV{a.x, a.z, a.y, a.c}
+ testFunVV(t, "subVV_g", subVV_g, arg)
+ testFunVV(t, "subVV", subVV, arg)
- arg = argVV{a.y, a.z, a.x, a.c};
- testFunVV(t, "subVV_g symmetric", subVV_g, arg);
- testFunVV(t, "subVV symmetric", subVV, arg);
+ arg = argVV{a.y, a.z, a.x, a.c}
+ testFunVV(t, "subVV_g symmetric", subVV_g, arg)
+ testFunVV(t, "subVV symmetric", subVV, arg)
}
}
type funVW func(z, x *Word, y Word, n int) (c Word)
type argVW struct {
- z, x []Word;
- y Word;
- c Word;
+ z, x []Word
+ y Word
+ c Word
}
var sumVW = []argVW{
@@ -149,13 +149,13 @@ var prodVW = []argVW{
func testFunVW(t *testing.T, msg string, f funVW, a argVW) {
- n := len(a.z);
- z := make([]Word, n);
- c := f(addr(z), addr(a.x), a.y, n);
+ n := len(a.z)
+ z := make([]Word, n)
+ c := f(addr(z), addr(a.x), a.y, n)
for i, zi := range z {
if zi != a.z[i] {
- t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i]);
- break;
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
}
}
if c != a.c {
@@ -166,22 +166,22 @@ func testFunVW(t *testing.T, msg string, f funVW, a argVW) {
func TestFunVW(t *testing.T) {
for _, a := range sumVW {
- arg := a;
- testFunVW(t, "addVW_g", addVW_g, arg);
- testFunVW(t, "addVW", addVW, arg);
+ arg := a
+ testFunVW(t, "addVW_g", addVW_g, arg)
+ testFunVW(t, "addVW", addVW, arg)
- arg = argVW{a.x, a.z, a.y, a.c};
- testFunVW(t, "subVW_g", subVW_g, arg);
- testFunVW(t, "subVW", subVW, arg);
+ arg = argVW{a.x, a.z, a.y, a.c}
+ testFunVW(t, "subVW_g", subVW_g, arg)
+ testFunVW(t, "subVW", subVW, arg)
}
}
type funVWW func(z, x *Word, y, r Word, n int) (c Word)
type argVWW struct {
- z, x []Word;
- y, r Word;
- c Word;
+ z, x []Word
+ y, r Word
+ c Word
}
var prodVWW = []argVWW{
@@ -212,13 +212,13 @@ var prodVWW = []argVWW{
func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) {
- n := len(a.z);
- z := make([]Word, n);
- c := f(addr(z), addr(a.x), a.y, a.r, n);
+ n := len(a.z)
+ z := make([]Word, n)
+ c := f(addr(z), addr(a.x), a.y, a.r, n)
for i, zi := range z {
if zi != a.z[i] {
- t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i]);
- break;
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
}
}
if c != a.c {
@@ -232,21 +232,21 @@ func testFunVWW(t *testing.T, msg string, f funVWW, a argVWW) {
type funWVW func(z *Word, xn Word, x *Word, y Word, n int) (r Word)
type argWVW struct {
- z []Word;
- xn Word;
- x []Word;
- y Word;
- r Word;
+ z []Word
+ xn Word
+ x []Word
+ y Word
+ r Word
}
func testFunWVW(t *testing.T, msg string, f funWVW, a argWVW) {
- n := len(a.z);
- z := make([]Word, n);
- r := f(addr(z), a.xn, addr(a.x), a.y, n);
+ n := len(a.z)
+ z := make([]Word, n)
+ r := f(addr(z), a.xn, addr(a.x), a.y, n)
for i, zi := range z {
if zi != a.z[i] {
- t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i]);
- break;
+ t.Errorf("%s%+v\n\tgot z[%d] = %#x; want %#x", msg, a, i, zi, a.z[i])
+ break
}
}
if r != a.r {
@@ -257,22 +257,22 @@ func testFunWVW(t *testing.T, msg string, f funWVW, a argWVW) {
func TestFunVWW(t *testing.T) {
for _, a := range prodVWW {
- arg := a;
- testFunVWW(t, "mulAddVWW_g", mulAddVWW_g, arg);
- testFunVWW(t, "mulAddVWW", mulAddVWW, arg);
+ arg := a
+ testFunVWW(t, "mulAddVWW_g", mulAddVWW_g, arg)
+ testFunVWW(t, "mulAddVWW", mulAddVWW, arg)
if a.y != 0 && a.r < a.y {
- arg := argWVW{a.x, a.c, a.z, a.y, a.r};
- testFunWVW(t, "divWVW_g", divWVW_g, arg);
- testFunWVW(t, "divWVW", divWVW, arg);
+ arg := argWVW{a.x, a.c, a.z, a.y, a.r}
+ testFunWVW(t, "divWVW_g", divWVW_g, arg)
+ testFunWVW(t, "divWVW", divWVW, arg)
}
}
}
type mulWWTest struct {
- x, y Word;
- q, r Word;
+ x, y Word
+ q, r Word
}
@@ -284,7 +284,7 @@ var mulWWTests = []mulWWTest{
func TestMulWW(t *testing.T) {
for i, test := range mulWWTests {
- q, r := mulWW_g(test.x, test.y);
+ q, r := mulWW_g(test.x, test.y)
if q != test.q || r != test.r {
t.Errorf("#%d got (%x, %x) want (%x, %x)", i, q, r, test.q, test.r)
}
@@ -293,8 +293,8 @@ func TestMulWW(t *testing.T) {
type mulAddWWWTest struct {
- x, y, c Word;
- q, r Word;
+ x, y, c Word
+ q, r Word
}
@@ -309,7 +309,7 @@ var mulAddWWWTests = []mulAddWWWTest{
func TestMulAddWWW(t *testing.T) {
for i, test := range mulAddWWWTests {
- q, r := mulAddWWW_g(test.x, test.y, test.c);
+ q, r := mulAddWWW_g(test.x, test.y, test.c)
if q != test.q || r != test.r {
t.Errorf("#%d got (%x, %x) want (%x, %x)", i, q, r, test.q, test.r)
}
diff --git a/src/pkg/big/int.go b/src/pkg/big/int.go
index 22c0eddff0..5a0f7c0dfd 100644
--- a/src/pkg/big/int.go
+++ b/src/pkg/big/int.go
@@ -9,32 +9,32 @@ package big
// An Int represents a signed multi-precision integer.
// The zero value for an Int represents the value 0.
type Int struct {
- neg bool; // sign
- abs []Word; // absolute value of the integer
+ neg bool // sign
+ abs []Word // absolute value of the integer
}
// New allocates and returns a new Int set to x.
func (z *Int) New(x int64) *Int {
- z.neg = false;
+ z.neg = false
if x < 0 {
- z.neg = true;
- x = -x;
+ z.neg = true
+ x = -x
}
- z.abs = newN(z.abs, uint64(x));
- return z;
+ z.abs = newN(z.abs, uint64(x))
+ return z
}
// NewInt allocates and returns a new Int set to x.
-func NewInt(x int64) *Int { return new(Int).New(x) }
+func NewInt(x int64) *Int { return new(Int).New(x) }
// Set sets z to x.
func (z *Int) Set(x *Int) *Int {
- z.neg = x.neg;
- z.abs = setN(z.abs, x.abs);
- return z;
+ z.neg = x.neg
+ z.abs = setN(z.abs, x.abs)
+ return z
}
@@ -43,23 +43,23 @@ func (z *Int) Add(x, y *Int) *Int {
if x.neg == y.neg {
// x + y == x + y
// (-x) + (-y) == -(x + y)
- z.neg = x.neg;
- z.abs = addNN(z.abs, x.abs, y.abs);
+ z.neg = x.neg
+ z.abs = addNN(z.abs, x.abs, y.abs)
} else {
// x + (-y) == x - y == -(y - x)
// (-x) + y == y - x == -(x - y)
if cmpNN(x.abs, y.abs) >= 0 {
- z.neg = x.neg;
- z.abs = subNN(z.abs, x.abs, y.abs);
+ z.neg = x.neg
+ z.abs = subNN(z.abs, x.abs, y.abs)
} else {
- z.neg = !x.neg;
- z.abs = subNN(z.abs, y.abs, x.abs);
+ z.neg = !x.neg
+ z.abs = subNN(z.abs, y.abs, x.abs)
}
}
if len(z.abs) == 0 {
- z.neg = false // 0 has no sign
+ z.neg = false // 0 has no sign
}
- return z;
+ return z
}
@@ -68,23 +68,23 @@ func (z *Int) Sub(x, y *Int) *Int {
if x.neg != y.neg {
// x - (-y) == x + y
// (-x) - y == -(x + y)
- z.neg = x.neg;
- z.abs = addNN(z.abs, x.abs, y.abs);
+ z.neg = x.neg
+ z.abs = addNN(z.abs, x.abs, y.abs)
} else {
// x - y == x - y == -(y - x)
// (-x) - (-y) == y - x == -(x - y)
if cmpNN(x.abs, y.abs) >= 0 {
- z.neg = x.neg;
- z.abs = subNN(z.abs, x.abs, y.abs);
+ z.neg = x.neg
+ z.abs = subNN(z.abs, x.abs, y.abs)
} else {
- z.neg = !x.neg;
- z.abs = subNN(z.abs, y.abs, x.abs);
+ z.neg = !x.neg
+ z.abs = subNN(z.abs, y.abs, x.abs)
}
}
if len(z.abs) == 0 {
- z.neg = false // 0 has no sign
+ z.neg = false // 0 has no sign
}
- return z;
+ return z
}
@@ -94,43 +94,43 @@ func (z *Int) Mul(x, y *Int) *Int {
// x * (-y) == -(x * y)
// (-x) * y == -(x * y)
// (-x) * (-y) == x * y
- z.abs = mulNN(z.abs, x.abs, y.abs);
- z.neg = len(z.abs) > 0 && x.neg != y.neg; // 0 has no sign
- return z;
+ z.abs = mulNN(z.abs, x.abs, y.abs)
+ z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
+ return z
}
// Div calculates q = (x-r)/y where 0 <= r < y. The receiver is set to q.
func (z *Int) Div(x, y *Int) (q, r *Int) {
- q = z;
- r = new(Int);
- div(q, r, x, y);
- return;
+ q = z
+ r = new(Int)
+ div(q, r, x, y)
+ return
}
// Mod calculates q = (x-r)/y and returns r.
func (z *Int) Mod(x, y *Int) (r *Int) {
- q := new(Int);
- r = z;
- div(q, r, x, y);
- return;
+ q := new(Int)
+ r = z
+ div(q, r, x, y)
+ return
}
func div(q, r, x, y *Int) {
- q.neg = x.neg != y.neg;
- r.neg = x.neg;
- q.abs, r.abs = divNN(q.abs, r.abs, x.abs, y.abs);
- return;
+ q.neg = x.neg != y.neg
+ r.neg = x.neg
+ q.abs, r.abs = divNN(q.abs, r.abs, x.abs, y.abs)
+ return
}
// Neg computes z = -x.
func (z *Int) Neg(x *Int) *Int {
- z.abs = setN(z.abs, x.abs);
- z.neg = len(z.abs) > 0 && !x.neg; // 0 has no sign
- return z;
+ z.abs = setN(z.abs, x.abs)
+ z.neg = len(z.abs) > 0 && !x.neg // 0 has no sign
+ return z
}
@@ -147,7 +147,7 @@ func (x *Int) Cmp(y *Int) (r int) {
// (-x) cmp (-y) == -(x cmp y)
switch {
case x.neg == y.neg:
- r = cmpNN(x.abs, y.abs);
+ r = cmpNN(x.abs, y.abs)
if x.neg {
r = -r
}
@@ -156,16 +156,16 @@ func (x *Int) Cmp(y *Int) (r int) {
default:
r = 1
}
- return;
+ return
}
func (z *Int) String() string {
- s := "";
+ s := ""
if z.neg {
s = "-"
}
- return s + stringN(z.abs, 10);
+ return s + stringN(z.abs, 10)
}
@@ -173,7 +173,7 @@ func (z *Int) String() string {
// If base is 0 then SetString attempts to detect the base by at the prefix of
// s. '0x' implies base 16, '0' implies base 8. Otherwise base 10 is assumed.
func (z *Int) SetString(s string, base int) (*Int, bool) {
- var scanned int;
+ var scanned int
if base == 1 || base > 16 {
goto Error
@@ -184,83 +184,83 @@ func (z *Int) SetString(s string, base int) (*Int, bool) {
}
if s[0] == '-' {
- z.neg = true;
- s = s[1:];
+ z.neg = true
+ s = s[1:]
} else {
z.neg = false
}
- z.abs, _, scanned = scanN(z.abs, s, base);
+ z.abs, _, scanned = scanN(z.abs, s, base)
if scanned != len(s) {
goto Error
}
- return z, true;
+ return z, true
Error:
- z.neg = false;
- z.abs = nil;
- return nil, false;
+ z.neg = false
+ z.abs = nil
+ return nil, false
}
// SetBytes interprets b as the bytes of a big-endian, unsigned integer and
// sets x to that value.
func (z *Int) SetBytes(b []byte) *Int {
- s := int(_S);
- z.abs = makeN(z.abs, (len(b)+s-1)/s, false);
- z.neg = false;
+ s := int(_S)
+ z.abs = makeN(z.abs, (len(b)+s-1)/s, false)
+ z.neg = false
- j := 0;
+ j := 0
for len(b) >= s {
- var w Word;
+ var w Word
for i := s; i > 0; i-- {
- w <<= 8;
- w |= Word(b[len(b)-i]);
+ w <<= 8
+ w |= Word(b[len(b)-i])
}
- z.abs[j] = w;
- j++;
- b = b[0 : len(b)-s];
+ z.abs[j] = w
+ j++
+ b = b[0 : len(b)-s]
}
if len(b) > 0 {
- var w Word;
+ var w Word
for i := len(b); i > 0; i-- {
- w <<= 8;
- w |= Word(b[len(b)-i]);
+ w <<= 8
+ w |= Word(b[len(b)-i])
}
- z.abs[j] = w;
+ z.abs[j] = w
}
- z.abs = normN(z.abs);
+ z.abs = normN(z.abs)
- return z;
+ return z
}
// Bytes returns the absolute value of x as a big-endian byte array.
func (z *Int) Bytes() []byte {
- s := int(_S);
- b := make([]byte, len(z.abs)*s);
+ s := int(_S)
+ b := make([]byte, len(z.abs)*s)
for i, w := range z.abs {
- wordBytes := b[(len(z.abs)-i-1)*s : (len(z.abs)-i)*s];
+ wordBytes := b[(len(z.abs)-i-1)*s : (len(z.abs)-i)*s]
for j := s - 1; j >= 0; j-- {
- wordBytes[j] = byte(w);
- w >>= 8;
+ wordBytes[j] = byte(w)
+ w >>= 8
}
}
- i := 0;
+ i := 0
for i < len(b) && b[i] == 0 {
i++
}
- return b[i:];
+ return b[i:]
}
@@ -271,7 +271,7 @@ func (z *Int) Len() int {
return 0
}
- return len(z.abs)*_W - int(leadingZeros(z.abs[len(z.abs)-1]));
+ return len(z.abs)*_W - int(leadingZeros(z.abs[len(z.abs)-1]))
}
@@ -279,19 +279,19 @@ func (z *Int) Len() int {
// See Knuth, volume 2, section 4.6.3.
func (z *Int) Exp(x, y, m *Int) *Int {
if y.neg || len(y.abs) == 0 {
- z.New(1);
- z.neg = x.neg;
- return z;
+ z.New(1)
+ z.neg = x.neg
+ return z
}
- var mWords []Word;
+ var mWords []Word
if m != nil {
mWords = m.abs
}
- z.abs = expNNN(z.abs, x.abs, y.abs, mWords);
- z.neg = x.neg && y.abs[0]&1 == 1;
- return z;
+ z.abs = expNNN(z.abs, x.abs, y.abs, mWords)
+ z.neg = x.neg && y.abs[0]&1 == 1
+ return z
}
@@ -301,44 +301,44 @@ func (z *Int) Exp(x, y, m *Int) *Int {
// If either a or b is not positive, GcdInt sets d = x = y = 0.
func GcdInt(d, x, y, a, b *Int) {
if a.neg || b.neg {
- d.New(0);
+ d.New(0)
if x != nil {
x.New(0)
}
if y != nil {
y.New(0)
}
- return;
+ return
}
- A := new(Int).Set(a);
- B := new(Int).Set(b);
+ A := new(Int).Set(a)
+ B := new(Int).Set(b)
- X := new(Int);
- Y := new(Int).New(1);
+ X := new(Int)
+ Y := new(Int).New(1)
- lastX := new(Int).New(1);
- lastY := new(Int);
+ lastX := new(Int).New(1)
+ lastY := new(Int)
- q := new(Int);
- temp := new(Int);
+ q := new(Int)
+ temp := new(Int)
for len(B.abs) > 0 {
- q, r := q.Div(A, B);
+ q, r := q.Div(A, B)
- A, B = B, r;
+ A, B = B, r
- temp.Set(X);
- X.Mul(X, q);
- X.neg = !X.neg;
- X.Add(X, lastX);
- lastX.Set(temp);
+ temp.Set(X)
+ X.Mul(X, q)
+ X.neg = !X.neg
+ X.Add(X, lastX)
+ lastX.Set(temp)
- temp.Set(Y);
- Y.Mul(Y, q);
- Y.neg = !Y.neg;
- Y.Add(Y, lastY);
- lastY.Set(temp);
+ temp.Set(Y)
+ Y.Mul(Y, q)
+ Y.neg = !Y.neg
+ Y.Add(Y, lastY)
+ lastY.Set(temp)
}
if x != nil {
@@ -349,22 +349,22 @@ func GcdInt(d, x, y, a, b *Int) {
*y = *lastY
}
- *d = *A;
+ *d = *A
}
// ProbablyPrime performs n Miller-Rabin tests to check whether z is prime.
// If it returns true, z is prime with probability 1 - 1/4^n.
// If it returns false, z is not prime.
-func ProbablyPrime(z *Int, reps int) bool { return !z.neg && probablyPrime(z.abs, reps) }
+func ProbablyPrime(z *Int, reps int) bool { return !z.neg && probablyPrime(z.abs, reps) }
// Rsh sets z = x >> s and returns z.
func (z *Int) Rsh(x *Int, n int) *Int {
- removedWords := n / _W;
- z.abs = makeN(z.abs, len(x.abs)-removedWords, false);
- z.neg = x.neg;
- shiftRight(z.abs, x.abs[removedWords:], n%_W);
- z.abs = normN(z.abs);
- return z;
+ removedWords := n / _W
+ z.abs = makeN(z.abs, len(x.abs)-removedWords, false)
+ z.neg = x.neg
+ shiftRight(z.abs, x.abs[removedWords:], n%_W)
+ z.abs = normN(z.abs)
+ return z
}
diff --git a/src/pkg/big/int_test.go b/src/pkg/big/int_test.go
index e5ed221afc..b2c33fcc45 100644
--- a/src/pkg/big/int_test.go
+++ b/src/pkg/big/int_test.go
@@ -5,21 +5,21 @@
package big
import (
- "bytes";
- "encoding/hex";
- "testing";
- "testing/quick";
+ "bytes"
+ "encoding/hex"
+ "testing"
+ "testing/quick"
)
func newZ(x int64) *Int {
- var z Int;
- return z.New(x);
+ var z Int
+ return z.New(x)
}
type funZZ func(z, x, y *Int) *Int
type argZZ struct {
- z, x, y *Int;
+ z, x, y *Int
}
@@ -44,8 +44,8 @@ var prodZZ = []argZZ{
func TestSetZ(t *testing.T) {
for _, a := range sumZZ {
- var z Int;
- z.Set(a.z);
+ var z Int
+ z.Set(a.z)
if (&z).Cmp(a.z) != 0 {
t.Errorf("got z = %v; want %v", z, a.z)
}
@@ -54,8 +54,8 @@ func TestSetZ(t *testing.T) {
func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) {
- var z Int;
- f(&z, a.x, a.y);
+ var z Int
+ f(&z, a.x, a.y)
if (&z).Cmp(a.z) != 0 {
t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z)
}
@@ -63,32 +63,32 @@ func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) {
func TestSumZZ(t *testing.T) {
- AddZZ := func(z, x, y *Int) *Int { return z.Add(x, y) };
- SubZZ := func(z, x, y *Int) *Int { return z.Sub(x, y) };
+ AddZZ := func(z, x, y *Int) *Int { return z.Add(x, y) }
+ SubZZ := func(z, x, y *Int) *Int { return z.Sub(x, y) }
for _, a := range sumZZ {
- arg := a;
- testFunZZ(t, "AddZZ", AddZZ, arg);
+ arg := a
+ testFunZZ(t, "AddZZ", AddZZ, arg)
- arg = argZZ{a.z, a.y, a.x};
- testFunZZ(t, "AddZZ symmetric", AddZZ, arg);
+ arg = argZZ{a.z, a.y, a.x}
+ testFunZZ(t, "AddZZ symmetric", AddZZ, arg)
- arg = argZZ{a.x, a.z, a.y};
- testFunZZ(t, "SubZZ", SubZZ, arg);
+ arg = argZZ{a.x, a.z, a.y}
+ testFunZZ(t, "SubZZ", SubZZ, arg)
- arg = argZZ{a.y, a.z, a.x};
- testFunZZ(t, "SubZZ symmetric", SubZZ, arg);
+ arg = argZZ{a.y, a.z, a.x}
+ testFunZZ(t, "SubZZ symmetric", SubZZ, arg)
}
}
func TestProdZZ(t *testing.T) {
- MulZZ := func(z, x, y *Int) *Int { return z.Mul(x, y) };
+ MulZZ := func(z, x, y *Int) *Int { return z.Mul(x, y) }
for _, a := range prodZZ {
- arg := a;
- testFunZZ(t, "MulZZ", MulZZ, arg);
+ arg := a
+ testFunZZ(t, "MulZZ", MulZZ, arg)
- arg = argZZ{a.z, a.y, a.x};
- testFunZZ(t, "MulZZ symmetric", MulZZ, arg);
+ arg = argZZ{a.z, a.y, a.x}
+ testFunZZ(t, "MulZZ symmetric", MulZZ, arg)
}
}
@@ -106,20 +106,20 @@ var facts = map[int]string{
func fact(n int) *Int {
- var z Int;
- z.New(1);
+ var z Int
+ z.New(1)
for i := 2; i <= n; i++ {
- var t Int;
- t.New(int64(i));
- z.Mul(&z, &t);
+ var t Int
+ t.New(int64(i))
+ z.Mul(&z, &t)
}
- return &z;
+ return &z
}
func TestFact(t *testing.T) {
for n, s := range facts {
- f := fact(n).String();
+ f := fact(n).String()
if f != s {
t.Errorf("%d! = %s; want %s", n, f, s)
}
@@ -128,10 +128,10 @@ func TestFact(t *testing.T) {
type fromStringTest struct {
- in string;
- base int;
- out int64;
- ok bool;
+ in string
+ base int
+ out int64
+ ok bool
}
@@ -156,10 +156,10 @@ var fromStringTests = []fromStringTest{
func TestSetString(t *testing.T) {
for i, test := range fromStringTests {
- n, ok := new(Int).SetString(test.in, test.base);
+ n, ok := new(Int).SetString(test.in, test.base)
if ok != test.ok {
- t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok);
- continue;
+ t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
+ continue
}
if !ok {
continue
@@ -173,8 +173,8 @@ func TestSetString(t *testing.T) {
type divSignsTest struct {
- x, y int64;
- q, r int64;
+ x, y int64
+ q, r int64
}
@@ -190,11 +190,11 @@ var divSignsTests = []divSignsTest{
func TestDivSigns(t *testing.T) {
for i, test := range divSignsTests {
- x := new(Int).New(test.x);
- y := new(Int).New(test.y);
- q, r := new(Int).Div(x, y);
- expectedQ := new(Int).New(test.q);
- expectedR := new(Int).New(test.r);
+ x := new(Int).New(test.x)
+ y := new(Int).New(test.y)
+ q, r := new(Int).Div(x, y)
+ expectedQ := new(Int).New(test.q)
+ expectedR := new(Int).New(test.r)
if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 {
t.Errorf("#%d: got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
@@ -204,8 +204,8 @@ func TestDivSigns(t *testing.T) {
func checkSetBytes(b []byte) bool {
- hex1 := hex.EncodeToString(new(Int).SetBytes(b).Bytes());
- hex2 := hex.EncodeToString(b);
+ hex1 := hex.EncodeToString(new(Int).SetBytes(b).Bytes())
+ hex2 := hex.EncodeToString(b)
for len(hex1) < len(hex2) {
hex1 = "0" + hex1
@@ -215,12 +215,12 @@ func checkSetBytes(b []byte) bool {
hex2 = "0" + hex2
}
- return hex1 == hex2;
+ return hex1 == hex2
}
func TestSetBytes(t *testing.T) {
- err := quick.Check(checkSetBytes, nil);
+ err := quick.Check(checkSetBytes, nil)
if err != nil {
t.Error(err)
}
@@ -228,13 +228,13 @@ func TestSetBytes(t *testing.T) {
func checkBytes(b []byte) bool {
- b2 := new(Int).SetBytes(b).Bytes();
- return bytes.Compare(b, b2) == 0;
+ b2 := new(Int).SetBytes(b).Bytes()
+ return bytes.Compare(b, b2) == 0
}
func TestBytes(t *testing.T) {
- err := quick.Check(checkSetBytes, nil);
+ err := quick.Check(checkSetBytes, nil)
if err != nil {
t.Error(err)
}
@@ -242,30 +242,30 @@ func TestBytes(t *testing.T) {
func checkDiv(x, y []byte) bool {
- u := new(Int).SetBytes(x);
- v := new(Int).SetBytes(y);
+ u := new(Int).SetBytes(x)
+ v := new(Int).SetBytes(y)
if len(v.abs) == 0 {
return true
}
- q, r := new(Int).Div(u, v);
+ q, r := new(Int).Div(u, v)
if r.Cmp(v) >= 0 {
return false
}
- uprime := new(Int).Set(q);
- uprime.Mul(uprime, v);
- uprime.Add(uprime, r);
+ uprime := new(Int).Set(q)
+ uprime.Mul(uprime, v)
+ uprime.Add(uprime, r)
- return uprime.Cmp(u) == 0;
+ return uprime.Cmp(u) == 0
}
type divTest struct {
- x, y string;
- q, r string;
+ x, y string
+ q, r string
}
@@ -286,18 +286,18 @@ var divTests = []divTest{
func TestDiv(t *testing.T) {
- err := quick.Check(checkDiv, nil);
+ err := quick.Check(checkDiv, nil)
if err != nil {
t.Error(err)
}
for i, test := range divTests {
- x, _ := new(Int).SetString(test.x, 10);
- y, _ := new(Int).SetString(test.y, 10);
- expectedQ, _ := new(Int).SetString(test.q, 10);
- expectedR, _ := new(Int).SetString(test.r, 10);
+ x, _ := new(Int).SetString(test.x, 10)
+ y, _ := new(Int).SetString(test.y, 10)
+ expectedQ, _ := new(Int).SetString(test.q, 10)
+ expectedR, _ := new(Int).SetString(test.r, 10)
- q, r := new(Int).Div(x, y);
+ q, r := new(Int).Div(x, y)
if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 {
t.Errorf("#%d got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
@@ -310,14 +310,14 @@ func TestDivStepD6(t *testing.T) {
// See Knuth, Volume 2, section 4.3.1, exercise 21. This code exercises
// a code path which only triggers 1 in 10^{-19} cases.
- u := &Int{false, []Word{0, 0, 1 + 1<<(_W-1), _M ^ (1 << (_W - 1))}};
- v := &Int{false, []Word{5, 2 + 1<<(_W-1), 1 << (_W - 1)}};
+ u := &Int{false, []Word{0, 0, 1 + 1<<(_W-1), _M ^ (1 << (_W - 1))}}
+ v := &Int{false, []Word{5, 2 + 1<<(_W-1), 1 << (_W - 1)}}
- q, r := new(Int).Div(u, v);
- const expectedQ64 = "18446744073709551613";
- const expectedR64 = "3138550867693340382088035895064302439801311770021610913807";
- const expectedQ32 = "4294967293";
- const expectedR32 = "39614081266355540837921718287";
+ q, r := new(Int).Div(u, v)
+ const expectedQ64 = "18446744073709551613"
+ const expectedR64 = "3138550867693340382088035895064302439801311770021610913807"
+ const expectedQ32 = "4294967293"
+ const expectedR32 = "39614081266355540837921718287"
if q.String() != expectedQ64 && q.String() != expectedQ32 ||
r.String() != expectedR64 && r.String() != expectedR32 {
t.Errorf("got (%s, %s) want (%s, %s) or (%s, %s)", q, r, expectedQ64, expectedR64, expectedQ32, expectedR32)
@@ -326,8 +326,8 @@ func TestDivStepD6(t *testing.T) {
type lenTest struct {
- in string;
- out int;
+ in string
+ out int
}
@@ -346,10 +346,10 @@ var lenTests = []lenTest{
func TestLen(t *testing.T) {
for i, test := range lenTests {
- n, ok := new(Int).SetString(test.in, 0);
+ n, ok := new(Int).SetString(test.in, 0)
if !ok {
- t.Errorf("#%d test input invalid: %s", i, test.in);
- continue;
+ t.Errorf("#%d test input invalid: %s", i, test.in)
+ continue
}
if n.Len() != test.out {
@@ -360,8 +360,8 @@ func TestLen(t *testing.T) {
type expTest struct {
- x, y, m string;
- out string;
+ x, y, m string
+ out string
}
@@ -388,12 +388,12 @@ var expTests = []expTest{
func TestExp(t *testing.T) {
for i, test := range expTests {
- x, ok1 := new(Int).SetString(test.x, 0);
- y, ok2 := new(Int).SetString(test.y, 0);
- out, ok3 := new(Int).SetString(test.out, 0);
+ x, ok1 := new(Int).SetString(test.x, 0)
+ y, ok2 := new(Int).SetString(test.y, 0)
+ out, ok3 := new(Int).SetString(test.out, 0)
- var ok4 bool;
- var m *Int;
+ var ok4 bool
+ var m *Int
if len(test.m) == 0 {
m, ok4 = nil, true
@@ -402,11 +402,11 @@ func TestExp(t *testing.T) {
}
if !ok1 || !ok2 || !ok3 || !ok4 {
- t.Errorf("#%d error in input", i);
- continue;
+ t.Errorf("#%d error in input", i)
+ continue
}
- z := new(Int).Exp(x, y, m);
+ z := new(Int).Exp(x, y, m)
if z.Cmp(out) != 0 {
t.Errorf("#%d got %s want %s", i, z, out)
}
@@ -415,25 +415,25 @@ func TestExp(t *testing.T) {
func checkGcd(aBytes, bBytes []byte) bool {
- a := new(Int).SetBytes(aBytes);
- b := new(Int).SetBytes(bBytes);
+ a := new(Int).SetBytes(aBytes)
+ b := new(Int).SetBytes(bBytes)
- x := new(Int);
- y := new(Int);
- d := new(Int);
+ x := new(Int)
+ y := new(Int)
+ d := new(Int)
- GcdInt(d, x, y, a, b);
- x.Mul(x, a);
- y.Mul(y, b);
- x.Add(x, y);
+ GcdInt(d, x, y, a, b)
+ x.Mul(x, a)
+ y.Mul(y, b)
+ x.Add(x, y)
- return x.Cmp(d) == 0;
+ return x.Cmp(d) == 0
}
type gcdTest struct {
- a, b int64;
- d, x, y int64;
+ a, b int64
+ d, x, y int64
}
@@ -444,18 +444,18 @@ var gcdTests = []gcdTest{
func TestGcd(t *testing.T) {
for i, test := range gcdTests {
- a := new(Int).New(test.a);
- b := new(Int).New(test.b);
+ a := new(Int).New(test.a)
+ b := new(Int).New(test.b)
- x := new(Int);
- y := new(Int);
- d := new(Int);
+ x := new(Int)
+ y := new(Int)
+ d := new(Int)
- expectedX := new(Int).New(test.x);
- expectedY := new(Int).New(test.y);
- expectedD := new(Int).New(test.d);
+ expectedX := new(Int).New(test.x)
+ expectedY := new(Int).New(test.y)
+ expectedD := new(Int).New(test.d)
- GcdInt(d, x, y, a, b);
+ GcdInt(d, x, y, a, b)
if expectedX.Cmp(x) != 0 ||
expectedY.Cmp(y) != 0 ||
@@ -464,7 +464,7 @@ func TestGcd(t *testing.T) {
}
}
- quick.Check(checkGcd, nil);
+ quick.Check(checkGcd, nil)
}
@@ -494,14 +494,14 @@ var composites = []string{
func TestProbablyPrime(t *testing.T) {
for i, s := range primes {
- p, _ := new(Int).SetString(s, 10);
+ p, _ := new(Int).SetString(s, 10)
if !ProbablyPrime(p, 20) {
t.Errorf("#%d prime found to be non-prime", i)
}
}
for i, s := range composites {
- c, _ := new(Int).SetString(s, 10);
+ c, _ := new(Int).SetString(s, 10)
if ProbablyPrime(c, 20) {
t.Errorf("#%d composite found to be prime", i)
}
@@ -510,9 +510,9 @@ func TestProbablyPrime(t *testing.T) {
type rshTest struct {
- in string;
- shift int;
- out string;
+ in string
+ shift int
+ out string
}
@@ -540,9 +540,9 @@ var rshTests = []rshTest{
func TestRsh(t *testing.T) {
for i, test := range rshTests {
- in, _ := new(Int).SetString(test.in, 10);
- expected, _ := new(Int).SetString(test.out, 10);
- out := new(Int).Rsh(in, test.shift);
+ in, _ := new(Int).SetString(test.in, 10)
+ expected, _ := new(Int).SetString(test.out, 10)
+ out := new(Int).Rsh(in, test.shift)
if out.Cmp(expected) != 0 {
t.Errorf("#%d got %s want %s", i, out, expected)
diff --git a/src/pkg/big/nat.go b/src/pkg/big/nat.go
index 0b7c184283..877bc98112 100644
--- a/src/pkg/big/nat.go
+++ b/src/pkg/big/nat.go
@@ -38,31 +38,31 @@ import "rand"
// - decide if type 'nat' should be exported
func normN(z []Word) []Word {
- i := len(z);
+ i := len(z)
for i > 0 && z[i-1] == 0 {
i--
}
- z = z[0:i];
- return z;
+ z = z[0:i]
+ return z
}
func makeN(z []Word, m int, clear bool) []Word {
if len(z) > m {
- z = z[0:m]; // reuse z - has at least one extra word for a carry, if any
+ z = z[0:m] // reuse z - has at least one extra word for a carry, if any
if clear {
for i := range z {
z[i] = 0
}
}
- return z;
+ return z
}
- c := 4; // minimum capacity
+ c := 4 // minimum capacity
if m > c {
c = m
}
- return make([]Word, m, c+1); // +1: extra word for a carry, if any
+ return make([]Word, m, c+1) // +1: extra word for a carry, if any
}
@@ -73,40 +73,40 @@ func newN(z []Word, x uint64) []Word {
// single-digit values
if x == uint64(Word(x)) {
- z = makeN(z, 1, false);
- z[0] = Word(x);
- return z;
+ z = makeN(z, 1, false)
+ z[0] = Word(x)
+ return z
}
// compute number of words n required to represent x
- n := 0;
+ n := 0
for t := x; t > 0; t >>= _W {
n++
}
// split x into n words
- z = makeN(z, n, false);
+ z = makeN(z, n, false)
for i := 0; i < n; i++ {
- z[i] = Word(x & _M);
- x >>= _W;
+ z[i] = Word(x & _M)
+ x >>= _W
}
- return z;
+ return z
}
func setN(z, x []Word) []Word {
- z = makeN(z, len(x), false);
+ z = makeN(z, len(x), false)
for i, d := range x {
z[i] = d
}
- return z;
+ return z
}
func addNN(z, x, y []Word) []Word {
- m := len(x);
- n := len(y);
+ m := len(x)
+ n := len(y)
switch {
case m < n:
@@ -120,23 +120,23 @@ func addNN(z, x, y []Word) []Word {
}
// m > 0
- z = makeN(z, m, false);
- c := addVV(&z[0], &x[0], &y[0], n);
+ z = makeN(z, m, false)
+ c := addVV(&z[0], &x[0], &y[0], n)
if m > n {
c = addVW(&z[n], &x[n], c, m-n)
}
if c > 0 {
- z = z[0 : m+1];
- z[m] = c;
+ z = z[0 : m+1]
+ z[m] = c
}
- return z;
+ return z
}
func subNN(z, x, y []Word) []Word {
- m := len(x);
- n := len(y);
+ m := len(x)
+ n := len(y)
switch {
case m < n:
@@ -150,23 +150,23 @@ func subNN(z, x, y []Word) []Word {
}
// m > 0
- z = makeN(z, m, false);
- c := subVV(&z[0], &x[0], &y[0], n);
+ z = makeN(z, m, false)
+ c := subVV(&z[0], &x[0], &y[0], n)
if m > n {
c = subVW(&z[n], &x[n], c, m-n)
}
if c != 0 {
panic("underflow")
}
- z = normN(z);
+ z = normN(z)
- return z;
+ return z
}
func cmpNN(x, y []Word) (r int) {
- m := len(x);
- n := len(y);
+ m := len(x)
+ n := len(y)
if m != n || m == 0 {
switch {
case m < n:
@@ -174,10 +174,10 @@ func cmpNN(x, y []Word) (r int) {
case m > n:
r = 1
}
- return;
+ return
}
- i := m - 1;
+ i := m - 1
for i > 0 && x[i] == y[i] {
i--
}
@@ -188,31 +188,31 @@ func cmpNN(x, y []Word) (r int) {
case x[i] > y[i]:
r = 1
}
- return;
+ return
}
func mulAddNWW(z, x []Word, y, r Word) []Word {
- m := len(x);
+ m := len(x)
if m == 0 || y == 0 {
- return newN(z, uint64(r)) // result is r
+ return newN(z, uint64(r)) // result is r
}
// m > 0
- z = makeN(z, m, false);
- c := mulAddVWW(&z[0], &x[0], y, r, m);
+ z = makeN(z, m, false)
+ c := mulAddVWW(&z[0], &x[0], y, r, m)
if c > 0 {
- z = z[0 : m+1];
- z[m] = c;
+ z = z[0 : m+1]
+ z[m] = c
}
- return z;
+ return z
}
func mulNN(z, x, y []Word) []Word {
- m := len(x);
- n := len(y);
+ m := len(x)
+ n := len(y)
switch {
case m < n:
@@ -224,39 +224,39 @@ func mulNN(z, x, y []Word) []Word {
}
// m >= n && m > 1 && n > 1
- z = makeN(z, m+n, true);
+ z = makeN(z, m+n, true)
if &z[0] == &x[0] || &z[0] == &y[0] {
- z = makeN(nil, m+n, true) // z is an alias for x or y - cannot reuse
+ z = makeN(nil, m+n, true) // z is an alias for x or y - cannot reuse
}
for i := 0; i < n; i++ {
if f := y[i]; f != 0 {
z[m+i] = addMulVVW(&z[i], &x[0], f, m)
}
}
- z = normN(z);
+ z = normN(z)
- return z;
+ return z
}
// q = (x-r)/y, with 0 <= r < y
func divNW(z, x []Word, y Word) (q []Word, r Word) {
- m := len(x);
+ m := len(x)
switch {
case y == 0:
panic("division by zero")
case y == 1:
- q = setN(z, x); // result is x
- return;
+ q = setN(z, x) // result is x
+ return
case m == 0:
- q = setN(z, nil); // result is 0
- return;
+ q = setN(z, nil) // result is 0
+ return
}
// m > 0
- z = makeN(z, m, false);
- r = divWVW(&z[0], 0, &x[0], y, m);
- q = normN(z);
- return;
+ z = makeN(z, m, false)
+ r = divWVW(&z[0], 0, &x[0], y, m)
+ q = normN(z)
+ return
}
@@ -266,25 +266,25 @@ func divNN(z, z2, u, v []Word) (q, r []Word) {
}
if cmpNN(u, v) < 0 {
- q = makeN(z, 0, false);
- r = setN(z2, u);
- return;
+ q = makeN(z, 0, false)
+ r = setN(z2, u)
+ return
}
if len(v) == 1 {
- var rprime Word;
- q, rprime = divNW(z, u, v[0]);
+ var rprime Word
+ q, rprime = divNW(z, u, v[0])
if rprime > 0 {
- r = makeN(z2, 1, false);
- r[0] = rprime;
+ r = makeN(z2, 1, false)
+ r[0] = rprime
} else {
r = makeN(z2, 0, false)
}
- return;
+ return
}
- q, r = divLargeNN(z, z2, u, v);
- return;
+ q, r = divLargeNN(z, z2, u, v)
+ return
}
@@ -294,63 +294,63 @@ func divNN(z, z2, u, v []Word) (q, r []Word) {
// len(v) >= 2
// len(uIn) >= len(v)
func divLargeNN(z, z2, uIn, v []Word) (q, r []Word) {
- n := len(v);
- m := len(uIn) - len(v);
+ n := len(v)
+ m := len(uIn) - len(v)
- u := makeN(z2, len(uIn)+1, false);
- qhatv := make([]Word, len(v)+1);
- q = makeN(z, m+1, false);
+ u := makeN(z2, len(uIn)+1, false)
+ qhatv := make([]Word, len(v)+1)
+ q = makeN(z, m+1, false)
// D1.
- shift := leadingZeroBits(v[n-1]);
- shiftLeft(v, v, shift);
- shiftLeft(u, uIn, shift);
- u[len(uIn)] = uIn[len(uIn)-1] >> (_W - uint(shift));
+ shift := leadingZeroBits(v[n-1])
+ shiftLeft(v, v, shift)
+ shiftLeft(u, uIn, shift)
+ u[len(uIn)] = uIn[len(uIn)-1] >> (_W - uint(shift))
// D2.
for j := m; j >= 0; j-- {
// D3.
- var qhat Word;
+ var qhat Word
if u[j+n] == v[n-1] {
qhat = _B - 1
} else {
- var rhat Word;
- qhat, rhat = divWW_g(u[j+n], u[j+n-1], v[n-1]);
+ var rhat Word
+ qhat, rhat = divWW_g(u[j+n], u[j+n-1], v[n-1])
// x1 | x2 = q̂v_{n-2}
- x1, x2 := mulWW_g(qhat, v[n-2]);
+ x1, x2 := mulWW_g(qhat, v[n-2])
// test if q̂v_{n-2} > br̂ + u_{j+n-2}
for greaterThan(x1, x2, rhat, u[j+n-2]) {
- qhat--;
- prevRhat := rhat;
- rhat += v[n-1];
+ qhat--
+ prevRhat := rhat
+ rhat += v[n-1]
// v[n-1] >= 0, so this tests for overflow.
if rhat < prevRhat {
break
}
- x1, x2 = mulWW_g(qhat, v[n-2]);
+ x1, x2 = mulWW_g(qhat, v[n-2])
}
}
// D4.
- qhatv[len(v)] = mulAddVWW(&qhatv[0], &v[0], qhat, 0, len(v));
+ qhatv[len(v)] = mulAddVWW(&qhatv[0], &v[0], qhat, 0, len(v))
- c := subVV(&u[j], &u[j], &qhatv[0], len(qhatv));
+ c := subVV(&u[j], &u[j], &qhatv[0], len(qhatv))
if c != 0 {
- c := addVV(&u[j], &u[j], &v[0], len(v));
- u[j+len(v)] += c;
- qhat--;
+ c := addVV(&u[j], &u[j], &v[0], len(v))
+ u[j+len(v)] += c
+ qhat--
}
- q[j] = qhat;
+ q[j] = qhat
}
- q = normN(q);
- shiftRight(u, u, shift);
- shiftRight(v, v, shift);
- r = normN(u);
+ q = normN(q)
+ shiftRight(u, u, shift)
+ shiftRight(v, v, shift)
+ r = normN(u)
- return q, r;
+ return q, r
}
@@ -358,11 +358,11 @@ func divLargeNN(z, z2, uIn, v []Word) (q, r []Word) {
// The result is the integer n for which 2^n <= x < 2^(n+1).
// If x == 0, the result is -1.
func log2(x Word) int {
- n := 0;
+ n := 0
for ; x > 0; x >>= 1 {
n++
}
- return n - 1;
+ return n - 1
}
@@ -370,16 +370,16 @@ func log2(x Word) int {
// The result is the integer n for which 2^n <= x < 2^(n+1).
// If x == 0, the result is -1.
func log2N(x []Word) int {
- m := len(x);
+ m := len(x)
if m > 0 {
return (m-1)*_W + log2(x[m-1])
}
- return -1;
+ return -1
}
func hexValue(ch byte) int {
- var d byte;
+ var d byte
switch {
case '0' <= ch && ch <= '9':
d = ch - '0'
@@ -390,7 +390,7 @@ func hexValue(ch byte) int {
default:
return -1
}
- return int(d);
+ return int(d)
}
@@ -406,16 +406,16 @@ func hexValue(ch byte) int {
//
func scanN(z []Word, s string, base int) ([]Word, int, int) {
// determine base if necessary
- i, n := 0, len(s);
+ i, n := 0, len(s)
if base == 0 {
- base = 10;
+ base = 10
if n > 0 && s[0] == '0' {
if n > 1 && (s[1] == 'x' || s[1] == 'X') {
if n == 2 {
// Reject a string which is just '0x' as nonsense.
return nil, 0, 0
}
- base, i = 16, 2;
+ base, i = 16, 2
} else {
base, i = 8, 1
}
@@ -426,9 +426,9 @@ func scanN(z []Word, s string, base int) ([]Word, int, int) {
}
// convert string
- z = makeN(z, len(z), false);
+ z = makeN(z, len(z), false)
for ; i < n; i++ {
- d := hexValue(s[i]);
+ d := hexValue(s[i])
if 0 <= d && d < base {
z = mulAddNWW(z, z, Word(base), Word(d))
} else {
@@ -436,7 +436,7 @@ func scanN(z []Word, s string, base int) ([]Word, int, int) {
}
}
- return z, base, i;
+ return z, base, i
}
@@ -453,40 +453,40 @@ func stringN(x []Word, base int) string {
}
// allocate buffer for conversion
- i := (log2N(x)+1)/log2(Word(base)) + 1; // +1: round up
- s := make([]byte, i);
+ i := (log2N(x)+1)/log2(Word(base)) + 1 // +1: round up
+ s := make([]byte, i)
// don't destroy x
- q := setN(nil, x);
+ q := setN(nil, x)
// convert
for len(q) > 0 {
- i--;
- var r Word;
- q, r = divNW(q, q, Word(base));
- s[i] = "0123456789abcdef"[r];
+ i--
+ var r Word
+ q, r = divNW(q, q, Word(base))
+ s[i] = "0123456789abcdef"[r]
}
- return string(s[i:]);
+ return string(s[i:])
}
// leadingZeroBits returns the number of leading zero bits in x.
func leadingZeroBits(x Word) int {
- c := 0;
+ c := 0
if x < 1<<(_W/2) {
- x <<= _W / 2;
- c = _W / 2;
+ x <<= _W / 2
+ c = _W / 2
}
for i := 0; x != 0; i++ {
if x&(1<<(_W-1)) != 0 {
return i + c
}
- x <<= 1;
+ x <<= 1
}
- return _W;
+ return _W
}
const deBruijn32 = 0x077CB531
@@ -526,7 +526,7 @@ func trailingZeroBits(x Word) int {
panic("Unknown word size")
}
- return 0;
+ return 0
}
@@ -535,12 +535,12 @@ func shiftLeft(dst, src []Word, n int) {
return
}
- ñ := _W - uint(n);
+ ñ := _W - uint(n)
for i := len(src) - 1; i >= 1; i-- {
- dst[i] = src[i] << uint(n);
- dst[i] |= src[i-1] >> ñ;
+ dst[i] = src[i] << uint(n)
+ dst[i] |= src[i-1] >> ñ
}
- dst[0] = src[0] << uint(n);
+ dst[0] = src[0] << uint(n)
}
@@ -549,24 +549,24 @@ func shiftRight(dst, src []Word, n int) {
return
}
- ñ := _W - uint(n);
+ ñ := _W - uint(n)
for i := 0; i < len(src)-1; i++ {
- dst[i] = src[i] >> uint(n);
- dst[i] |= src[i+1] << ñ;
+ dst[i] = src[i] >> uint(n)
+ dst[i] |= src[i+1] << ñ
}
- dst[len(src)-1] = src[len(src)-1] >> uint(n);
+ dst[len(src)-1] = src[len(src)-1] >> uint(n)
}
// greaterThan returns true iff (x1<<_W + x2) > (y1<<_W + y2)
-func greaterThan(x1, x2, y1, y2 Word) bool { return x1 > y1 || x1 == y1 && x2 > y2 }
+func greaterThan(x1, x2, y1, y2 Word) bool { return x1 > y1 || x1 == y1 && x2 > y2 }
// modNW returns x % d.
func modNW(x []Word, d Word) (r Word) {
// TODO(agl): we don't actually need to store the q value.
- q := makeN(nil, len(x), false);
- return divWVW(&q[0], 0, &x[0], d, len(x));
+ q := makeN(nil, len(x), false)
+ return divWVW(&q[0], 0, &x[0], d, len(x))
}
@@ -576,28 +576,28 @@ func powersOfTwoDecompose(n []Word) (q []Word, k Word) {
return n, 0
}
- zeroWords := 0;
+ zeroWords := 0
for n[zeroWords] == 0 {
zeroWords++
}
// One of the words must be non-zero by invariant, therefore
// zeroWords < len(n).
- x := trailingZeroBits(n[zeroWords]);
+ x := trailingZeroBits(n[zeroWords])
- q = makeN(nil, len(n)-zeroWords, false);
- shiftRight(q, n[zeroWords:], x);
+ q = makeN(nil, len(n)-zeroWords, false)
+ shiftRight(q, n[zeroWords:], x)
- k = Word(_W*zeroWords + x);
- return;
+ k = Word(_W*zeroWords + x)
+ return
}
// randomN creates a random integer in [0..limit), using the space in z if
// possible. n is the bit length of limit.
func randomN(z []Word, rand *rand.Rand, limit []Word, n int) []Word {
- bitLengthOfMSW := uint(n % _W);
- mask := Word((1 << bitLengthOfMSW) - 1);
- z = makeN(z, len(limit), false);
+ bitLengthOfMSW := uint(n % _W)
+ mask := Word((1 << bitLengthOfMSW) - 1)
+ z = makeN(z, len(limit), false)
for {
for i := range z {
@@ -609,14 +609,14 @@ func randomN(z []Word, rand *rand.Rand, limit []Word, n int) []Word {
}
}
- z[len(limit)-1] &= mask;
+ z[len(limit)-1] &= mask
if cmpNN(z, limit) < 0 {
break
}
}
- return z;
+ return z
}
@@ -624,32 +624,32 @@ func randomN(z []Word, rand *rand.Rand, limit []Word, n int) []Word {
// reuses the storage of z if possible.
func expNNN(z, x, y, m []Word) []Word {
if len(y) == 0 {
- z = makeN(z, 1, false);
- z[0] = 1;
- return z;
+ z = makeN(z, 1, false)
+ z[0] = 1
+ return z
}
if m != nil {
// We likely end up being as long as the modulus.
z = makeN(z, len(m), false)
}
- z = setN(z, x);
- v := y[len(y)-1];
+ z = setN(z, x)
+ v := y[len(y)-1]
// It's invalid for the most significant word to be zero, therefore we
// will find a one bit.
- shift := leadingZeros(v) + 1;
- v <<= shift;
- var q []Word;
+ shift := leadingZeros(v) + 1
+ v <<= shift
+ var q []Word
- const mask = 1 << (_W - 1);
+ const mask = 1 << (_W - 1)
// We walk through the bits of the exponent one by one. Each time we
// see a bit, we square, thus doubling the power. If the bit is a one,
// we also multiply by x, thus adding one to the power.
- w := _W - int(shift);
+ w := _W - int(shift)
for j := 0; j < w; j++ {
- z = mulNN(z, z, z);
+ z = mulNN(z, z, z)
if v&mask != 0 {
z = mulNN(z, z, x)
@@ -659,14 +659,14 @@ func expNNN(z, x, y, m []Word) []Word {
q, z = divNN(q, z, z, m)
}
- v <<= 1;
+ v <<= 1
}
for i := len(y) - 2; i >= 0; i-- {
- v = y[i];
+ v = y[i]
for j := 0; j < _W; j++ {
- z = mulNN(z, z, z);
+ z = mulNN(z, z, z)
if v&mask != 0 {
z = mulNN(z, z, x)
@@ -676,11 +676,11 @@ func expNNN(z, x, y, m []Word) []Word {
q, z = divNN(q, z, z, m)
}
- v <<= 1;
+ v <<= 1
}
}
- return z;
+ return z
}
@@ -690,13 +690,13 @@ func lenN(z []Word) int {
return 0
}
- return (len(z)-1)*_W + (_W - leadingZeroBits(z[len(z)-1]));
+ return (len(z)-1)*_W + (_W - leadingZeroBits(z[len(z)-1]))
}
const (
- primesProduct32 = 0xC0CFD797; // Π {p ∈ primes, 2 < p <= 29}
- primesProduct64 = 0xE221F97C30E94E1D; // Π {p ∈ primes, 2 < p <= 53}
+ primesProduct32 = 0xC0CFD797 // Π {p ∈ primes, 2 < p <= 29}
+ primesProduct64 = 0xE221F97C30E94E1D // Π {p ∈ primes, 2 < p <= 53}
)
var bigOne = []Word{1}
@@ -725,7 +725,7 @@ func probablyPrime(n []Word, reps int) bool {
}
}
- var r Word;
+ var r Word
switch _W {
case 32:
r = modNW(n, primesProduct32)
@@ -745,27 +745,27 @@ func probablyPrime(n []Word, reps int) bool {
return false
}
- nm1 := subNN(nil, n, bigOne);
+ nm1 := subNN(nil, n, bigOne)
// 1<<k * q = nm1;
- q, k := powersOfTwoDecompose(nm1);
+ q, k := powersOfTwoDecompose(nm1)
- nm3 := subNN(nil, nm1, bigTwo);
- rand := rand.New(rand.NewSource(int64(n[0])));
+ nm3 := subNN(nil, nm1, bigTwo)
+ rand := rand.New(rand.NewSource(int64(n[0])))
- var x, y, quotient []Word;
- nm3Len := lenN(nm3);
+ var x, y, quotient []Word
+ nm3Len := lenN(nm3)
NextRandom:
for i := 0; i < reps; i++ {
- x = randomN(x, rand, nm3, nm3Len);
- addNN(x, x, bigTwo);
- y = expNNN(y, x, q, n);
+ x = randomN(x, rand, nm3, nm3Len)
+ addNN(x, x, bigTwo)
+ y = expNNN(y, x, q, n)
if cmpNN(y, bigOne) == 0 || cmpNN(y, nm1) == 0 {
continue
}
for j := Word(1); j < k; j++ {
- y = mulNN(y, y, y);
- quotient, y = divNN(quotient, y, y, n);
+ y = mulNN(y, y, y)
+ quotient, y = divNN(quotient, y, y, n)
if cmpNN(y, nm1) == 0 {
continue NextRandom
}
@@ -773,8 +773,8 @@ NextRandom:
return false
}
}
- return false;
+ return false
}
- return true;
+ return true
}
diff --git a/src/pkg/big/nat_test.go b/src/pkg/big/nat_test.go
index b1c9c1a102..1c993bad14 100644
--- a/src/pkg/big/nat_test.go
+++ b/src/pkg/big/nat_test.go
@@ -13,7 +13,7 @@ func TestCmpNN(t *testing.T) {
type funNN func(z, x, y []Word) []Word
type argNN struct {
- z, x, y []Word;
+ z, x, y []Word
}
@@ -41,7 +41,7 @@ var prodNN = []argNN{
func TestSetN(t *testing.T) {
for _, a := range sumNN {
- z := setN(nil, a.z);
+ z := setN(nil, a.z)
if cmpNN(z, a.z) != 0 {
t.Errorf("got z = %v; want %v", z, a.z)
}
@@ -50,7 +50,7 @@ func TestSetN(t *testing.T) {
func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
- z := f(nil, a.x, a.y);
+ z := f(nil, a.x, a.y)
if cmpNN(z, a.z) != 0 {
t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, z, a.z)
}
@@ -59,33 +59,33 @@ func testFunNN(t *testing.T, msg string, f funNN, a argNN) {
func TestFunNN(t *testing.T) {
for _, a := range sumNN {
- arg := a;
- testFunNN(t, "addNN", addNN, arg);
+ arg := a
+ testFunNN(t, "addNN", addNN, arg)
- arg = argNN{a.z, a.y, a.x};
- testFunNN(t, "addNN symmetric", addNN, arg);
+ arg = argNN{a.z, a.y, a.x}
+ testFunNN(t, "addNN symmetric", addNN, arg)
- arg = argNN{a.x, a.z, a.y};
- testFunNN(t, "subNN", subNN, arg);
+ arg = argNN{a.x, a.z, a.y}
+ testFunNN(t, "subNN", subNN, arg)
- arg = argNN{a.y, a.z, a.x};
- testFunNN(t, "subNN symmetric", subNN, arg);
+ arg = argNN{a.y, a.z, a.x}
+ testFunNN(t, "subNN symmetric", subNN, arg)
}
for _, a := range prodNN {
- arg := a;
- testFunNN(t, "mulNN", mulNN, arg);
+ arg := a
+ testFunNN(t, "mulNN", mulNN, arg)
- arg = argNN{a.z, a.y, a.x};
- testFunNN(t, "mulNN symmetric", mulNN, arg);
+ arg = argNN{a.z, a.y, a.x}
+ testFunNN(t, "mulNN symmetric", mulNN, arg)
}
}
type strN struct {
- x []Word;
- b int;
- s string;
+ x []Word
+ b int
+ s string
}
@@ -99,12 +99,12 @@ var tabN = []strN{
func TestStringN(t *testing.T) {
for _, a := range tabN {
- s := stringN(a.x, a.b);
+ s := stringN(a.x, a.b)
if s != a.s {
t.Errorf("stringN%+v\n\tgot s = %s; want %s", a, s, a.s)
}
- x, b, n := scanN(nil, a.s, a.b);
+ x, b, n := scanN(nil, a.s, a.b)
if cmpNN(x, a.x) != 0 {
t.Errorf("scanN%+v\n\tgot z = %v; want %v", a, x, a.x)
}
@@ -119,20 +119,20 @@ func TestStringN(t *testing.T) {
func TestLeadingZeroBits(t *testing.T) {
- var x Word = 1 << (_W - 1);
+ var x Word = 1 << (_W - 1)
for i := 0; i <= _W; i++ {
if leadingZeroBits(x) != i {
t.Errorf("failed at %x: got %d want %d", x, leadingZeroBits(x), i)
}
- x >>= 1;
+ x >>= 1
}
}
type shiftTest struct {
- in []Word;
- shift int;
- out []Word;
+ in []Word
+ shift int
+ out []Word
}
@@ -149,12 +149,12 @@ var leftShiftTests = []shiftTest{
func TestShiftLeft(t *testing.T) {
for i, test := range leftShiftTests {
- dst := make([]Word, len(test.out));
- shiftLeft(dst, test.in, test.shift);
+ dst := make([]Word, len(test.out))
+ shiftLeft(dst, test.in, test.shift)
for j, v := range dst {
if test.out[j] != v {
- t.Errorf("#%d: got: %v want: %v", i, dst, test.out);
- break;
+ t.Errorf("#%d: got: %v want: %v", i, dst, test.out)
+ break
}
}
}
@@ -175,12 +175,12 @@ var rightShiftTests = []shiftTest{
func TestShiftRight(t *testing.T) {
for i, test := range rightShiftTests {
- dst := make([]Word, len(test.out));
- shiftRight(dst, test.in, test.shift);
+ dst := make([]Word, len(test.out))
+ shiftRight(dst, test.in, test.shift)
for j, v := range dst {
if test.out[j] != v {
- t.Errorf("#%d: got: %v want: %v", i, dst, test.out);
- break;
+ t.Errorf("#%d: got: %v want: %v", i, dst, test.out)
+ break
}
}
}
@@ -188,9 +188,9 @@ func TestShiftRight(t *testing.T) {
type modNWTest struct {
- in string;
- dividend string;
- out string;
+ in string
+ dividend string
+ out string
}
@@ -206,11 +206,11 @@ var modNWTests64 = []modNWTest{
func runModNWTests(t *testing.T, tests []modNWTest) {
for i, test := range tests {
- in, _ := new(Int).SetString(test.in, 10);
- d, _ := new(Int).SetString(test.dividend, 10);
- out, _ := new(Int).SetString(test.out, 10);
+ in, _ := new(Int).SetString(test.in, 10)
+ d, _ := new(Int).SetString(test.dividend, 10)
+ out, _ := new(Int).SetString(test.out, 10)
- r := modNW(in.abs, d.abs[0]);
+ r := modNW(in.abs, d.abs[0])
if r != out.abs[0] {
t.Errorf("#%d failed: got %s want %s\n", i, r, out)
}
@@ -229,20 +229,20 @@ func TestModNW(t *testing.T) {
func TestTrailingZeroBits(t *testing.T) {
- var x Word;
- x--;
+ var x Word
+ x--
for i := 0; i < _W; i++ {
if trailingZeroBits(x) != i {
t.Errorf("Failed at step %d: x: %x got: %d\n", i, x, trailingZeroBits(x))
}
- x <<= 1;
+ x <<= 1
}
}
type expNNNTest struct {
- x, y, m string;
- out string;
+ x, y, m string
+ out string
}
@@ -263,17 +263,17 @@ var expNNNTests = []expNNNTest{
func TestExpNNN(t *testing.T) {
for i, test := range expNNNTests {
- x, _, _ := scanN(nil, test.x, 0);
- y, _, _ := scanN(nil, test.y, 0);
- out, _, _ := scanN(nil, test.out, 0);
+ x, _, _ := scanN(nil, test.x, 0)
+ y, _, _ := scanN(nil, test.y, 0)
+ out, _, _ := scanN(nil, test.out, 0)
- var m []Word;
+ var m []Word
if len(test.m) > 0 {
m, _, _ = scanN(nil, test.m, 0)
}
- z := expNNN(nil, x, y, m);
+ z := expNNN(nil, x, y, m)
if cmpNN(z, out) != 0 {
t.Errorf("#%d got %v want %v", i, z, out)
}
diff --git a/src/pkg/bignum/arith.go b/src/pkg/bignum/arith.go
index 243e34b9cd..aa65dbd7a8 100644
--- a/src/pkg/bignum/arith.go
+++ b/src/pkg/bignum/arith.go
@@ -18,10 +18,10 @@ func Mul128(x, y uint64) (z1, z0 uint64) {
// and return the product as 2 words.
const (
- W = uint(unsafe.Sizeof(x)) * 8;
- W2 = W / 2;
- B2 = 1 << W2;
- M2 = B2 - 1;
+ W = uint(unsafe.Sizeof(x)) * 8
+ W2 = W / 2
+ B2 = 1 << W2
+ M2 = B2 - 1
)
if x < y {
@@ -32,44 +32,44 @@ func Mul128(x, y uint64) (z1, z0 uint64) {
// y < B2 because y <= x
// sub-digits of x and y are (0, x) and (0, y)
// z = z[0] = x*y
- z0 = x * y;
- return;
+ z0 = x * y
+ return
}
if y < B2 {
// sub-digits of x and y are (x1, x0) and (0, y)
// x = (x1*B2 + x0)
// y = (y1*B2 + y0)
- x1, x0 := x>>W2, x&M2;
+ x1, x0 := x>>W2, x&M2
// x*y = t2*B2*B2 + t1*B2 + t0
- t0 := x0 * y;
- t1 := x1 * y;
+ t0 := x0 * y
+ t1 := x1 * y
// compute result digits but avoid overflow
// z = z[1]*B + z[0] = x*y
- z0 = t1<<W2 + t0;
- z1 = (t1 + t0>>W2) >> W2;
- return;
+ z0 = t1<<W2 + t0
+ z1 = (t1 + t0>>W2) >> W2
+ return
}
// general case
// sub-digits of x and y are (x1, x0) and (y1, y0)
// x = (x1*B2 + x0)
// y = (y1*B2 + y0)
- x1, x0 := x>>W2, x&M2;
- y1, y0 := y>>W2, y&M2;
+ x1, x0 := x>>W2, x&M2
+ y1, y0 := y>>W2, y&M2
// x*y = t2*B2*B2 + t1*B2 + t0
- t0 := x0 * y0;
- t1 := x1*y0 + x0*y1;
- t2 := x1 * y1;
+ t0 := x0 * y0
+ t1 := x1*y0 + x0*y1
+ t2 := x1 * y1
// compute result digits but avoid overflow
// z = z[1]*B + z[0] = x*y
- z0 = t1<<W2 + t0;
- z1 = t2 + (t1+t0>>W2)>>W2;
- return;
+ z0 = t1<<W2 + t0
+ z1 = t2 + (t1+t0>>W2)>>W2
+ return
}
@@ -80,10 +80,10 @@ func MulAdd128(x, y, c uint64) (z1, z0 uint64) {
// and return the product as 2 words.
const (
- W = uint(unsafe.Sizeof(x)) * 8;
- W2 = W / 2;
- B2 = 1 << W2;
- M2 = B2 - 1;
+ W = uint(unsafe.Sizeof(x)) * 8
+ W2 = W / 2
+ B2 = 1 << W2
+ M2 = B2 - 1
)
// TODO(gri) Should implement special cases for faster execution.
@@ -92,30 +92,30 @@ func MulAdd128(x, y, c uint64) (z1, z0 uint64) {
// sub-digits of x, y, and c are (x1, x0), (y1, y0), (c1, c0)
// x = (x1*B2 + x0)
// y = (y1*B2 + y0)
- x1, x0 := x>>W2, x&M2;
- y1, y0 := y>>W2, y&M2;
- c1, c0 := c>>W2, c&M2;
+ x1, x0 := x>>W2, x&M2
+ y1, y0 := y>>W2, y&M2
+ c1, c0 := c>>W2, c&M2
// x*y + c = t2*B2*B2 + t1*B2 + t0
- t0 := x0*y0 + c0;
- t1 := x1*y0 + x0*y1 + c1;
- t2 := x1 * y1;
+ t0 := x0*y0 + c0
+ t1 := x1*y0 + x0*y1 + c1
+ t2 := x1 * y1
// compute result digits but avoid overflow
// z = z[1]*B + z[0] = x*y
- z0 = t1<<W2 + t0;
- z1 = t2 + (t1+t0>>W2)>>W2;
- return;
+ z0 = t1<<W2 + t0
+ z1 = t2 + (t1+t0>>W2)>>W2
+ return
}
// q = (x1<<64 + x0)/y + r
func Div128(x1, x0, y uint64) (q, r uint64) {
if x1 == 0 {
- q, r = x0/y, x0%y;
- return;
+ q, r = x0/y, x0%y
+ return
}
// TODO(gri) Implement general case.
- panic("Div128 not implemented for x > 1<<64-1");
+ panic("Div128 not implemented for x > 1<<64-1")
}
diff --git a/src/pkg/bignum/bignum.go b/src/pkg/bignum/bignum.go
index 8106a26645..ee7d45ba67 100644
--- a/src/pkg/bignum/bignum.go
+++ b/src/pkg/bignum/bignum.go
@@ -16,7 +16,7 @@
package bignum
import (
- "fmt";
+ "fmt"
)
// TODO(gri) Complete the set of in-place operations.
@@ -60,25 +60,25 @@ import (
// in bits must be even.
type (
- digit uint64;
- digit2 uint32; // half-digits for division
+ digit uint64
+ digit2 uint32 // half-digits for division
)
const (
- logW = 64; // word width
- logH = 4; // bits for a hex digit (= small number)
- logB = logW - logH; // largest bit-width available
+ logW = 64 // word width
+ logH = 4 // bits for a hex digit (= small number)
+ logB = logW - logH // largest bit-width available
// half-digits
- _W2 = logB / 2; // width
- _B2 = 1 << _W2; // base
- _M2 = _B2 - 1; // mask
+ _W2 = logB / 2 // width
+ _B2 = 1 << _W2 // base
+ _M2 = _B2 - 1 // mask
// full digits
- _W = _W2 * 2; // width
- _B = 1 << _W; // base
- _M = _B - 1; // mask
+ _W = _W2 * 2 // width
+ _B = 1 << _W // base
+ _M = _B - 1 // mask
)
@@ -92,7 +92,7 @@ func assert(p bool) {
}
-func isSmall(x digit) bool { return x < 1<<logH }
+func isSmall(x digit) bool { return x < 1<<logH }
// For debugging. Keep around.
@@ -119,7 +119,7 @@ type Natural []digit
//
func Nat(x uint64) Natural {
if x == 0 {
- return nil // len == 0
+ return nil // len == 0
}
// single-digit values
@@ -132,19 +132,19 @@ func Nat(x uint64) Natural {
// compute number of digits required to represent x
// (this is usually 1 or 2, but the algorithm works
// for any base)
- n := 0;
+ n := 0
for t := x; t > 0; t >>= _W {
n++
}
// split x into digits
- z := make(Natural, n);
+ z := make(Natural, n)
for i := 0; i < n; i++ {
- z[i] = digit(x & _M);
- x >>= _W;
+ z[i] = digit(x & _M)
+ x >>= _W
}
- return z;
+ return z
}
@@ -152,7 +152,7 @@ func Nat(x uint64) Natural {
//
func (x Natural) Value() uint64 {
// single-digit values
- n := len(x);
+ n := len(x)
switch n {
case 0:
return 0
@@ -163,14 +163,14 @@ func (x Natural) Value() uint64 {
// multi-digit values
// (this is usually 1 or 2, but the algorithm works
// for any base)
- z := uint64(0);
- s := uint(0);
+ z := uint64(0)
+ s := uint(0)
for i := 0; i < n && s < 64; i++ {
- z += uint64(x[i]) << s;
- s += _W;
+ z += uint64(x[i]) << s
+ s += _W
}
- return z;
+ return z
}
@@ -178,17 +178,17 @@ func (x Natural) Value() uint64 {
// IsEven returns true iff x is divisible by 2.
//
-func (x Natural) IsEven() bool { return len(x) == 0 || x[0]&1 == 0 }
+func (x Natural) IsEven() bool { return len(x) == 0 || x[0]&1 == 0 }
// IsOdd returns true iff x is not divisible by 2.
//
-func (x Natural) IsOdd() bool { return len(x) > 0 && x[0]&1 != 0 }
+func (x Natural) IsOdd() bool { return len(x) > 0 && x[0]&1 != 0 }
// IsZero returns true iff x == 0.
//
-func (x Natural) IsZero() bool { return len(x) == 0 }
+func (x Natural) IsZero() bool { return len(x) == 0 }
// Operations
@@ -201,11 +201,11 @@ func (x Natural) IsZero() bool { return len(x) == 0 }
// n, m len(x), len(y)
func normalize(x Natural) Natural {
- n := len(x);
+ n := len(x)
for n > 0 && x[n-1] == 0 {
n--
}
- return x[0:n];
+ return x[0:n]
}
@@ -214,14 +214,14 @@ func normalize(x Natural) Natural {
// Natural is allocated.
//
func nalloc(z Natural, n int) Natural {
- size := n;
+ size := n
if size <= 0 {
size = 4
}
if size <= cap(z) {
return z[0:n]
}
- return make(Natural, n, size);
+ return make(Natural, n, size)
}
@@ -229,40 +229,40 @@ func nalloc(z Natural, n int) Natural {
// *zp may be x or y.
//
func Nadd(zp *Natural, x, y Natural) {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
- Nadd(zp, y, x);
- return;
+ Nadd(zp, y, x)
+ return
}
- z := nalloc(*zp, n+1);
- c := digit(0);
- i := 0;
+ z := nalloc(*zp, n+1)
+ c := digit(0)
+ i := 0
for i < m {
- t := c + x[i] + y[i];
- c, z[i] = t>>_W, t&_M;
- i++;
+ t := c + x[i] + y[i]
+ c, z[i] = t>>_W, t&_M
+ i++
}
for i < n {
- t := c + x[i];
- c, z[i] = t>>_W, t&_M;
- i++;
+ t := c + x[i]
+ c, z[i] = t>>_W, t&_M
+ i++
}
if c != 0 {
- z[i] = c;
- i++;
+ z[i] = c
+ i++
}
- *zp = z[0:i];
+ *zp = z[0:i]
}
// Add returns the sum z = x + y.
//
func (x Natural) Add(y Natural) Natural {
- var z Natural;
- Nadd(&z, x, y);
- return z;
+ var z Natural
+ Nadd(&z, x, y)
+ return z
}
@@ -271,29 +271,29 @@ func (x Natural) Add(y Natural) Natural {
// *zp may be x or y.
//
func Nsub(zp *Natural, x, y Natural) {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
panic("underflow")
}
- z := nalloc(*zp, n);
- c := digit(0);
- i := 0;
+ z := nalloc(*zp, n)
+ c := digit(0)
+ i := 0
for i < m {
- t := c + x[i] - y[i];
- c, z[i] = digit(int64(t)>>_W), t&_M; // requires arithmetic shift!
- i++;
+ t := c + x[i] - y[i]
+ c, z[i] = digit(int64(t)>>_W), t&_M // requires arithmetic shift!
+ i++
}
for i < n {
- t := c + x[i];
- c, z[i] = digit(int64(t)>>_W), t&_M; // requires arithmetic shift!
- i++;
+ t := c + x[i]
+ c, z[i] = digit(int64(t)>>_W), t&_M // requires arithmetic shift!
+ i++
}
if int64(c) < 0 {
panic("underflow")
}
- *zp = normalize(z);
+ *zp = normalize(z)
}
@@ -301,17 +301,17 @@ func Nsub(zp *Natural, x, y Natural) {
// If x < y, an underflow run-time error occurs (use Cmp to test if x >= y).
//
func (x Natural) Sub(y Natural) Natural {
- var z Natural;
- Nsub(&z, x, y);
- return z;
+ var z Natural
+ Nsub(&z, x, y)
+ return z
}
// Returns z1 = (x*y + c) div B, z0 = (x*y + c) mod B.
//
func muladd11(x, y, c digit) (digit, digit) {
- z1, z0 := MulAdd128(uint64(x), uint64(y), uint64(c));
- return digit(z1<<(64-logB) | z0>>logB), digit(z0 & _M);
+ z1, z0 := MulAdd128(uint64(x), uint64(y), uint64(c))
+ return digit(z1<<(64-logB) | z0>>logB), digit(z0 & _M)
}
@@ -319,7 +319,7 @@ func mul1(z, x Natural, y digit) (c digit) {
for i := 0; i < len(x); i++ {
c, z[i] = muladd11(x[i], y, c)
}
- return;
+ return
}
@@ -328,29 +328,29 @@ func mul1(z, x Natural, y digit) (c digit) {
func Nscale(z *Natural, d uint64) {
switch {
case d == 0:
- *z = Nat(0);
- return;
+ *z = Nat(0)
+ return
case d == 1:
return
case d >= _B:
- *z = z.Mul1(d);
- return;
+ *z = z.Mul1(d)
+ return
}
- c := mul1(*z, *z, digit(d));
+ c := mul1(*z, *z, digit(d))
if c != 0 {
- n := len(*z);
+ n := len(*z)
if n >= cap(*z) {
- zz := make(Natural, n+1);
+ zz := make(Natural, n+1)
for i, d := range *z {
zz[i] = d
}
- *z = zz;
+ *z = zz
} else {
*z = (*z)[0 : n+1]
}
- (*z)[n] = c;
+ (*z)[n] = c
}
}
@@ -358,17 +358,17 @@ func Nscale(z *Natural, d uint64) {
// Computes x = x*d + c for small d's.
//
func muladd1(x Natural, d, c digit) Natural {
- assert(isSmall(d-1) && isSmall(c));
- n := len(x);
- z := make(Natural, n+1);
+ assert(isSmall(d-1) && isSmall(c))
+ n := len(x)
+ z := make(Natural, n+1)
for i := 0; i < n; i++ {
- t := c + x[i]*d;
- c, z[i] = t>>_W, t&_M;
+ t := c + x[i]*d
+ c, z[i] = t>>_W, t&_M
}
- z[n] = c;
+ z[n] = c
- return normalize(z);
+ return normalize(z)
}
@@ -386,18 +386,18 @@ func (x Natural) Mul1(d uint64) Natural {
return x.Mul(Nat(d))
}
- z := make(Natural, len(x)+1);
- c := mul1(z, x, digit(d));
- z[len(x)] = c;
- return normalize(z);
+ z := make(Natural, len(x)+1)
+ c := mul1(z, x, digit(d))
+ z[len(x)] = c
+ return normalize(z)
}
// Mul returns the product x * y.
//
func (x Natural) Mul(y Natural) Natural {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
return y.Mul(x)
}
@@ -410,19 +410,19 @@ func (x Natural) Mul(y Natural) Natural {
return x.Mul1(uint64(y[0]))
}
- z := make(Natural, n+m);
+ z := make(Natural, n+m)
for j := 0; j < m; j++ {
- d := y[j];
+ d := y[j]
if d != 0 {
- c := digit(0);
+ c := digit(0)
for i := 0; i < n; i++ {
c, z[i+j] = muladd11(x[i], d, z[i+j]+c)
}
- z[n+j] = c;
+ z[n+j] = c
}
}
- return normalize(z);
+ return normalize(z)
}
@@ -432,57 +432,57 @@ func (x Natural) Mul(y Natural) Natural {
// DivMod, and then pack the results again.
func unpack(x Natural) []digit2 {
- n := len(x);
- z := make([]digit2, n*2+1); // add space for extra digit (used by DivMod)
+ n := len(x)
+ z := make([]digit2, n*2+1) // add space for extra digit (used by DivMod)
for i := 0; i < n; i++ {
- t := x[i];
- z[i*2] = digit2(t & _M2);
- z[i*2+1] = digit2(t >> _W2 & _M2);
+ t := x[i]
+ z[i*2] = digit2(t & _M2)
+ z[i*2+1] = digit2(t >> _W2 & _M2)
}
// normalize result
- k := 2 * n;
+ k := 2 * n
for k > 0 && z[k-1] == 0 {
k--
}
- return z[0:k]; // trim leading 0's
+ return z[0:k] // trim leading 0's
}
func pack(x []digit2) Natural {
- n := (len(x) + 1) / 2;
- z := make(Natural, n);
+ n := (len(x) + 1) / 2
+ z := make(Natural, n)
if len(x)&1 == 1 {
// handle odd len(x)
- n--;
- z[n] = digit(x[n*2]);
+ n--
+ z[n] = digit(x[n*2])
}
for i := 0; i < n; i++ {
z[i] = digit(x[i*2+1])<<_W2 | digit(x[i*2])
}
- return normalize(z);
+ return normalize(z)
}
func mul21(z, x []digit2, y digit2) digit2 {
- c := digit(0);
- f := digit(y);
+ c := digit(0)
+ f := digit(y)
for i := 0; i < len(x); i++ {
- t := c + digit(x[i])*f;
- c, z[i] = t>>_W2, digit2(t&_M2);
+ t := c + digit(x[i])*f
+ c, z[i] = t>>_W2, digit2(t&_M2)
}
- return digit2(c);
+ return digit2(c)
}
func div21(z, x []digit2, y digit2) digit2 {
- c := digit(0);
- d := digit(y);
+ c := digit(0)
+ d := digit(y)
for i := len(x) - 1; i >= 0; i-- {
- t := c<<_W2 + digit(x[i]);
- c, z[i] = t%d, digit2(t/d);
+ t := c<<_W2 + digit(x[i])
+ c, z[i] = t%d, digit2(t/d)
}
- return digit2(c);
+ return digit2(c)
}
@@ -507,14 +507,14 @@ func div21(z, x []digit2, y digit2) digit2 {
// 579-601. John Wiley & Sons, Ltd.
func divmod(x, y []digit2) ([]digit2, []digit2) {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if m == 0 {
panic("division by zero")
}
- assert(n+1 <= cap(x)); // space for one extra digit
- x = x[0 : n+1];
- assert(x[n] == 0);
+ assert(n+1 <= cap(x)) // space for one extra digit
+ x = x[0 : n+1]
+ assert(x[n] == 0)
if m == 1 {
// division by single digit
@@ -528,27 +528,27 @@ func divmod(x, y []digit2) ([]digit2, []digit2) {
} else {
// general case
- assert(2 <= m && m <= n);
+ assert(2 <= m && m <= n)
// normalize x and y
// TODO Instead of multiplying, it would be sufficient to
// shift y such that the normalization condition is
// satisfied (as done in Hacker's Delight).
- f := _B2 / (digit(y[m-1]) + 1);
+ f := _B2 / (digit(y[m-1]) + 1)
if f != 1 {
- mul21(x, x, digit2(f));
- mul21(y, y, digit2(f));
+ mul21(x, x, digit2(f))
+ mul21(y, y, digit2(f))
}
- assert(_B2/2 <= y[m-1] && y[m-1] < _B2); // incorrect scaling
+ assert(_B2/2 <= y[m-1] && y[m-1] < _B2) // incorrect scaling
- y1, y2 := digit(y[m-1]), digit(y[m-2]);
+ y1, y2 := digit(y[m-1]), digit(y[m-2])
for i := n - m; i >= 0; i-- {
- k := i + m;
+ k := i + m
// compute trial digit (Knuth)
- var q digit;
+ var q digit
{
- x0, x1, x2 := digit(x[k]), digit(x[k-1]), digit(x[k-2]);
+ x0, x1, x2 := digit(x[k]), digit(x[k-1]), digit(x[k-2])
if x0 != y1 {
q = (x0<<_W2 + x1) / y1
} else {
@@ -560,36 +560,36 @@ func divmod(x, y []digit2) ([]digit2, []digit2) {
}
// subtract y*q
- c := digit(0);
+ c := digit(0)
for j := 0; j < m; j++ {
- t := c + digit(x[i+j]) - digit(y[j])*q;
- c, x[i+j] = digit(int64(t)>>_W2), digit2(t&_M2); // requires arithmetic shift!
+ t := c + digit(x[i+j]) - digit(y[j])*q
+ c, x[i+j] = digit(int64(t)>>_W2), digit2(t&_M2) // requires arithmetic shift!
}
// correct if trial digit was too large
if c+digit(x[k]) != 0 {
// add y
- c := digit(0);
+ c := digit(0)
for j := 0; j < m; j++ {
- t := c + digit(x[i+j]) + digit(y[j]);
- c, x[i+j] = t>>_W2, digit2(t&_M2);
+ t := c + digit(x[i+j]) + digit(y[j])
+ c, x[i+j] = t>>_W2, digit2(t&_M2)
}
- assert(c+digit(x[k]) == 0);
+ assert(c+digit(x[k]) == 0)
// correct trial digit
- q--;
+ q--
}
- x[k] = digit2(q);
+ x[k] = digit2(q)
}
// undo normalization for remainder
if f != 1 {
- c := div21(x[0:m], x[0:m], digit2(f));
- assert(c == 0);
+ c := div21(x[0:m], x[0:m], digit2(f))
+ assert(c == 0)
}
}
- return x[m : n+1], x[0:m];
+ return x[m : n+1], x[0:m]
}
@@ -598,8 +598,8 @@ func divmod(x, y []digit2) ([]digit2, []digit2) {
// If y == 0, a division-by-zero run-time error occurs.
//
func (x Natural) Div(y Natural) Natural {
- q, _ := divmod(unpack(x), unpack(y));
- return pack(q);
+ q, _ := divmod(unpack(x), unpack(y))
+ return pack(q)
}
@@ -608,8 +608,8 @@ func (x Natural) Div(y Natural) Natural {
// If y == 0, a division-by-zero run-time error occurs.
//
func (x Natural) Mod(y Natural) Natural {
- _, r := divmod(unpack(x), unpack(y));
- return pack(r);
+ _, r := divmod(unpack(x), unpack(y))
+ return pack(r)
}
@@ -617,78 +617,78 @@ func (x Natural) Mod(y Natural) Natural {
// If y == 0, a division-by-zero run-time error occurs.
//
func (x Natural) DivMod(y Natural) (Natural, Natural) {
- q, r := divmod(unpack(x), unpack(y));
- return pack(q), pack(r);
+ q, r := divmod(unpack(x), unpack(y))
+ return pack(q), pack(r)
}
func shl(z, x Natural, s uint) digit {
- assert(s <= _W);
- n := len(x);
- c := digit(0);
+ assert(s <= _W)
+ n := len(x)
+ c := digit(0)
for i := 0; i < n; i++ {
c, z[i] = x[i]>>(_W-s), x[i]<<s&_M|c
}
- return c;
+ return c
}
// Shl implements ``shift left'' x << s. It returns x * 2^s.
//
func (x Natural) Shl(s uint) Natural {
- n := uint(len(x));
- m := n + s/_W;
- z := make(Natural, m+1);
+ n := uint(len(x))
+ m := n + s/_W
+ z := make(Natural, m+1)
- z[m] = shl(z[m-n:m], x, s%_W);
+ z[m] = shl(z[m-n:m], x, s%_W)
- return normalize(z);
+ return normalize(z)
}
func shr(z, x Natural, s uint) digit {
- assert(s <= _W);
- n := len(x);
- c := digit(0);
+ assert(s <= _W)
+ n := len(x)
+ c := digit(0)
for i := n - 1; i >= 0; i-- {
c, z[i] = x[i]<<(_W-s)&_M, x[i]>>s|c
}
- return c;
+ return c
}
// Shr implements ``shift right'' x >> s. It returns x / 2^s.
//
func (x Natural) Shr(s uint) Natural {
- n := uint(len(x));
- m := n - s/_W;
- if m > n { // check for underflow
+ n := uint(len(x))
+ m := n - s/_W
+ if m > n { // check for underflow
m = 0
}
- z := make(Natural, m);
+ z := make(Natural, m)
- shr(z, x[n-m:n], s%_W);
+ shr(z, x[n-m:n], s%_W)
- return normalize(z);
+ return normalize(z)
}
// And returns the ``bitwise and'' x & y for the 2's-complement representation of x and y.
//
func (x Natural) And(y Natural) Natural {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
return y.And(x)
}
- z := make(Natural, m);
+ z := make(Natural, m)
for i := 0; i < m; i++ {
z[i] = x[i] & y[i]
}
// upper bits are 0
- return normalize(z);
+ return normalize(z)
}
@@ -702,57 +702,57 @@ func copy(z, x Natural) {
// AndNot returns the ``bitwise clear'' x &^ y for the 2's-complement representation of x and y.
//
func (x Natural) AndNot(y Natural) Natural {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
m = n
}
- z := make(Natural, n);
+ z := make(Natural, n)
for i := 0; i < m; i++ {
z[i] = x[i] &^ y[i]
}
- copy(z[m:n], x[m:n]);
+ copy(z[m:n], x[m:n])
- return normalize(z);
+ return normalize(z)
}
// Or returns the ``bitwise or'' x | y for the 2's-complement representation of x and y.
//
func (x Natural) Or(y Natural) Natural {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
return y.Or(x)
}
- z := make(Natural, n);
+ z := make(Natural, n)
for i := 0; i < m; i++ {
z[i] = x[i] | y[i]
}
- copy(z[m:n], x[m:n]);
+ copy(z[m:n], x[m:n])
- return z;
+ return z
}
// Xor returns the ``bitwise exclusive or'' x ^ y for the 2's-complement representation of x and y.
//
func (x Natural) Xor(y Natural) Natural {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n < m {
return y.Xor(x)
}
- z := make(Natural, n);
+ z := make(Natural, n)
for i := 0; i < m; i++ {
z[i] = x[i] ^ y[i]
}
- copy(z[m:n], x[m:n]);
+ copy(z[m:n], x[m:n])
- return normalize(z);
+ return normalize(z)
}
@@ -763,19 +763,19 @@ func (x Natural) Xor(y Natural) Natural {
// > 0 if x > y
//
func (x Natural) Cmp(y Natural) int {
- n := len(x);
- m := len(y);
+ n := len(x)
+ m := len(y)
if n != m || n == 0 {
return n - m
}
- i := n - 1;
+ i := n - 1
for i > 0 && x[i] == y[i] {
i--
}
- d := 0;
+ d := 0
switch {
case x[i] < y[i]:
d = -1
@@ -783,7 +783,7 @@ func (x Natural) Cmp(y Natural) int {
d = 1
}
- return d;
+ return d
}
@@ -792,13 +792,13 @@ func (x Natural) Cmp(y Natural) int {
// If x == 0 a run-time error occurs.
//
func log2(x uint64) uint {
- assert(x > 0);
- n := uint(0);
+ assert(x > 0)
+ n := uint(0)
for x > 0 {
- x >>= 1;
- n++;
+ x >>= 1
+ n++
}
- return n - 1;
+ return n - 1
}
@@ -807,11 +807,11 @@ func log2(x uint64) uint {
// If x == 0 a run-time error occurs.
//
func (x Natural) Log2() uint {
- n := len(x);
+ n := len(x)
if n > 0 {
return (uint(n)-1)*_W + log2(uint64(x[n-1]))
}
- panic("Log2(0)");
+ panic("Log2(0)")
}
@@ -819,15 +819,15 @@ func (x Natural) Log2() uint {
// Returns updated x and x mod d.
//
func divmod1(x Natural, d digit) (Natural, digit) {
- assert(0 < d && isSmall(d-1));
+ assert(0 < d && isSmall(d-1))
- c := digit(0);
+ c := digit(0)
for i := len(x) - 1; i >= 0; i-- {
- t := c<<_W + x[i];
- c, x[i] = t%d, t/d;
+ t := c<<_W + x[i]
+ c, x[i] = t%d, t/d
}
- return normalize(x), c;
+ return normalize(x), c
}
@@ -839,31 +839,31 @@ func (x Natural) ToString(base uint) string {
}
// allocate buffer for conversion
- assert(2 <= base && base <= 16);
- n := (x.Log2()+1)/log2(uint64(base)) + 1; // +1: round up
- s := make([]byte, n);
+ assert(2 <= base && base <= 16)
+ n := (x.Log2()+1)/log2(uint64(base)) + 1 // +1: round up
+ s := make([]byte, n)
// don't destroy x
- t := make(Natural, len(x));
- copy(t, x);
+ t := make(Natural, len(x))
+ copy(t, x)
// convert
- i := n;
+ i := n
for !t.IsZero() {
- i--;
- var d digit;
- t, d = divmod1(t, digit(base));
- s[i] = "0123456789abcdef"[d];
+ i--
+ var d digit
+ t, d = divmod1(t, digit(base))
+ s[i] = "0123456789abcdef"[d]
}
- return string(s[i:n]);
+ return string(s[i:n])
}
// String converts x to its decimal string representation.
// x.String() is the same as x.ToString(10).
//
-func (x Natural) String() string { return x.ToString(10) }
+func (x Natural) String() string { return x.ToString(10) }
func fmtbase(c int) uint {
@@ -875,18 +875,18 @@ func fmtbase(c int) uint {
case 'x':
return 16
}
- return 10;
+ return 10
}
// Format is a support routine for fmt.Formatter. It accepts
// the formats 'b' (binary), 'o' (octal), and 'x' (hexadecimal).
//
-func (x Natural) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(fmtbase(c))) }
+func (x Natural) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(fmtbase(c))) }
func hexvalue(ch byte) uint {
- d := uint(1 << logH);
+ d := uint(1 << logH)
switch {
case '0' <= ch && ch <= '9':
d = uint(ch - '0')
@@ -895,7 +895,7 @@ func hexvalue(ch byte) uint {
case 'A' <= ch && ch <= 'F':
d = uint(ch-'A') + 10
}
- return d;
+ return d
}
@@ -911,9 +911,9 @@ func hexvalue(ch byte) uint {
//
func NatFromString(s string, base uint) (Natural, uint, int) {
// determine base if necessary
- i, n := 0, len(s);
+ i, n := 0, len(s)
if base == 0 {
- base = 10;
+ base = 10
if n > 0 && s[0] == '0' {
if n > 1 && (s[1] == 'x' || s[1] == 'X') {
base, i = 16, 2
@@ -924,10 +924,10 @@ func NatFromString(s string, base uint) (Natural, uint, int) {
}
// convert string
- assert(2 <= base && base <= 16);
- x := Nat(0);
+ assert(2 <= base && base <= 16)
+ x := Nat(0)
for ; i < n; i++ {
- d := hexvalue(s[i]);
+ d := hexvalue(s[i])
if d < base {
x = muladd1(x, digit(base), digit(d))
} else {
@@ -935,46 +935,46 @@ func NatFromString(s string, base uint) (Natural, uint, int) {
}
}
- return x, base, i;
+ return x, base, i
}
// Natural number functions
func pop1(x digit) uint {
- n := uint(0);
+ n := uint(0)
for x != 0 {
- x &= x - 1;
- n++;
+ x &= x - 1
+ n++
}
- return n;
+ return n
}
// Pop computes the ``population count'' of (the number of 1 bits in) x.
//
func (x Natural) Pop() uint {
- n := uint(0);
+ n := uint(0)
for i := len(x) - 1; i >= 0; i-- {
n += pop1(x[i])
}
- return n;
+ return n
}
// Pow computes x to the power of n.
//
func (xp Natural) Pow(n uint) Natural {
- z := Nat(1);
- x := xp;
+ z := Nat(1)
+ x := xp
for n > 0 {
// z * x^n == x^n0
if n&1 == 1 {
z = z.Mul(x)
}
- x, n = x.Mul(x), n/2;
+ x, n = x.Mul(x), n/2
}
- return z;
+ return z
}
@@ -990,9 +990,9 @@ func MulRange(a, b uint) Natural {
case a+1 == b:
return Nat(uint64(a)).Mul(Nat(uint64(b)))
}
- m := (a + b) >> 1;
- assert(a <= m && m < b);
- return MulRange(a, m).Mul(MulRange(m+1, b));
+ m := (a + b) >> 1
+ assert(a <= m && m < b)
+ return MulRange(a, m).Mul(MulRange(m+1, b))
}
@@ -1007,16 +1007,16 @@ func Fact(n uint) Natural {
// Binomial computes the binomial coefficient of (n, k).
//
-func Binomial(n, k uint) Natural { return MulRange(n-k+1, n).Div(MulRange(1, k)) }
+func Binomial(n, k uint) Natural { return MulRange(n-k+1, n).Div(MulRange(1, k)) }
// Gcd computes the gcd of x and y.
//
func (x Natural) Gcd(y Natural) Natural {
// Euclidean algorithm.
- a, b := x, y;
+ a, b := x, y
for !b.IsZero() {
a, b = b, a.Mod(b)
}
- return a;
+ return a
}
diff --git a/src/pkg/bignum/bignum_test.go b/src/pkg/bignum/bignum_test.go
index 73edc93453..532fc97405 100644
--- a/src/pkg/bignum/bignum_test.go
+++ b/src/pkg/bignum/bignum_test.go
@@ -5,62 +5,62 @@
package bignum
import (
- "fmt";
- "testing";
+ "fmt"
+ "testing"
)
const (
- sa = "991";
- sb = "2432902008176640000"; // 20!
- sc = "933262154439441526816992388562667004907159682643816214685929" +
+ sa = "991"
+ sb = "2432902008176640000" // 20!
+ sc = "933262154439441526816992388562667004907159682643816214685929" +
"638952175999932299156089414639761565182862536979208272237582" +
- "51185210916864000000000000000000000000"; // 100!
- sp = "170141183460469231731687303715884105727"; // prime
+ "51185210916864000000000000000000000000" // 100!
+ sp = "170141183460469231731687303715884105727" // prime
)
func natFromString(s string, base uint, slen *int) Natural {
- x, _, len := NatFromString(s, base);
+ x, _, len := NatFromString(s, base)
if slen != nil {
*slen = len
}
- return x;
+ return x
}
func intFromString(s string, base uint, slen *int) *Integer {
- x, _, len := IntFromString(s, base);
+ x, _, len := IntFromString(s, base)
if slen != nil {
*slen = len
}
- return x;
+ return x
}
func ratFromString(s string, base uint, slen *int) *Rational {
- x, _, len := RatFromString(s, base);
+ x, _, len := RatFromString(s, base)
if slen != nil {
*slen = len
}
- return x;
+ return x
}
var (
- nat_zero = Nat(0);
- nat_one = Nat(1);
- nat_two = Nat(2);
- a = natFromString(sa, 10, nil);
- b = natFromString(sb, 10, nil);
- c = natFromString(sc, 10, nil);
- p = natFromString(sp, 10, nil);
- int_zero = Int(0);
- int_one = Int(1);
- int_two = Int(2);
- ip = intFromString(sp, 10, nil);
- rat_zero = Rat(0, 1);
- rat_half = Rat(1, 2);
- rat_one = Rat(1, 1);
- rat_two = Rat(2, 1);
+ nat_zero = Nat(0)
+ nat_one = Nat(1)
+ nat_two = Nat(2)
+ a = natFromString(sa, 10, nil)
+ b = natFromString(sb, 10, nil)
+ c = natFromString(sc, 10, nil)
+ p = natFromString(sp, 10, nil)
+ int_zero = Int(0)
+ int_one = Int(1)
+ int_two = Int(2)
+ ip = intFromString(sp, 10, nil)
+ rat_zero = Rat(0, 1)
+ rat_half = Rat(1, 2)
+ rat_one = Rat(1, 1)
+ rat_two = Rat(2, 1)
)
@@ -96,11 +96,11 @@ func rat_eq(n uint, x, y *Rational) {
func TestNatConv(t *testing.T) {
- tester = t;
- test_msg = "NatConvA";
+ tester = t
+ test_msg = "NatConvA"
type entry1 struct {
- x uint64;
- s string;
+ x uint64
+ s string
}
tab := []entry1{
entry1{0, "0"},
@@ -108,51 +108,51 @@ func TestNatConv(t *testing.T) {
entry1{65535, "65535"},
entry1{4294967295, "4294967295"},
entry1{18446744073709551615, "18446744073709551615"},
- };
+ }
for i, e := range tab {
- test(100+uint(i), Nat(e.x).String() == e.s);
- test(200+uint(i), natFromString(e.s, 0, nil).Value() == e.x);
+ test(100+uint(i), Nat(e.x).String() == e.s)
+ test(200+uint(i), natFromString(e.s, 0, nil).Value() == e.x)
}
- test_msg = "NatConvB";
+ test_msg = "NatConvB"
for i := uint(0); i < 100; i++ {
test(i, Nat(uint64(i)).String() == fmt.Sprintf("%d", i))
}
- test_msg = "NatConvC";
- z := uint64(7);
+ test_msg = "NatConvC"
+ z := uint64(7)
for i := uint(0); i <= 64; i++ {
- test(i, Nat(z).Value() == z);
- z <<= 1;
+ test(i, Nat(z).Value() == z)
+ z <<= 1
}
- test_msg = "NatConvD";
- nat_eq(0, a, Nat(991));
- nat_eq(1, b, Fact(20));
- nat_eq(2, c, Fact(100));
- test(3, a.String() == sa);
- test(4, b.String() == sb);
- test(5, c.String() == sc);
+ test_msg = "NatConvD"
+ nat_eq(0, a, Nat(991))
+ nat_eq(1, b, Fact(20))
+ nat_eq(2, c, Fact(100))
+ test(3, a.String() == sa)
+ test(4, b.String() == sb)
+ test(5, c.String() == sc)
- test_msg = "NatConvE";
- var slen int;
- nat_eq(10, natFromString("0", 0, nil), nat_zero);
- nat_eq(11, natFromString("123", 0, nil), Nat(123));
- nat_eq(12, natFromString("077", 0, nil), Nat(7*8+7));
- nat_eq(13, natFromString("0x1f", 0, nil), Nat(1*16+15));
- nat_eq(14, natFromString("0x1fg", 0, &slen), Nat(1*16+15));
- test(4, slen == 4);
+ test_msg = "NatConvE"
+ var slen int
+ nat_eq(10, natFromString("0", 0, nil), nat_zero)
+ nat_eq(11, natFromString("123", 0, nil), Nat(123))
+ nat_eq(12, natFromString("077", 0, nil), Nat(7*8+7))
+ nat_eq(13, natFromString("0x1f", 0, nil), Nat(1*16+15))
+ nat_eq(14, natFromString("0x1fg", 0, &slen), Nat(1*16+15))
+ test(4, slen == 4)
- test_msg = "NatConvF";
- tmp := c.Mul(c);
+ test_msg = "NatConvF"
+ tmp := c.Mul(c)
for base := uint(2); base <= 16; base++ {
nat_eq(base, natFromString(tmp.ToString(base), base, nil), tmp)
}
- test_msg = "NatConvG";
- x := Nat(100);
- y, _, _ := NatFromString(fmt.Sprintf("%b", &x), 2);
- nat_eq(100, y, x);
+ test_msg = "NatConvG"
+ x := Nat(100)
+ y, _, _ := NatFromString(fmt.Sprintf("%b", &x), 2)
+ nat_eq(100, y, x)
}
@@ -160,16 +160,16 @@ func abs(x int64) uint64 {
if x < 0 {
x = -x
}
- return uint64(x);
+ return uint64(x)
}
func TestIntConv(t *testing.T) {
- tester = t;
- test_msg = "IntConvA";
+ tester = t
+ test_msg = "IntConvA"
type entry2 struct {
- x int64;
- s string;
+ x int64
+ s string
}
tab := []entry2{
entry2{0, "0"},
@@ -181,92 +181,92 @@ func TestIntConv(t *testing.T) {
entry2{2147483647, "2147483647"},
entry2{-9223372036854775808, "-9223372036854775808"},
entry2{9223372036854775807, "9223372036854775807"},
- };
+ }
for i, e := range tab {
- test(100+uint(i), Int(e.x).String() == e.s);
- test(200+uint(i), intFromString(e.s, 0, nil).Value() == e.x);
- test(300+uint(i), Int(e.x).Abs().Value() == abs(e.x));
+ test(100+uint(i), Int(e.x).String() == e.s)
+ test(200+uint(i), intFromString(e.s, 0, nil).Value() == e.x)
+ test(300+uint(i), Int(e.x).Abs().Value() == abs(e.x))
}
- test_msg = "IntConvB";
- var slen int;
- int_eq(0, intFromString("0", 0, nil), int_zero);
- int_eq(1, intFromString("-0", 0, nil), int_zero);
- int_eq(2, intFromString("123", 0, nil), Int(123));
- int_eq(3, intFromString("-123", 0, nil), Int(-123));
- int_eq(4, intFromString("077", 0, nil), Int(7*8+7));
- int_eq(5, intFromString("-077", 0, nil), Int(-(7*8 + 7)));
- int_eq(6, intFromString("0x1f", 0, nil), Int(1*16+15));
- int_eq(7, intFromString("-0x1f", 0, &slen), Int(-(1*16 + 15)));
- test(7, slen == 5);
- int_eq(8, intFromString("+0x1f", 0, &slen), Int(+(1*16 + 15)));
- test(8, slen == 5);
- int_eq(9, intFromString("0x1fg", 0, &slen), Int(1*16+15));
- test(9, slen == 4);
- int_eq(10, intFromString("-0x1fg", 0, &slen), Int(-(1*16 + 15)));
- test(10, slen == 5);
+ test_msg = "IntConvB"
+ var slen int
+ int_eq(0, intFromString("0", 0, nil), int_zero)
+ int_eq(1, intFromString("-0", 0, nil), int_zero)
+ int_eq(2, intFromString("123", 0, nil), Int(123))
+ int_eq(3, intFromString("-123", 0, nil), Int(-123))
+ int_eq(4, intFromString("077", 0, nil), Int(7*8+7))
+ int_eq(5, intFromString("-077", 0, nil), Int(-(7*8 + 7)))
+ int_eq(6, intFromString("0x1f", 0, nil), Int(1*16+15))
+ int_eq(7, intFromString("-0x1f", 0, &slen), Int(-(1*16 + 15)))
+ test(7, slen == 5)
+ int_eq(8, intFromString("+0x1f", 0, &slen), Int(+(1*16 + 15)))
+ test(8, slen == 5)
+ int_eq(9, intFromString("0x1fg", 0, &slen), Int(1*16+15))
+ test(9, slen == 4)
+ int_eq(10, intFromString("-0x1fg", 0, &slen), Int(-(1*16 + 15)))
+ test(10, slen == 5)
}
func TestRatConv(t *testing.T) {
- tester = t;
- test_msg = "RatConv";
- var slen int;
- rat_eq(0, ratFromString("0", 0, nil), rat_zero);
- rat_eq(1, ratFromString("0/1", 0, nil), rat_zero);
- rat_eq(2, ratFromString("0/01", 0, nil), rat_zero);
- rat_eq(3, ratFromString("0x14/10", 0, &slen), rat_two);
- test(4, slen == 7);
- rat_eq(5, ratFromString("0.", 0, nil), rat_zero);
- rat_eq(6, ratFromString("0.001f", 10, nil), Rat(1, 1000));
- rat_eq(7, ratFromString(".1", 0, nil), Rat(1, 10));
- rat_eq(8, ratFromString("10101.0101", 2, nil), Rat(0x155, 1<<4));
- rat_eq(9, ratFromString("-0003.145926", 10, &slen), Rat(-3145926, 1000000));
- test(10, slen == 12);
- rat_eq(11, ratFromString("1e2", 0, nil), Rat(100, 1));
- rat_eq(12, ratFromString("1e-2", 0, nil), Rat(1, 100));
- rat_eq(13, ratFromString("1.1e2", 0, nil), Rat(110, 1));
- rat_eq(14, ratFromString(".1e2x", 0, &slen), Rat(10, 1));
- test(15, slen == 4);
+ tester = t
+ test_msg = "RatConv"
+ var slen int
+ rat_eq(0, ratFromString("0", 0, nil), rat_zero)
+ rat_eq(1, ratFromString("0/1", 0, nil), rat_zero)
+ rat_eq(2, ratFromString("0/01", 0, nil), rat_zero)
+ rat_eq(3, ratFromString("0x14/10", 0, &slen), rat_two)
+ test(4, slen == 7)
+ rat_eq(5, ratFromString("0.", 0, nil), rat_zero)
+ rat_eq(6, ratFromString("0.001f", 10, nil), Rat(1, 1000))
+ rat_eq(7, ratFromString(".1", 0, nil), Rat(1, 10))
+ rat_eq(8, ratFromString("10101.0101", 2, nil), Rat(0x155, 1<<4))
+ rat_eq(9, ratFromString("-0003.145926", 10, &slen), Rat(-3145926, 1000000))
+ test(10, slen == 12)
+ rat_eq(11, ratFromString("1e2", 0, nil), Rat(100, 1))
+ rat_eq(12, ratFromString("1e-2", 0, nil), Rat(1, 100))
+ rat_eq(13, ratFromString("1.1e2", 0, nil), Rat(110, 1))
+ rat_eq(14, ratFromString(".1e2x", 0, &slen), Rat(10, 1))
+ test(15, slen == 4)
}
func add(x, y Natural) Natural {
- z1 := x.Add(y);
- z2 := y.Add(x);
+ z1 := x.Add(y)
+ z2 := y.Add(x)
if z1.Cmp(z2) != 0 {
tester.Fatalf("addition not symmetric:\n\tx = %v\n\ty = %t", x, y)
}
- return z1;
+ return z1
}
func sum(n uint64, scale Natural) Natural {
- s := nat_zero;
+ s := nat_zero
for ; n > 0; n-- {
s = add(s, Nat(n).Mul(scale))
}
- return s;
+ return s
}
func TestNatAdd(t *testing.T) {
- tester = t;
- test_msg = "NatAddA";
- nat_eq(0, add(nat_zero, nat_zero), nat_zero);
- nat_eq(1, add(nat_zero, c), c);
+ tester = t
+ test_msg = "NatAddA"
+ nat_eq(0, add(nat_zero, nat_zero), nat_zero)
+ nat_eq(1, add(nat_zero, c), c)
- test_msg = "NatAddB";
+ test_msg = "NatAddB"
for i := uint64(0); i < 100; i++ {
- t := Nat(i);
- nat_eq(uint(i), sum(i, c), t.Mul(t).Add(t).Shr(1).Mul(c));
+ t := Nat(i)
+ nat_eq(uint(i), sum(i, c), t.Mul(t).Add(t).Shr(1).Mul(c))
}
}
func mul(x, y Natural) Natural {
- z1 := x.Mul(y);
- z2 := y.Mul(x);
+ z1 := x.Mul(y)
+ z2 := y.Mul(x)
if z1.Cmp(z2) != 0 {
tester.Fatalf("multiplication not symmetric:\n\tx = %v\n\ty = %t", x, y)
}
@@ -276,40 +276,40 @@ func mul(x, y Natural) Natural {
if !y.IsZero() && z1.Div(y).Cmp(x) != 0 {
tester.Fatalf("multiplication/division not inverse (B):\n\tx = %v\n\ty = %t", x, y)
}
- return z1;
+ return z1
}
func TestNatSub(t *testing.T) {
- tester = t;
- test_msg = "NatSubA";
- nat_eq(0, nat_zero.Sub(nat_zero), nat_zero);
- nat_eq(1, c.Sub(nat_zero), c);
+ tester = t
+ test_msg = "NatSubA"
+ nat_eq(0, nat_zero.Sub(nat_zero), nat_zero)
+ nat_eq(1, c.Sub(nat_zero), c)
- test_msg = "NatSubB";
+ test_msg = "NatSubB"
for i := uint64(0); i < 100; i++ {
- t := sum(i, c);
+ t := sum(i, c)
for j := uint64(0); j <= i; j++ {
t = t.Sub(mul(Nat(j), c))
}
- nat_eq(uint(i), t, nat_zero);
+ nat_eq(uint(i), t, nat_zero)
}
}
func TestNatMul(t *testing.T) {
- tester = t;
- test_msg = "NatMulA";
- nat_eq(0, mul(c, nat_zero), nat_zero);
- nat_eq(1, mul(c, nat_one), c);
+ tester = t
+ test_msg = "NatMulA"
+ nat_eq(0, mul(c, nat_zero), nat_zero)
+ nat_eq(1, mul(c, nat_one), c)
- test_msg = "NatMulB";
- nat_eq(0, b.Mul(MulRange(0, 100)), nat_zero);
- nat_eq(1, b.Mul(MulRange(21, 100)), c);
+ test_msg = "NatMulB"
+ nat_eq(0, b.Mul(MulRange(0, 100)), nat_zero)
+ nat_eq(1, b.Mul(MulRange(21, 100)), c)
- test_msg = "NatMulC";
- const n = 100;
- p := b.Mul(c).Shl(n);
+ test_msg = "NatMulC"
+ const n = 100
+ p := b.Mul(c).Shl(n)
for i := uint(0); i < n; i++ {
nat_eq(i, mul(b.Shl(i), c.Shl(n-i)), p)
}
@@ -317,17 +317,17 @@ func TestNatMul(t *testing.T) {
func TestNatDiv(t *testing.T) {
- tester = t;
- test_msg = "NatDivA";
- nat_eq(0, c.Div(nat_one), c);
- nat_eq(1, c.Div(Nat(100)), Fact(99));
- nat_eq(2, b.Div(c), nat_zero);
- nat_eq(4, nat_one.Shl(100).Div(nat_one.Shl(90)), nat_one.Shl(10));
- nat_eq(5, c.Div(b), MulRange(21, 100));
+ tester = t
+ test_msg = "NatDivA"
+ nat_eq(0, c.Div(nat_one), c)
+ nat_eq(1, c.Div(Nat(100)), Fact(99))
+ nat_eq(2, b.Div(c), nat_zero)
+ nat_eq(4, nat_one.Shl(100).Div(nat_one.Shl(90)), nat_one.Shl(10))
+ nat_eq(5, c.Div(b), MulRange(21, 100))
- test_msg = "NatDivB";
- const n = 100;
- p := Fact(n);
+ test_msg = "NatDivB"
+ const n = 100
+ p := Fact(n)
for i := uint(0); i < n; i++ {
nat_eq(100+i, p.Div(MulRange(1, i)), MulRange(i+1, n))
}
@@ -335,10 +335,10 @@ func TestNatDiv(t *testing.T) {
func TestIntQuoRem(t *testing.T) {
- tester = t;
- test_msg = "IntQuoRem";
+ tester = t
+ test_msg = "IntQuoRem"
type T struct {
- x, y, q, r int64;
+ x, y, q, r int64
}
a := []T{
T{+8, +3, +2, +2},
@@ -349,25 +349,25 @@ func TestIntQuoRem(t *testing.T) {
T{+1, -2, 0, +1},
T{-1, +2, 0, -1},
T{-1, -2, 0, -1},
- };
+ }
for i := uint(0); i < uint(len(a)); i++ {
- e := &a[i];
- x, y := Int(e.x).Mul(ip), Int(e.y).Mul(ip);
- q, r := Int(e.q), Int(e.r).Mul(ip);
- qq, rr := x.QuoRem(y);
- int_eq(4*i+0, x.Quo(y), q);
- int_eq(4*i+1, x.Rem(y), r);
- int_eq(4*i+2, qq, q);
- int_eq(4*i+3, rr, r);
+ e := &a[i]
+ x, y := Int(e.x).Mul(ip), Int(e.y).Mul(ip)
+ q, r := Int(e.q), Int(e.r).Mul(ip)
+ qq, rr := x.QuoRem(y)
+ int_eq(4*i+0, x.Quo(y), q)
+ int_eq(4*i+1, x.Rem(y), r)
+ int_eq(4*i+2, qq, q)
+ int_eq(4*i+3, rr, r)
}
}
func TestIntDivMod(t *testing.T) {
- tester = t;
- test_msg = "IntDivMod";
+ tester = t
+ test_msg = "IntDivMod"
type T struct {
- x, y, q, r int64;
+ x, y, q, r int64
}
a := []T{
T{+8, +3, +2, +2},
@@ -378,144 +378,144 @@ func TestIntDivMod(t *testing.T) {
T{+1, -2, 0, +1},
T{-1, +2, -1, +1},
T{-1, -2, +1, +1},
- };
+ }
for i := uint(0); i < uint(len(a)); i++ {
- e := &a[i];
- x, y := Int(e.x).Mul(ip), Int(e.y).Mul(ip);
- q, r := Int(e.q), Int(e.r).Mul(ip);
- qq, rr := x.DivMod(y);
- int_eq(4*i+0, x.Div(y), q);
- int_eq(4*i+1, x.Mod(y), r);
- int_eq(4*i+2, qq, q);
- int_eq(4*i+3, rr, r);
+ e := &a[i]
+ x, y := Int(e.x).Mul(ip), Int(e.y).Mul(ip)
+ q, r := Int(e.q), Int(e.r).Mul(ip)
+ qq, rr := x.DivMod(y)
+ int_eq(4*i+0, x.Div(y), q)
+ int_eq(4*i+1, x.Mod(y), r)
+ int_eq(4*i+2, qq, q)
+ int_eq(4*i+3, rr, r)
}
}
func TestNatMod(t *testing.T) {
- tester = t;
- test_msg = "NatModA";
+ tester = t
+ test_msg = "NatModA"
for i := uint(0); ; i++ {
- d := nat_one.Shl(i);
+ d := nat_one.Shl(i)
if d.Cmp(c) < 0 {
nat_eq(i, c.Add(d).Mod(c), d)
} else {
- nat_eq(i, c.Add(d).Div(c), nat_two);
- nat_eq(i, c.Add(d).Mod(c), d.Sub(c));
- break;
+ nat_eq(i, c.Add(d).Div(c), nat_two)
+ nat_eq(i, c.Add(d).Mod(c), d.Sub(c))
+ break
}
}
}
func TestNatShift(t *testing.T) {
- tester = t;
- test_msg = "NatShift1L";
- test(0, b.Shl(0).Cmp(b) == 0);
- test(1, c.Shl(1).Cmp(c) > 0);
+ tester = t
+ test_msg = "NatShift1L"
+ test(0, b.Shl(0).Cmp(b) == 0)
+ test(1, c.Shl(1).Cmp(c) > 0)
- test_msg = "NatShift1R";
- test(3, b.Shr(0).Cmp(b) == 0);
- test(4, c.Shr(1).Cmp(c) < 0);
+ test_msg = "NatShift1R"
+ test(3, b.Shr(0).Cmp(b) == 0)
+ test(4, c.Shr(1).Cmp(c) < 0)
- test_msg = "NatShift2";
+ test_msg = "NatShift2"
for i := uint(0); i < 100; i++ {
test(i, c.Shl(i).Shr(i).Cmp(c) == 0)
}
- test_msg = "NatShift3L";
+ test_msg = "NatShift3L"
{
- const m = 3;
- p := b;
- f := Nat(1 << m);
+ const m = 3
+ p := b
+ f := Nat(1 << m)
for i := uint(0); i < 100; i++ {
- nat_eq(i, b.Shl(i*m), p);
- p = mul(p, f);
+ nat_eq(i, b.Shl(i*m), p)
+ p = mul(p, f)
}
}
- test_msg = "NatShift3R";
+ test_msg = "NatShift3R"
{
- p := c;
+ p := c
for i := uint(0); !p.IsZero(); i++ {
- nat_eq(i, c.Shr(i), p);
- p = p.Shr(1);
+ nat_eq(i, c.Shr(i), p)
+ p = p.Shr(1)
}
}
}
func TestIntShift(t *testing.T) {
- tester = t;
- test_msg = "IntShift1L";
- test(0, ip.Shl(0).Cmp(ip) == 0);
- test(1, ip.Shl(1).Cmp(ip) > 0);
+ tester = t
+ test_msg = "IntShift1L"
+ test(0, ip.Shl(0).Cmp(ip) == 0)
+ test(1, ip.Shl(1).Cmp(ip) > 0)
- test_msg = "IntShift1R";
- test(0, ip.Shr(0).Cmp(ip) == 0);
- test(1, ip.Shr(1).Cmp(ip) < 0);
+ test_msg = "IntShift1R"
+ test(0, ip.Shr(0).Cmp(ip) == 0)
+ test(1, ip.Shr(1).Cmp(ip) < 0)
- test_msg = "IntShift2";
+ test_msg = "IntShift2"
for i := uint(0); i < 100; i++ {
test(i, ip.Shl(i).Shr(i).Cmp(ip) == 0)
}
- test_msg = "IntShift3L";
+ test_msg = "IntShift3L"
{
- const m = 3;
- p := ip;
- f := Int(1 << m);
+ const m = 3
+ p := ip
+ f := Int(1 << m)
for i := uint(0); i < 100; i++ {
- int_eq(i, ip.Shl(i*m), p);
- p = p.Mul(f);
+ int_eq(i, ip.Shl(i*m), p)
+ p = p.Mul(f)
}
}
- test_msg = "IntShift3R";
+ test_msg = "IntShift3R"
{
- p := ip;
+ p := ip
for i := uint(0); p.IsPos(); i++ {
- int_eq(i, ip.Shr(i), p);
- p = p.Shr(1);
+ int_eq(i, ip.Shr(i), p)
+ p = p.Shr(1)
}
}
- test_msg = "IntShift4R";
- int_eq(0, Int(-43).Shr(1), Int(-43>>1));
- int_eq(0, Int(-1024).Shr(100), Int(-1));
- int_eq(1, ip.Neg().Shr(10), ip.Neg().Div(Int(1).Shl(10)));
+ test_msg = "IntShift4R"
+ int_eq(0, Int(-43).Shr(1), Int(-43>>1))
+ int_eq(0, Int(-1024).Shr(100), Int(-1))
+ int_eq(1, ip.Neg().Shr(10), ip.Neg().Div(Int(1).Shl(10)))
}
func TestNatBitOps(t *testing.T) {
- tester = t;
+ tester = t
- x := uint64(0xf08e6f56bd8c3941);
- y := uint64(0x3984ef67834bc);
+ x := uint64(0xf08e6f56bd8c3941)
+ y := uint64(0x3984ef67834bc)
- bx := Nat(x);
- by := Nat(y);
+ bx := Nat(x)
+ by := Nat(y)
- test_msg = "NatAnd";
- bz := Nat(x & y);
+ test_msg = "NatAnd"
+ bz := Nat(x & y)
for i := uint(0); i < 100; i++ {
nat_eq(i, bx.Shl(i).And(by.Shl(i)), bz.Shl(i))
}
- test_msg = "NatAndNot";
- bz = Nat(x &^ y);
+ test_msg = "NatAndNot"
+ bz = Nat(x &^ y)
for i := uint(0); i < 100; i++ {
nat_eq(i, bx.Shl(i).AndNot(by.Shl(i)), bz.Shl(i))
}
- test_msg = "NatOr";
- bz = Nat(x | y);
+ test_msg = "NatOr"
+ bz = Nat(x | y)
for i := uint(0); i < 100; i++ {
nat_eq(i, bx.Shl(i).Or(by.Shl(i)), bz.Shl(i))
}
- test_msg = "NatXor";
- bz = Nat(x ^ y);
+ test_msg = "NatXor"
+ bz = Nat(x ^ y)
for i := uint(0); i < 100; i++ {
nat_eq(i, bx.Shl(i).Xor(by.Shl(i)), bz.Shl(i))
}
@@ -523,77 +523,77 @@ func TestNatBitOps(t *testing.T) {
func TestIntBitOps1(t *testing.T) {
- tester = t;
- test_msg = "IntBitOps1";
+ tester = t
+ test_msg = "IntBitOps1"
type T struct {
- x, y int64;
+ x, y int64
}
a := []T{
T{+7, +3},
T{+7, -3},
T{-7, +3},
T{-7, -3},
- };
+ }
for i := uint(0); i < uint(len(a)); i++ {
- e := &a[i];
- int_eq(4*i+0, Int(e.x).And(Int(e.y)), Int(e.x&e.y));
- int_eq(4*i+1, Int(e.x).AndNot(Int(e.y)), Int(e.x&^e.y));
- int_eq(4*i+2, Int(e.x).Or(Int(e.y)), Int(e.x|e.y));
- int_eq(4*i+3, Int(e.x).Xor(Int(e.y)), Int(e.x^e.y));
+ e := &a[i]
+ int_eq(4*i+0, Int(e.x).And(Int(e.y)), Int(e.x&e.y))
+ int_eq(4*i+1, Int(e.x).AndNot(Int(e.y)), Int(e.x&^e.y))
+ int_eq(4*i+2, Int(e.x).Or(Int(e.y)), Int(e.x|e.y))
+ int_eq(4*i+3, Int(e.x).Xor(Int(e.y)), Int(e.x^e.y))
}
}
func TestIntBitOps2(t *testing.T) {
- tester = t;
+ tester = t
- test_msg = "IntNot";
- int_eq(0, Int(-2).Not(), Int(1));
- int_eq(0, Int(-1).Not(), Int(0));
- int_eq(0, Int(0).Not(), Int(-1));
- int_eq(0, Int(1).Not(), Int(-2));
- int_eq(0, Int(2).Not(), Int(-3));
+ test_msg = "IntNot"
+ int_eq(0, Int(-2).Not(), Int(1))
+ int_eq(0, Int(-1).Not(), Int(0))
+ int_eq(0, Int(0).Not(), Int(-1))
+ int_eq(0, Int(1).Not(), Int(-2))
+ int_eq(0, Int(2).Not(), Int(-3))
- test_msg = "IntAnd";
+ test_msg = "IntAnd"
for x := int64(-15); x < 5; x++ {
- bx := Int(x);
+ bx := Int(x)
for y := int64(-5); y < 15; y++ {
- by := Int(y);
- for i := uint(50); i < 70; i++ { // shift across 64bit boundary
+ by := Int(y)
+ for i := uint(50); i < 70; i++ { // shift across 64bit boundary
int_eq(i, bx.Shl(i).And(by.Shl(i)), Int(x&y).Shl(i))
}
}
}
- test_msg = "IntAndNot";
+ test_msg = "IntAndNot"
for x := int64(-15); x < 5; x++ {
- bx := Int(x);
+ bx := Int(x)
for y := int64(-5); y < 15; y++ {
- by := Int(y);
- for i := uint(50); i < 70; i++ { // shift across 64bit boundary
- int_eq(2*i+0, bx.Shl(i).AndNot(by.Shl(i)), Int(x&^y).Shl(i));
- int_eq(2*i+1, bx.Shl(i).And(by.Shl(i).Not()), Int(x&^y).Shl(i));
+ by := Int(y)
+ for i := uint(50); i < 70; i++ { // shift across 64bit boundary
+ int_eq(2*i+0, bx.Shl(i).AndNot(by.Shl(i)), Int(x&^y).Shl(i))
+ int_eq(2*i+1, bx.Shl(i).And(by.Shl(i).Not()), Int(x&^y).Shl(i))
}
}
}
- test_msg = "IntOr";
+ test_msg = "IntOr"
for x := int64(-15); x < 5; x++ {
- bx := Int(x);
+ bx := Int(x)
for y := int64(-5); y < 15; y++ {
- by := Int(y);
- for i := uint(50); i < 70; i++ { // shift across 64bit boundary
+ by := Int(y)
+ for i := uint(50); i < 70; i++ { // shift across 64bit boundary
int_eq(i, bx.Shl(i).Or(by.Shl(i)), Int(x|y).Shl(i))
}
}
}
- test_msg = "IntXor";
+ test_msg = "IntXor"
for x := int64(-15); x < 5; x++ {
- bx := Int(x);
+ bx := Int(x)
for y := int64(-5); y < 15; y++ {
- by := Int(y);
- for i := uint(50); i < 70; i++ { // shift across 64bit boundary
+ by := Int(y)
+ for i := uint(50); i < 70; i++ { // shift across 64bit boundary
int_eq(i, bx.Shl(i).Xor(by.Shl(i)), Int(x^y).Shl(i))
}
}
@@ -602,27 +602,27 @@ func TestIntBitOps2(t *testing.T) {
func TestNatCmp(t *testing.T) {
- tester = t;
- test_msg = "NatCmp";
- test(0, a.Cmp(a) == 0);
- test(1, a.Cmp(b) < 0);
- test(2, b.Cmp(a) > 0);
- test(3, a.Cmp(c) < 0);
- d := c.Add(b);
- test(4, c.Cmp(d) < 0);
- test(5, d.Cmp(c) > 0);
+ tester = t
+ test_msg = "NatCmp"
+ test(0, a.Cmp(a) == 0)
+ test(1, a.Cmp(b) < 0)
+ test(2, b.Cmp(a) > 0)
+ test(3, a.Cmp(c) < 0)
+ d := c.Add(b)
+ test(4, c.Cmp(d) < 0)
+ test(5, d.Cmp(c) > 0)
}
func TestNatLog2(t *testing.T) {
- tester = t;
- test_msg = "NatLog2A";
- test(0, nat_one.Log2() == 0);
- test(1, nat_two.Log2() == 1);
- test(2, Nat(3).Log2() == 1);
- test(3, Nat(4).Log2() == 2);
+ tester = t
+ test_msg = "NatLog2A"
+ test(0, nat_one.Log2() == 0)
+ test(1, nat_two.Log2() == 1)
+ test(2, Nat(3).Log2() == 1)
+ test(3, Nat(4).Log2() == 2)
- test_msg = "NatLog2B";
+ test_msg = "NatLog2B"
for i := uint(0); i < 100; i++ {
test(i, nat_one.Shl(i).Log2() == i)
}
@@ -630,19 +630,19 @@ func TestNatLog2(t *testing.T) {
func TestNatGcd(t *testing.T) {
- tester = t;
- test_msg = "NatGcdA";
- f := Nat(99991);
- nat_eq(0, b.Mul(f).Gcd(c.Mul(f)), MulRange(1, 20).Mul(f));
+ tester = t
+ test_msg = "NatGcdA"
+ f := Nat(99991)
+ nat_eq(0, b.Mul(f).Gcd(c.Mul(f)), MulRange(1, 20).Mul(f))
}
func TestNatPow(t *testing.T) {
- tester = t;
- test_msg = "NatPowA";
- nat_eq(0, nat_two.Pow(0), nat_one);
+ tester = t
+ test_msg = "NatPowA"
+ nat_eq(0, nat_two.Pow(0), nat_one)
- test_msg = "NatPowB";
+ test_msg = "NatPowB"
for i := uint(0); i < 100; i++ {
nat_eq(i, nat_two.Pow(i), nat_one.Shl(i))
}
@@ -650,15 +650,15 @@ func TestNatPow(t *testing.T) {
func TestNatPop(t *testing.T) {
- tester = t;
- test_msg = "NatPopA";
- test(0, nat_zero.Pop() == 0);
- test(1, nat_one.Pop() == 1);
- test(2, Nat(10).Pop() == 2);
- test(3, Nat(30).Pop() == 4);
- test(4, Nat(0x1248f).Shl(33).Pop() == 8);
+ tester = t
+ test_msg = "NatPopA"
+ test(0, nat_zero.Pop() == 0)
+ test(1, nat_one.Pop() == 1)
+ test(2, Nat(10).Pop() == 2)
+ test(3, Nat(30).Pop() == 4)
+ test(4, Nat(0x1248f).Shl(33).Pop() == 8)
- test_msg = "NatPopB";
+ test_msg = "NatPopB"
for i := uint(0); i < 100; i++ {
test(i, nat_one.Shl(i).Sub(nat_one).Pop() == i)
}
diff --git a/src/pkg/bignum/integer.go b/src/pkg/bignum/integer.go
index 3d382473e1..873b2664a7 100644
--- a/src/pkg/bignum/integer.go
+++ b/src/pkg/bignum/integer.go
@@ -10,7 +10,7 @@
package bignum
import (
- "fmt";
+ "fmt"
)
// TODO(gri) Complete the set of in-place operations.
@@ -18,8 +18,8 @@ import (
// Integer represents a signed integer value of arbitrary precision.
//
type Integer struct {
- sign bool;
- mant Natural;
+ sign bool
+ mant Natural
}
@@ -29,16 +29,16 @@ type Integer struct {
//
func MakeInt(sign bool, mant Natural) *Integer {
if mant.IsZero() {
- sign = false // normalize
+ sign = false // normalize
}
- return &Integer{sign, mant};
+ return &Integer{sign, mant}
}
// Int creates a small integer with value x.
//
func Int(x int64) *Integer {
- var ux uint64;
+ var ux uint64
if x < 0 {
// For the most negative x, -x == x, and
// the bit pattern has the correct value.
@@ -46,7 +46,7 @@ func Int(x int64) *Integer {
} else {
ux = uint64(x)
}
- return MakeInt(x < 0, Nat(ux));
+ return MakeInt(x < 0, Nat(ux))
}
@@ -54,51 +54,51 @@ func Int(x int64) *Integer {
// otherwise the result is undefined.
//
func (x *Integer) Value() int64 {
- z := int64(x.mant.Value());
+ z := int64(x.mant.Value())
if x.sign {
z = -z
}
- return z;
+ return z
}
// Abs returns the absolute value of x.
//
-func (x *Integer) Abs() Natural { return x.mant }
+func (x *Integer) Abs() Natural { return x.mant }
// Predicates
// IsEven returns true iff x is divisible by 2.
//
-func (x *Integer) IsEven() bool { return x.mant.IsEven() }
+func (x *Integer) IsEven() bool { return x.mant.IsEven() }
// IsOdd returns true iff x is not divisible by 2.
//
-func (x *Integer) IsOdd() bool { return x.mant.IsOdd() }
+func (x *Integer) IsOdd() bool { return x.mant.IsOdd() }
// IsZero returns true iff x == 0.
//
-func (x *Integer) IsZero() bool { return x.mant.IsZero() }
+func (x *Integer) IsZero() bool { return x.mant.IsZero() }
// IsNeg returns true iff x < 0.
//
-func (x *Integer) IsNeg() bool { return x.sign && !x.mant.IsZero() }
+func (x *Integer) IsNeg() bool { return x.sign && !x.mant.IsZero() }
// IsPos returns true iff x >= 0.
//
-func (x *Integer) IsPos() bool { return !x.sign && !x.mant.IsZero() }
+func (x *Integer) IsPos() bool { return !x.sign && !x.mant.IsZero() }
// Operations
// Neg returns the negated value of x.
//
-func (x *Integer) Neg() *Integer { return MakeInt(!x.sign, x.mant) }
+func (x *Integer) Neg() *Integer { return MakeInt(!x.sign, x.mant) }
// Iadd sets z to the sum x + y.
@@ -108,17 +108,17 @@ func Iadd(z, x, y *Integer) {
if x.sign == y.sign {
// x + y == x + y
// (-x) + (-y) == -(x + y)
- z.sign = x.sign;
- Nadd(&z.mant, x.mant, y.mant);
+ z.sign = x.sign
+ Nadd(&z.mant, x.mant, y.mant)
} else {
// x + (-y) == x - y == -(y - x)
// (-x) + y == y - x == -(x - y)
if x.mant.Cmp(y.mant) >= 0 {
- z.sign = x.sign;
- Nsub(&z.mant, x.mant, y.mant);
+ z.sign = x.sign
+ Nsub(&z.mant, x.mant, y.mant)
} else {
- z.sign = !x.sign;
- Nsub(&z.mant, y.mant, x.mant);
+ z.sign = !x.sign
+ Nsub(&z.mant, y.mant, x.mant)
}
}
}
@@ -127,9 +127,9 @@ func Iadd(z, x, y *Integer) {
// Add returns the sum x + y.
//
func (x *Integer) Add(y *Integer) *Integer {
- var z Integer;
- Iadd(&z, x, y);
- return &z;
+ var z Integer
+ Iadd(&z, x, y)
+ return &z
}
@@ -137,17 +137,17 @@ func Isub(z, x, y *Integer) {
if x.sign != y.sign {
// x - (-y) == x + y
// (-x) - y == -(x + y)
- z.sign = x.sign;
- Nadd(&z.mant, x.mant, y.mant);
+ z.sign = x.sign
+ Nadd(&z.mant, x.mant, y.mant)
} else {
// x - y == x - y == -(y - x)
// (-x) - (-y) == y - x == -(x - y)
if x.mant.Cmp(y.mant) >= 0 {
- z.sign = x.sign;
- Nsub(&z.mant, x.mant, y.mant);
+ z.sign = x.sign
+ Nsub(&z.mant, x.mant, y.mant)
} else {
- z.sign = !x.sign;
- Nsub(&z.mant, y.mant, x.mant);
+ z.sign = !x.sign
+ Nsub(&z.mant, y.mant, x.mant)
}
}
}
@@ -156,32 +156,32 @@ func Isub(z, x, y *Integer) {
// Sub returns the difference x - y.
//
func (x *Integer) Sub(y *Integer) *Integer {
- var z Integer;
- Isub(&z, x, y);
- return &z;
+ var z Integer
+ Isub(&z, x, y)
+ return &z
}
// Nscale sets *z to the scaled value (*z) * d.
//
func Iscale(z *Integer, d int64) {
- f := uint64(d);
+ f := uint64(d)
if d < 0 {
f = uint64(-d)
}
- z.sign = z.sign != (d < 0);
- Nscale(&z.mant, f);
+ z.sign = z.sign != (d < 0)
+ Nscale(&z.mant, f)
}
// Mul1 returns the product x * d.
//
func (x *Integer) Mul1(d int64) *Integer {
- f := uint64(d);
+ f := uint64(d)
if d < 0 {
f = uint64(-d)
}
- return MakeInt(x.sign != (d < 0), x.mant.Mul1(f));
+ return MakeInt(x.sign != (d < 0), x.mant.Mul1(f))
}
@@ -242,8 +242,8 @@ func (x *Integer) Rem(y *Integer) *Integer {
// If y == 0, a division-by-zero run-time error occurs.
//
func (x *Integer) QuoRem(y *Integer) (*Integer, *Integer) {
- q, r := x.mant.DivMod(y.mant);
- return MakeInt(x.sign != y.sign, q), MakeInt(x.sign, r);
+ q, r := x.mant.DivMod(y.mant)
+ return MakeInt(x.sign != y.sign, q), MakeInt(x.sign, r)
}
@@ -261,7 +261,7 @@ func (x *Integer) QuoRem(y *Integer) (*Integer, *Integer) {
// ACM press.)
//
func (x *Integer) Div(y *Integer) *Integer {
- q, r := x.QuoRem(y);
+ q, r := x.QuoRem(y)
if r.IsNeg() {
if y.IsPos() {
q = q.Sub(Int(1))
@@ -269,7 +269,7 @@ func (x *Integer) Div(y *Integer) *Integer {
q = q.Add(Int(1))
}
}
- return q;
+ return q
}
@@ -278,7 +278,7 @@ func (x *Integer) Div(y *Integer) *Integer {
// If y == 0, a division-by-zero run-time error occurs.
//
func (x *Integer) Mod(y *Integer) *Integer {
- r := x.Rem(y);
+ r := x.Rem(y)
if r.IsNeg() {
if y.IsPos() {
r = r.Add(y)
@@ -286,30 +286,30 @@ func (x *Integer) Mod(y *Integer) *Integer {
r = r.Sub(y)
}
}
- return r;
+ return r
}
// DivMod returns the pair (x.Div(y), x.Mod(y)).
//
func (x *Integer) DivMod(y *Integer) (*Integer, *Integer) {
- q, r := x.QuoRem(y);
+ q, r := x.QuoRem(y)
if r.IsNeg() {
if y.IsPos() {
- q = q.Sub(Int(1));
- r = r.Add(y);
+ q = q.Sub(Int(1))
+ r = r.Add(y)
} else {
- q = q.Add(Int(1));
- r = r.Sub(y);
+ q = q.Add(Int(1))
+ r = r.Sub(y)
}
}
- return q, r;
+ return q, r
}
// Shl implements ``shift left'' x << s. It returns x * 2^s.
//
-func (x *Integer) Shl(s uint) *Integer { return MakeInt(x.sign, x.mant.Shl(s)) }
+func (x *Integer) Shl(s uint) *Integer { return MakeInt(x.sign, x.mant.Shl(s)) }
// The bitwise operations on integers are defined on the 2's-complement
@@ -336,7 +336,7 @@ func (x *Integer) Shr(s uint) *Integer {
return MakeInt(true, x.mant.Sub(Nat(1)).Shr(s).Add(Nat(1)))
}
- return MakeInt(false, x.mant.Shr(s));
+ return MakeInt(false, x.mant.Shr(s))
}
@@ -348,7 +348,7 @@ func (x *Integer) Not() *Integer {
}
// ^x == -x-1 == -(x+1)
- return MakeInt(true, x.mant.Add(Nat(1)));
+ return MakeInt(true, x.mant.Add(Nat(1)))
}
@@ -362,16 +362,16 @@ func (x *Integer) And(y *Integer) *Integer {
}
// x & y == x & y
- return MakeInt(false, x.mant.And(y.mant));
+ return MakeInt(false, x.mant.And(y.mant))
}
// x.sign != y.sign
if x.sign {
- x, y = y, x // & is symmetric
+ x, y = y, x // & is symmetric
}
// x & (-y) == x & ^(y-1) == x &^ (y-1)
- return MakeInt(false, x.mant.AndNot(y.mant.Sub(Nat(1))));
+ return MakeInt(false, x.mant.AndNot(y.mant.Sub(Nat(1))))
}
@@ -385,7 +385,7 @@ func (x *Integer) AndNot(y *Integer) *Integer {
}
// x &^ y == x &^ y
- return MakeInt(false, x.mant.AndNot(y.mant));
+ return MakeInt(false, x.mant.AndNot(y.mant))
}
if x.sign {
@@ -394,7 +394,7 @@ func (x *Integer) AndNot(y *Integer) *Integer {
}
// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
- return MakeInt(false, x.mant.And(y.mant.Sub(Nat(1))));
+ return MakeInt(false, x.mant.And(y.mant.Sub(Nat(1))))
}
@@ -408,16 +408,16 @@ func (x *Integer) Or(y *Integer) *Integer {
}
// x | y == x | y
- return MakeInt(false, x.mant.Or(y.mant));
+ return MakeInt(false, x.mant.Or(y.mant))
}
// x.sign != y.sign
if x.sign {
- x, y = y, x // | or symmetric
+ x, y = y, x // | or symmetric
}
// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
- return MakeInt(true, y.mant.Sub(Nat(1)).AndNot(x.mant).Add(Nat(1)));
+ return MakeInt(true, y.mant.Sub(Nat(1)).AndNot(x.mant).Add(Nat(1)))
}
@@ -431,16 +431,16 @@ func (x *Integer) Xor(y *Integer) *Integer {
}
// x ^ y == x ^ y
- return MakeInt(false, x.mant.Xor(y.mant));
+ return MakeInt(false, x.mant.Xor(y.mant))
}
// x.sign != y.sign
if x.sign {
- x, y = y, x // ^ is symmetric
+ x, y = y, x // ^ is symmetric
}
// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
- return MakeInt(true, x.mant.Xor(y.mant.Sub(Nat(1))).Add(Nat(1)));
+ return MakeInt(true, x.mant.Xor(y.mant.Sub(Nat(1))).Add(Nat(1)))
}
@@ -455,10 +455,10 @@ func (x *Integer) Cmp(y *Integer) int {
// x cmp (-y) == x
// (-x) cmp y == y
// (-x) cmp (-y) == -(x cmp y)
- var r int;
+ var r int
switch {
case x.sign == y.sign:
- r = x.mant.Cmp(y.mant);
+ r = x.mant.Cmp(y.mant)
if x.sign {
r = -r
}
@@ -467,7 +467,7 @@ func (x *Integer) Cmp(y *Integer) int {
case y.sign:
r = 1
}
- return r;
+ return r
}
@@ -477,24 +477,24 @@ func (x *Integer) ToString(base uint) string {
if x.mant.IsZero() {
return "0"
}
- var s string;
+ var s string
if x.sign {
s = "-"
}
- return s + x.mant.ToString(base);
+ return s + x.mant.ToString(base)
}
// String converts x to its decimal string representation.
// x.String() is the same as x.ToString(10).
//
-func (x *Integer) String() string { return x.ToString(10) }
+func (x *Integer) String() string { return x.ToString(10) }
// Format is a support routine for fmt.Formatter. It accepts
// the formats 'b' (binary), 'o' (octal), and 'x' (hexadecimal).
//
-func (x *Integer) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(fmtbase(c))) }
+func (x *Integer) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(fmtbase(c))) }
// IntFromString returns the integer corresponding to the
@@ -509,12 +509,12 @@ func (x *Integer) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(f
//
func IntFromString(s string, base uint) (*Integer, uint, int) {
// skip sign, if any
- i0 := 0;
+ i0 := 0
if len(s) > 0 && (s[0] == '-' || s[0] == '+') {
i0 = 1
}
- mant, base, slen := NatFromString(s[i0:], base);
+ mant, base, slen := NatFromString(s[i0:], base)
- return MakeInt(i0 > 0 && s[0] == '-', mant), base, i0 + slen;
+ return MakeInt(i0 > 0 && s[0] == '-', mant), base, i0 + slen
}
diff --git a/src/pkg/bignum/nrdiv_test.go b/src/pkg/bignum/nrdiv_test.go
index 724eecec3d..725b1acea8 100644
--- a/src/pkg/bignum/nrdiv_test.go
+++ b/src/pkg/bignum/nrdiv_test.go
@@ -21,8 +21,8 @@ import "testing"
// value of an fpNat x is x.m * 2^x.e .
//
type fpNat struct {
- m Natural;
- e int;
+ m Natural
+ e int
}
@@ -34,16 +34,16 @@ func (x fpNat) sub(y fpNat) fpNat {
case d > 0:
return fpNat{x.m.Shl(uint(d)).Sub(y.m), y.e}
}
- return fpNat{x.m.Sub(y.m), x.e};
+ return fpNat{x.m.Sub(y.m), x.e}
}
// mul2 computes x*2.
-func (x fpNat) mul2() fpNat { return fpNat{x.m, x.e + 1} }
+func (x fpNat) mul2() fpNat { return fpNat{x.m, x.e + 1} }
// mul computes x*y.
-func (x fpNat) mul(y fpNat) fpNat { return fpNat{x.m.Mul(y.m), x.e + y.e} }
+func (x fpNat) mul(y fpNat) fpNat { return fpNat{x.m.Mul(y.m), x.e + y.e} }
// mant computes the (possibly truncated) Natural representation
@@ -56,7 +56,7 @@ func (x fpNat) mant() Natural {
case x.e < 0:
return x.m.Shr(uint(-x.e))
}
- return x.m;
+ return x.m
}
@@ -65,8 +65,8 @@ func (x fpNat) mant() Natural {
//
func nrDivEst(x0, y0 Natural) Natural {
if y0.IsZero() {
- panic("division by zero");
- return nil;
+ panic("division by zero")
+ return nil
}
// y0 > 0
@@ -84,78 +84,78 @@ func nrDivEst(x0, y0 Natural) Natural {
// x0 > y0 > 1
// Determine maximum result length.
- maxLen := int(x0.Log2() - y0.Log2() + 1);
+ maxLen := int(x0.Log2() - y0.Log2() + 1)
// In the following, each number x is represented
// as a mantissa x.m and an exponent x.e such that
// x = xm * 2^x.e.
- x := fpNat{x0, 0};
- y := fpNat{y0, 0};
+ x := fpNat{x0, 0}
+ y := fpNat{y0, 0}
// Determine a scale factor f = 2^e such that
// 0.5 <= y/f == y*(2^-e) < 1.0
// and scale y accordingly.
- e := int(y.m.Log2()) + 1;
- y.e -= e;
+ e := int(y.m.Log2()) + 1
+ y.e -= e
// t1
- var c = 2.9142;
- const n = 14;
- t1 := fpNat{Nat(uint64(c * (1 << n))), -n};
+ var c = 2.9142
+ const n = 14
+ t1 := fpNat{Nat(uint64(c * (1 << n))), -n}
// Compute initial value r0 for the reciprocal of y/f.
// r0 = t1 - 2*y
- r := t1.sub(y.mul2());
- two := fpNat{Nat(2), 0};
+ r := t1.sub(y.mul2())
+ two := fpNat{Nat(2), 0}
// Newton-Raphson iteration
- p := Nat(0);
+ p := Nat(0)
for i := 0; ; i++ {
// check if we are done
// TODO: Need to come up with a better test here
// as it will reduce computation time significantly.
// q = x*r/f
- q := x.mul(r);
- q.e -= e;
- res := q.mant();
+ q := x.mul(r)
+ q.e -= e
+ res := q.mant()
if res.Cmp(p) == 0 {
return res
}
- p = res;
+ p = res
// r' = r*(2 - y*r)
- r = r.mul(two.sub(y.mul(r)));
+ r = r.mul(two.sub(y.mul(r)))
// reduce mantissa size
// TODO: Find smaller bound as it will reduce
// computation time massively.
- d := int(r.m.Log2()+1) - maxLen;
+ d := int(r.m.Log2()+1) - maxLen
if d > 0 {
r = fpNat{r.m.Shr(uint(d)), r.e + d}
}
}
- panic("unreachable");
- return nil;
+ panic("unreachable")
+ return nil
}
func nrdiv(x, y Natural) (q, r Natural) {
- q = nrDivEst(x, y);
- r = x.Sub(y.Mul(q));
+ q = nrDivEst(x, y)
+ r = x.Sub(y.Mul(q))
// if r is too large, correct q and r
// (usually one iteration)
for r.Cmp(y) >= 0 {
- q = q.Add(Nat(1));
- r = r.Sub(y);
+ q = q.Add(Nat(1))
+ r = r.Sub(y)
}
- return;
+ return
}
func div(t *testing.T, x, y Natural) {
- q, r := nrdiv(x, y);
- qx, rx := x.DivMod(y);
+ q, r := nrdiv(x, y)
+ qx, rx := x.DivMod(y)
if q.Cmp(qx) != 0 {
t.Errorf("x = %s, y = %s, got q = %s, want q = %s", x, y, q, qx)
}
@@ -165,24 +165,24 @@ func div(t *testing.T, x, y Natural) {
}
-func idiv(t *testing.T, x0, y0 uint64) { div(t, Nat(x0), Nat(y0)) }
+func idiv(t *testing.T, x0, y0 uint64) { div(t, Nat(x0), Nat(y0)) }
func TestNRDiv(t *testing.T) {
- idiv(t, 17, 18);
- idiv(t, 17, 17);
- idiv(t, 17, 1);
- idiv(t, 17, 16);
- idiv(t, 17, 10);
- idiv(t, 17, 9);
- idiv(t, 17, 8);
- idiv(t, 17, 5);
- idiv(t, 17, 3);
- idiv(t, 1025, 512);
- idiv(t, 7489595, 2);
- idiv(t, 5404679459, 78495);
- idiv(t, 7484890589595, 7484890589594);
- div(t, Fact(100), Fact(91));
- div(t, Fact(1000), Fact(991));
+ idiv(t, 17, 18)
+ idiv(t, 17, 17)
+ idiv(t, 17, 1)
+ idiv(t, 17, 16)
+ idiv(t, 17, 10)
+ idiv(t, 17, 9)
+ idiv(t, 17, 8)
+ idiv(t, 17, 5)
+ idiv(t, 17, 3)
+ idiv(t, 1025, 512)
+ idiv(t, 7489595, 2)
+ idiv(t, 5404679459, 78495)
+ idiv(t, 7484890589595, 7484890589594)
+ div(t, Fact(100), Fact(91))
+ div(t, Fact(1000), Fact(991))
//div(t, Fact(10000), Fact(9991)); // takes too long - disabled for now
}
diff --git a/src/pkg/bignum/rational.go b/src/pkg/bignum/rational.go
index 9e9c3a8e08..378585e5f2 100644
--- a/src/pkg/bignum/rational.go
+++ b/src/pkg/bignum/rational.go
@@ -12,31 +12,31 @@ import "fmt"
// Rational represents a quotient a/b of arbitrary precision.
//
type Rational struct {
- a *Integer; // numerator
- b Natural; // denominator
+ a *Integer // numerator
+ b Natural // denominator
}
// MakeRat makes a rational number given a numerator a and a denominator b.
//
func MakeRat(a *Integer, b Natural) *Rational {
- f := a.mant.Gcd(b); // f > 0
+ f := a.mant.Gcd(b) // f > 0
if f.Cmp(Nat(1)) != 0 {
- a = MakeInt(a.sign, a.mant.Div(f));
- b = b.Div(f);
+ a = MakeInt(a.sign, a.mant.Div(f))
+ b = b.Div(f)
}
- return &Rational{a, b};
+ return &Rational{a, b}
}
// Rat creates a small rational number with value a0/b0.
//
func Rat(a0 int64, b0 int64) *Rational {
- a, b := Int(a0), Int(b0);
+ a, b := Int(a0), Int(b0)
if b.sign {
a = a.Neg()
}
- return MakeRat(a, b.mant);
+ return MakeRat(a, b.mant)
}
@@ -51,30 +51,30 @@ func (x *Rational) Value() (numerator *Integer, denominator Natural) {
// IsZero returns true iff x == 0.
//
-func (x *Rational) IsZero() bool { return x.a.IsZero() }
+func (x *Rational) IsZero() bool { return x.a.IsZero() }
// IsNeg returns true iff x < 0.
//
-func (x *Rational) IsNeg() bool { return x.a.IsNeg() }
+func (x *Rational) IsNeg() bool { return x.a.IsNeg() }
// IsPos returns true iff x > 0.
//
-func (x *Rational) IsPos() bool { return x.a.IsPos() }
+func (x *Rational) IsPos() bool { return x.a.IsPos() }
// IsInt returns true iff x can be written with a denominator 1
// in the form x == x'/1; i.e., if x is an integer value.
//
-func (x *Rational) IsInt() bool { return x.b.Cmp(Nat(1)) == 0 }
+func (x *Rational) IsInt() bool { return x.b.Cmp(Nat(1)) == 0 }
// Operations
// Neg returns the negated value of x.
//
-func (x *Rational) Neg() *Rational { return MakeRat(x.a.Neg(), x.b) }
+func (x *Rational) Neg() *Rational { return MakeRat(x.a.Neg(), x.b) }
// Add returns the sum x + y.
@@ -93,19 +93,19 @@ func (x *Rational) Sub(y *Rational) *Rational {
// Mul returns the product x * y.
//
-func (x *Rational) Mul(y *Rational) *Rational { return MakeRat(x.a.Mul(y.a), x.b.Mul(y.b)) }
+func (x *Rational) Mul(y *Rational) *Rational { return MakeRat(x.a.Mul(y.a), x.b.Mul(y.b)) }
// Quo returns the quotient x / y for y != 0.
// If y == 0, a division-by-zero run-time error occurs.
//
func (x *Rational) Quo(y *Rational) *Rational {
- a := x.a.MulNat(y.b);
- b := y.a.MulNat(x.b);
+ a := x.a.MulNat(y.b)
+ b := y.a.MulNat(x.b)
if b.IsNeg() {
a = a.Neg()
}
- return MakeRat(a, b.mant);
+ return MakeRat(a, b.mant)
}
@@ -115,7 +115,7 @@ func (x *Rational) Quo(y *Rational) *Rational {
// == 0 if x == y
// > 0 if x > y
//
-func (x *Rational) Cmp(y *Rational) int { return (x.a.MulNat(y.b)).Cmp(y.a.MulNat(x.b)) }
+func (x *Rational) Cmp(y *Rational) int { return (x.a.MulNat(y.b)).Cmp(y.a.MulNat(x.b)) }
// ToString converts x to a string for a given base, with 2 <= base <= 16.
@@ -123,24 +123,24 @@ func (x *Rational) Cmp(y *Rational) int { return (x.a.MulNat(y.b)).Cmp(y.a.MulNa
// it is of form "n/d".
//
func (x *Rational) ToString(base uint) string {
- s := x.a.ToString(base);
+ s := x.a.ToString(base)
if !x.IsInt() {
s += "/" + x.b.ToString(base)
}
- return s;
+ return s
}
// String converts x to its decimal string representation.
// x.String() is the same as x.ToString(10).
//
-func (x *Rational) String() string { return x.ToString(10) }
+func (x *Rational) String() string { return x.ToString(10) }
// Format is a support routine for fmt.Formatter. It accepts
// the formats 'b' (binary), 'o' (octal), and 'x' (hexadecimal).
//
-func (x *Rational) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(fmtbase(c))) }
+func (x *Rational) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(fmtbase(c))) }
// RatFromString returns the rational number corresponding to the
@@ -164,35 +164,35 @@ func (x *Rational) Format(h fmt.State, c int) { fmt.Fprintf(h, "%s", x.ToString(
//
func RatFromString(s string, base uint) (*Rational, uint, int) {
// read numerator
- a, abase, alen := IntFromString(s, base);
- b := Nat(1);
+ a, abase, alen := IntFromString(s, base)
+ b := Nat(1)
// read denominator or fraction, if any
- var blen int;
+ var blen int
if alen < len(s) {
- ch := s[alen];
+ ch := s[alen]
if ch == '/' {
- alen++;
- b, base, blen = NatFromString(s[alen:], base);
+ alen++
+ b, base, blen = NatFromString(s[alen:], base)
} else if ch == '.' {
- alen++;
- b, base, blen = NatFromString(s[alen:], abase);
- assert(base == abase);
- f := Nat(uint64(base)).Pow(uint(blen));
- a = MakeInt(a.sign, a.mant.Mul(f).Add(b));
- b = f;
+ alen++
+ b, base, blen = NatFromString(s[alen:], abase)
+ assert(base == abase)
+ f := Nat(uint64(base)).Pow(uint(blen))
+ a = MakeInt(a.sign, a.mant.Mul(f).Add(b))
+ b = f
}
}
// read exponent, if any
- rlen := alen + blen;
+ rlen := alen + blen
if rlen < len(s) {
- ch := s[rlen];
+ ch := s[rlen]
if ch == 'e' || ch == 'E' {
- rlen++;
- e, _, elen := IntFromString(s[rlen:], 10);
- rlen += elen;
- m := Nat(10).Pow(uint(e.mant.Value()));
+ rlen++
+ e, _, elen := IntFromString(s[rlen:], 10)
+ rlen += elen
+ m := Nat(10).Pow(uint(e.mant.Value()))
if e.sign {
b = b.Mul(m)
} else {
@@ -201,5 +201,5 @@ func RatFromString(s string, base uint) (*Rational, uint, int) {
}
}
- return MakeRat(a, b), base, rlen;
+ return MakeRat(a, b), base, rlen
}
diff --git a/src/pkg/bufio/bufio.go b/src/pkg/bufio/bufio.go
index 782bfe2c48..00bc53cd73 100644
--- a/src/pkg/bufio/bufio.go
+++ b/src/pkg/bufio/bufio.go
@@ -8,27 +8,27 @@
package bufio
import (
- "bytes";
- "io";
- "os";
- "strconv";
- "utf8";
+ "bytes"
+ "io"
+ "os"
+ "strconv"
+ "utf8"
)
const (
- defaultBufSize = 4096;
+ defaultBufSize = 4096
)
// Errors introduced by this package.
type Error struct {
- os.ErrorString;
+ os.ErrorString
}
var (
- ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"};
- ErrBufferFull os.Error = &Error{"bufio: buffer full"};
- errInternal os.Error = &Error{"bufio: internal error"};
+ ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"}
+ ErrBufferFull os.Error = &Error{"bufio: buffer full"}
+ errInternal os.Error = &Error{"bufio: internal error"}
)
// BufSizeError is the error representing an invalid buffer size.
@@ -43,11 +43,11 @@ func (b BufSizeError) String() string {
// Reader implements buffering for an io.Reader object.
type Reader struct {
- buf []byte;
- rd io.Reader;
- r, w int;
- err os.Error;
- lastbyte int;
+ buf []byte
+ rd io.Reader
+ r, w int
+ err os.Error
+ lastbyte int
}
// NewReaderSize creates a new Reader whose buffer has the specified size,
@@ -59,41 +59,41 @@ func NewReaderSize(rd io.Reader, size int) (*Reader, os.Error) {
return nil, BufSizeError(size)
}
// Is it already a Reader?
- b, ok := rd.(*Reader);
+ b, ok := rd.(*Reader)
if ok && len(b.buf) >= size {
return b, nil
}
- b = new(Reader);
- b.buf = make([]byte, size);
- b.rd = rd;
- b.lastbyte = -1;
- return b, nil;
+ b = new(Reader)
+ b.buf = make([]byte, size)
+ b.rd = rd
+ b.lastbyte = -1
+ return b, nil
}
// NewReader returns a new Reader whose buffer has the default size.
func NewReader(rd io.Reader) *Reader {
- b, err := NewReaderSize(rd, defaultBufSize);
+ b, err := NewReaderSize(rd, defaultBufSize)
if err != nil {
// cannot happen - defaultBufSize is a valid size
panic("bufio: NewReader: ", err.String())
}
- return b;
+ return b
}
// fill reads a new chunk into the buffer.
func (b *Reader) fill() {
// Slide existing data to beginning.
if b.w > b.r {
- copy(b.buf[0:b.w-b.r], b.buf[b.r:b.w]);
- b.w -= b.r;
+ copy(b.buf[0:b.w-b.r], b.buf[b.r:b.w])
+ b.w -= b.r
} else {
b.w = 0
}
- b.r = 0;
+ b.r = 0
// Read new data.
- n, e := b.rd.Read(b.buf[b.w:]);
- b.w += n;
+ n, e := b.rd.Read(b.buf[b.w:])
+ b.w += n
if e != nil {
b.err = e
}
@@ -105,9 +105,9 @@ func (b *Reader) fill() {
// why the read is short. At EOF, the count will be
// zero and err will be os.EOF.
func (b *Reader) Read(p []byte) (nn int, err os.Error) {
- nn = 0;
+ nn = 0
for len(p) > 0 {
- n := len(p);
+ n := len(p)
if b.w == b.r {
if b.err != nil {
return nn, b.err
@@ -115,27 +115,27 @@ func (b *Reader) Read(p []byte) (nn int, err os.Error) {
if len(p) >= len(b.buf) {
// Large read, empty buffer.
// Read directly into p to avoid copy.
- n, b.err = b.rd.Read(p);
+ n, b.err = b.rd.Read(p)
if n > 0 {
b.lastbyte = int(p[n-1])
}
- p = p[n:];
- nn += n;
- continue;
+ p = p[n:]
+ nn += n
+ continue
}
- b.fill();
- continue;
+ b.fill()
+ continue
}
if n > b.w-b.r {
n = b.w - b.r
}
- copy(p[0:n], b.buf[b.r:b.r+n]);
- p = p[n:];
- b.r += n;
- b.lastbyte = int(b.buf[b.r-1]);
- nn += n;
+ copy(p[0:n], b.buf[b.r:b.r+n])
+ p = p[n:]
+ b.r += n
+ b.lastbyte = int(b.buf[b.r-1])
+ nn += n
}
- return nn, nil;
+ return nn, nil
}
// ReadByte reads and returns a single byte.
@@ -145,29 +145,29 @@ func (b *Reader) ReadByte() (c byte, err os.Error) {
if b.err != nil {
return 0, b.err
}
- b.fill();
+ b.fill()
}
- c = b.buf[b.r];
- b.r++;
- b.lastbyte = int(c);
- return c, nil;
+ c = b.buf[b.r]
+ b.r++
+ b.lastbyte = int(c)
+ return c, nil
}
// UnreadByte unreads the last byte. Only the most recently read byte can be unread.
func (b *Reader) UnreadByte() os.Error {
if b.r == b.w && b.lastbyte >= 0 {
- b.w = 1;
- b.r = 0;
- b.buf[0] = byte(b.lastbyte);
- b.lastbyte = -1;
- return nil;
+ b.w = 1
+ b.r = 0
+ b.buf[0] = byte(b.lastbyte)
+ b.lastbyte = -1
+ return nil
}
if b.r <= 0 {
return ErrInvalidUnreadByte
}
- b.r--;
- b.lastbyte = -1;
- return nil;
+ b.r--
+ b.lastbyte = -1
+ return nil
}
// ReadRune reads a single UTF-8 encoded Unicode character and returns the
@@ -179,17 +179,17 @@ func (b *Reader) ReadRune() (rune int, size int, err os.Error) {
if b.r == b.w {
return 0, 0, b.err
}
- rune, size = int(b.buf[b.r]), 1;
+ rune, size = int(b.buf[b.r]), 1
if rune >= 0x80 {
rune, size = utf8.DecodeRune(b.buf[b.r:b.w])
}
- b.r += size;
- b.lastbyte = int(b.buf[b.r-1]);
- return rune, size, nil;
+ b.r += size
+ b.lastbyte = int(b.buf[b.r-1])
+ return rune, size, nil
}
// Buffered returns the number of bytes that can be read from the current buffer.
-func (b *Reader) Buffered() int { return b.w - b.r }
+func (b *Reader) Buffered() int { return b.w - b.r }
// ReadSlice reads until the first occurrence of delim in the input,
// returning a slice pointing at the bytes in the buffer.
@@ -204,27 +204,27 @@ func (b *Reader) Buffered() int { return b.w - b.r }
func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) {
// Look in buffer.
if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 {
- line1 := b.buf[b.r : b.r+i+1];
- b.r += i + 1;
- return line1, nil;
+ line1 := b.buf[b.r : b.r+i+1]
+ b.r += i + 1
+ return line1, nil
}
// Read more into buffer, until buffer fills or we find delim.
for {
if b.err != nil {
- line := b.buf[b.r:b.w];
- b.r = b.w;
- return line, b.err;
+ line := b.buf[b.r:b.w]
+ b.r = b.w
+ return line, b.err
}
- n := b.Buffered();
- b.fill();
+ n := b.Buffered()
+ b.fill()
// Search new part of buffer
if i := bytes.IndexByte(b.buf[n:b.w], delim); i >= 0 {
- line := b.buf[0 : n+i+1];
- b.r = n + i + 1;
- return line, nil;
+ line := b.buf[0 : n+i+1]
+ b.r = n + i + 1
+ return line, nil
}
// Buffer is full?
@@ -232,7 +232,7 @@ func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) {
return nil, ErrBufferFull
}
}
- panic("not reached");
+ panic("not reached")
}
// ReadBytes reads until the first occurrence of delim in the input,
@@ -243,69 +243,69 @@ func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) {
func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) {
// Use ReadSlice to look for array,
// accumulating full buffers.
- var frag []byte;
- var full [][]byte;
- nfull := 0;
- err = nil;
+ var frag []byte
+ var full [][]byte
+ nfull := 0
+ err = nil
for {
- var e os.Error;
- frag, e = b.ReadSlice(delim);
- if e == nil { // got final fragment
+ var e os.Error
+ frag, e = b.ReadSlice(delim)
+ if e == nil { // got final fragment
break
}
- if e != ErrBufferFull { // unexpected error
- err = e;
- break;
+ if e != ErrBufferFull { // unexpected error
+ err = e
+ break
}
// Read bytes out of buffer.
- buf := make([]byte, b.Buffered());
- var n int;
- n, e = b.Read(buf);
+ buf := make([]byte, b.Buffered())
+ var n int
+ n, e = b.Read(buf)
if e != nil {
- frag = buf[0:n];
- err = e;
- break;
+ frag = buf[0:n]
+ err = e
+ break
}
if n != len(buf) {
- frag = buf[0:n];
- err = errInternal;
- break;
+ frag = buf[0:n]
+ err = errInternal
+ break
}
// Grow list if needed.
if full == nil {
full = make([][]byte, 16)
} else if nfull >= len(full) {
- newfull := make([][]byte, len(full)*2);
+ newfull := make([][]byte, len(full)*2)
for i := 0; i < len(full); i++ {
newfull[i] = full[i]
}
- full = newfull;
+ full = newfull
}
// Save buffer
- full[nfull] = buf;
- nfull++;
+ full[nfull] = buf
+ nfull++
}
// Allocate new buffer to hold the full pieces and the fragment.
- n := 0;
+ n := 0
for i := 0; i < nfull; i++ {
n += len(full[i])
}
- n += len(frag);
+ n += len(frag)
// Copy full pieces and fragment in.
- buf := make([]byte, n);
- n = 0;
+ buf := make([]byte, n)
+ n = 0
for i := 0; i < nfull; i++ {
- copy(buf[n:n+len(full[i])], full[i]);
- n += len(full[i]);
+ copy(buf[n:n+len(full[i])], full[i])
+ n += len(full[i])
}
- copy(buf[n:n+len(frag)], frag);
- return buf, err;
+ copy(buf[n:n+len(frag)], frag)
+ return buf, err
}
// ReadString reads until the first occurrence of delim in the input,
@@ -314,8 +314,8 @@ func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) {
// it returns the data read before the error and the error itself (often os.EOF).
// ReadString returns err != nil if and only if line does not end in delim.
func (b *Reader) ReadString(delim byte) (line string, err os.Error) {
- bytes, e := b.ReadBytes(delim);
- return string(bytes), e;
+ bytes, e := b.ReadBytes(delim)
+ return string(bytes), e
}
@@ -323,10 +323,10 @@ func (b *Reader) ReadString(delim byte) (line string, err os.Error) {
// Writer implements buffering for an io.Writer object.
type Writer struct {
- err os.Error;
- buf []byte;
- n int;
- wr io.Writer;
+ err os.Error
+ buf []byte
+ n int
+ wr io.Writer
}
// NewWriterSize creates a new Writer whose buffer has the specified size,
@@ -338,24 +338,24 @@ func NewWriterSize(wr io.Writer, size int) (*Writer, os.Error) {
return nil, BufSizeError(size)
}
// Is it already a Writer?
- b, ok := wr.(*Writer);
+ b, ok := wr.(*Writer)
if ok && len(b.buf) >= size {
return b, nil
}
- b = new(Writer);
- b.buf = make([]byte, size);
- b.wr = wr;
- return b, nil;
+ b = new(Writer)
+ b.buf = make([]byte, size)
+ b.wr = wr
+ return b, nil
}
// NewWriter returns a new Writer whose buffer has the default size.
func NewWriter(wr io.Writer) *Writer {
- b, err := NewWriterSize(wr, defaultBufSize);
+ b, err := NewWriterSize(wr, defaultBufSize)
if err != nil {
// cannot happen - defaultBufSize is valid size
panic("bufio: NewWriter: ", err.String())
}
- return b;
+ return b
}
// Flush writes any buffered data to the underlying io.Writer.
@@ -363,7 +363,7 @@ func (b *Writer) Flush() os.Error {
if b.err != nil {
return b.err
}
- n, e := b.wr.Write(b.buf[0:b.n]);
+ n, e := b.wr.Write(b.buf[0:b.n])
if n < b.n && e == nil {
e = io.ErrShortWrite
}
@@ -371,19 +371,19 @@ func (b *Writer) Flush() os.Error {
if n > 0 && n < b.n {
copy(b.buf[0:b.n-n], b.buf[n:b.n])
}
- b.n -= n;
- b.err = e;
- return e;
+ b.n -= n
+ b.err = e
+ return e
}
- b.n = 0;
- return nil;
+ b.n = 0
+ return nil
}
// Available returns how many bytes are unused in the buffer.
-func (b *Writer) Available() int { return len(b.buf) - b.n }
+func (b *Writer) Available() int { return len(b.buf) - b.n }
// Buffered returns the number of bytes that have been written into the current buffer.
-func (b *Writer) Buffered() int { return b.n }
+func (b *Writer) Buffered() int { return b.n }
// Write writes the contents of p into the buffer.
// It returns the number of bytes written.
@@ -393,35 +393,35 @@ func (b *Writer) Write(p []byte) (nn int, err os.Error) {
if b.err != nil {
return 0, b.err
}
- nn = 0;
+ nn = 0
for len(p) > 0 {
- n := b.Available();
+ n := b.Available()
if n <= 0 {
if b.Flush(); b.err != nil {
break
}
- n = b.Available();
+ n = b.Available()
}
if b.Available() == 0 && len(p) >= len(b.buf) {
// Large write, empty buffer.
// Write directly from p to avoid copy.
- n, b.err = b.wr.Write(p);
- nn += n;
- p = p[n:];
+ n, b.err = b.wr.Write(p)
+ nn += n
+ p = p[n:]
if b.err != nil {
break
}
- continue;
+ continue
}
if n > len(p) {
n = len(p)
}
- copy(b.buf[b.n:b.n+n], p[0:n]);
- b.n += n;
- nn += n;
- p = p[n:];
+ copy(b.buf[b.n:b.n+n], p[0:n])
+ b.n += n
+ nn += n
+ p = p[n:]
}
- return nn, b.err;
+ return nn, b.err
}
// WriteByte writes a single byte.
@@ -432,9 +432,9 @@ func (b *Writer) WriteByte(c byte) os.Error {
if b.Available() <= 0 && b.Flush() != nil {
return b.err
}
- b.buf[b.n] = c;
- b.n++;
- return nil;
+ b.buf[b.n] = c
+ b.n++
+ return nil
}
// WriteString writes a string.
@@ -444,16 +444,16 @@ func (b *Writer) WriteString(s string) os.Error {
}
// Common case, worth making fast.
if b.Available() >= len(s) || len(b.buf) >= len(s) && b.Flush() == nil {
- for i := 0; i < len(s); i++ { // loop over bytes, not runes.
- b.buf[b.n] = s[i];
- b.n++;
+ for i := 0; i < len(s); i++ { // loop over bytes, not runes.
+ b.buf[b.n] = s[i]
+ b.n++
}
- return nil;
+ return nil
}
- for i := 0; i < len(s); i++ { // loop over bytes, not runes.
+ for i := 0; i < len(s); i++ { // loop over bytes, not runes.
b.WriteByte(s[i])
}
- return b.err;
+ return b.err
}
// buffered input and output
@@ -461,8 +461,8 @@ func (b *Writer) WriteString(s string) os.Error {
// ReadWriter stores pointers to a Reader and a Writer.
// It implements io.ReadWriter.
type ReadWriter struct {
- *Reader;
- *Writer;
+ *Reader
+ *Writer
}
// NewReadWriter allocates a new ReadWriter that dispatches to r and w.
diff --git a/src/pkg/bufio/bufio_test.go b/src/pkg/bufio/bufio_test.go
index bdd4800b4e..83152e9265 100644
--- a/src/pkg/bufio/bufio_test.go
+++ b/src/pkg/bufio/bufio_test.go
@@ -5,68 +5,68 @@
package bufio
import (
- "bytes";
- "fmt";
- "io";
- "os";
- "strings";
- "testing";
- "testing/iotest";
+ "bytes"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "testing"
+ "testing/iotest"
)
// Reads from a reader and rot13s the result.
type rot13Reader struct {
- r io.Reader;
+ r io.Reader
}
func newRot13Reader(r io.Reader) *rot13Reader {
- r13 := new(rot13Reader);
- r13.r = r;
- return r13;
+ r13 := new(rot13Reader)
+ r13.r = r
+ return r13
}
func (r13 *rot13Reader) Read(p []byte) (int, os.Error) {
- n, e := r13.r.Read(p);
+ n, e := r13.r.Read(p)
if e != nil {
return n, e
}
for i := 0; i < n; i++ {
- c := p[i] | 0x20; // lowercase byte
+ c := p[i] | 0x20 // lowercase byte
if 'a' <= c && c <= 'm' {
p[i] += 13
} else if 'n' <= c && c <= 'z' {
p[i] -= 13
}
}
- return n, nil;
+ return n, nil
}
// Call ReadByte to accumulate the text of a file
func readBytes(buf *Reader) string {
- var b [1000]byte;
- nb := 0;
+ var b [1000]byte
+ nb := 0
for {
- c, e := buf.ReadByte();
+ c, e := buf.ReadByte()
if e == os.EOF {
break
}
if e != nil {
panic("Data: " + e.String())
}
- b[nb] = c;
- nb++;
+ b[nb] = c
+ nb++
}
- return string(b[0:nb]);
+ return string(b[0:nb])
}
func TestReaderSimple(t *testing.T) {
- data := "hello world";
- b := NewReader(bytes.NewBufferString(data));
+ data := "hello world"
+ b := NewReader(bytes.NewBufferString(data))
if s := readBytes(b); s != "hello world" {
t.Errorf("simple hello world test failed: got %q", s)
}
- b = NewReader(newRot13Reader(bytes.NewBufferString(data)));
+ b = NewReader(newRot13Reader(bytes.NewBufferString(data)))
if s := readBytes(b); s != "uryyb jbeyq" {
t.Error("rot13 hello world test failed: got %q", s)
}
@@ -74,8 +74,8 @@ func TestReaderSimple(t *testing.T) {
type readMaker struct {
- name string;
- fn func(io.Reader) io.Reader;
+ name string
+ fn func(io.Reader) io.Reader
}
var readMakers = []readMaker{
@@ -88,37 +88,37 @@ var readMakers = []readMaker{
// Call ReadString (which ends up calling everything else)
// to accumulate the text of a file.
func readLines(b *Reader) string {
- s := "";
+ s := ""
for {
- s1, e := b.ReadString('\n');
+ s1, e := b.ReadString('\n')
if e == os.EOF {
break
}
if e != nil {
panic("GetLines: " + e.String())
}
- s += s1;
+ s += s1
}
- return s;
+ return s
}
// Call Read to accumulate the text of a file
func reads(buf *Reader, m int) string {
- var b [1000]byte;
- nb := 0;
+ var b [1000]byte
+ nb := 0
for {
- n, e := buf.Read(b[nb : nb+m]);
- nb += n;
+ n, e := buf.Read(b[nb : nb+m])
+ nb += n
if e == os.EOF {
break
}
}
- return string(b[0:nb]);
+ return string(b[0:nb])
}
type bufReader struct {
- name string;
- fn func(*Reader) string;
+ name string
+ fn func(*Reader) string
}
var bufreaders = []bufReader{
@@ -138,27 +138,27 @@ var bufsizes = []int{
}
func TestReader(t *testing.T) {
- var texts [31]string;
- str := "";
- all := "";
+ var texts [31]string
+ str := ""
+ all := ""
for i := 0; i < len(texts)-1; i++ {
- texts[i] = str + "\n";
- all += texts[i];
- str += string(i%26 + 'a');
+ texts[i] = str + "\n"
+ all += texts[i]
+ str += string(i%26 + 'a')
}
- texts[len(texts)-1] = all;
+ texts[len(texts)-1] = all
for h := 0; h < len(texts); h++ {
- text := texts[h];
+ text := texts[h]
for i := 0; i < len(readMakers); i++ {
for j := 0; j < len(bufreaders); j++ {
for k := 0; k < len(bufsizes); k++ {
- readmaker := readMakers[i];
- bufreader := bufreaders[j];
- bufsize := bufsizes[k];
- read := readmaker.fn(bytes.NewBufferString(text));
- buf, _ := NewReaderSize(read, bufsize);
- s := bufreader.fn(buf);
+ readmaker := readMakers[i]
+ bufreader := bufreaders[j]
+ bufsize := bufsizes[k]
+ read := readmaker.fn(bytes.NewBufferString(text))
+ buf, _ := NewReaderSize(read, bufsize)
+ s := bufreader.fn(buf)
if s != text {
t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q",
readmaker.name, bufreader.name, bufsize, text, s)
@@ -171,37 +171,37 @@ func TestReader(t *testing.T) {
// A StringReader delivers its data one string segment at a time via Read.
type StringReader struct {
- data []string;
- step int;
+ data []string
+ step int
}
func (r *StringReader) Read(p []byte) (n int, err os.Error) {
if r.step < len(r.data) {
- s := r.data[r.step];
+ s := r.data[r.step]
for i := 0; i < len(s); i++ {
p[i] = s[i]
}
- n = len(s);
- r.step++;
+ n = len(s)
+ r.step++
} else {
err = os.EOF
}
- return;
+ return
}
func readRuneSegments(t *testing.T, segments []string) {
- got := "";
- want := strings.Join(segments, "");
- r := NewReader(&StringReader{data: segments});
+ got := ""
+ want := strings.Join(segments, "")
+ r := NewReader(&StringReader{data: segments})
for {
- rune, _, err := r.ReadRune();
+ rune, _, err := r.ReadRune()
if err != nil {
if err != os.EOF {
return
}
- break;
+ break
}
- got += string(rune);
+ got += string(rune)
}
if got != want {
t.Errorf("segments=%v got=%s want=%s", segments, got, want)
@@ -226,46 +226,46 @@ func TestReadRune(t *testing.T) {
}
func TestWriter(t *testing.T) {
- var data [8192]byte;
+ var data [8192]byte
for i := 0; i < len(data); i++ {
data[i] = byte(' ' + i%('~'-' '))
}
- w := new(bytes.Buffer);
+ w := new(bytes.Buffer)
for i := 0; i < len(bufsizes); i++ {
for j := 0; j < len(bufsizes); j++ {
- nwrite := bufsizes[i];
- bs := bufsizes[j];
+ nwrite := bufsizes[i]
+ bs := bufsizes[j]
// Write nwrite bytes using buffer size bs.
// Check that the right amount makes it out
// and that the data is correct.
- w.Reset();
- buf, e := NewWriterSize(w, bs);
- context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs);
+ w.Reset()
+ buf, e := NewWriterSize(w, bs)
+ context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
if e != nil {
- t.Errorf("%s: NewWriterSize %d: %v", context, bs, e);
- continue;
+ t.Errorf("%s: NewWriterSize %d: %v", context, bs, e)
+ continue
}
- n, e1 := buf.Write(data[0:nwrite]);
+ n, e1 := buf.Write(data[0:nwrite])
if e1 != nil || n != nwrite {
- t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1);
- continue;
+ t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
+ continue
}
if e = buf.Flush(); e != nil {
t.Errorf("%s: buf.Flush = %v", context, e)
}
- written := w.Bytes();
+ written := w.Bytes()
if len(written) != nwrite {
t.Errorf("%s: %d bytes written", context, len(written))
}
for l := 0; l < len(written); l++ {
if written[i] != data[i] {
- t.Errorf("%s: wrong bytes written");
- t.Errorf("want=%s", data[0:len(written)]);
- t.Errorf("have=%s", written);
+ t.Errorf("%s: wrong bytes written")
+ t.Errorf("want=%s", data[0:len(written)])
+ t.Errorf("have=%s", written)
}
}
}
@@ -275,9 +275,9 @@ func TestWriter(t *testing.T) {
// Check that write errors are returned properly.
type errorWriterTest struct {
- n, m int;
- err os.Error;
- expect os.Error;
+ n, m int
+ err os.Error
+ expect os.Error
}
func (w errorWriterTest) Write(p []byte) (int, os.Error) {
@@ -295,13 +295,13 @@ var errorWriterTests = []errorWriterTest{
func TestWriteErrors(t *testing.T) {
for _, w := range errorWriterTests {
- buf := NewWriter(w);
- _, e := buf.Write(strings.Bytes("hello world"));
+ buf := NewWriter(w)
+ _, e := buf.Write(strings.Bytes("hello world"))
if e != nil {
- t.Errorf("Write hello to %v: %v", w, e);
- continue;
+ t.Errorf("Write hello to %v: %v", w, e)
+ continue
}
- e = buf.Flush();
+ e = buf.Flush()
if e != w.expect {
t.Errorf("Flush %v: got %v, wanted %v", w, e, w.expect)
}
@@ -309,13 +309,13 @@ func TestWriteErrors(t *testing.T) {
}
func TestNewReaderSizeIdempotent(t *testing.T) {
- const BufSize = 1000;
- b, err := NewReaderSize(bytes.NewBufferString("hello world"), BufSize);
+ const BufSize = 1000
+ b, err := NewReaderSize(bytes.NewBufferString("hello world"), BufSize)
if err != nil {
t.Error("NewReaderSize create fail", err)
}
// Does it recognize itself?
- b1, err2 := NewReaderSize(b, BufSize);
+ b1, err2 := NewReaderSize(b, BufSize)
if err2 != nil {
t.Error("NewReaderSize #2 create fail", err2)
}
@@ -323,7 +323,7 @@ func TestNewReaderSizeIdempotent(t *testing.T) {
t.Error("NewReaderSize did not detect underlying Reader")
}
// Does it wrap if existing buffer is too small?
- b2, err3 := NewReaderSize(b, 2*BufSize);
+ b2, err3 := NewReaderSize(b, 2*BufSize)
if err3 != nil {
t.Error("NewReaderSize #3 create fail", err3)
}
@@ -333,13 +333,13 @@ func TestNewReaderSizeIdempotent(t *testing.T) {
}
func TestNewWriterSizeIdempotent(t *testing.T) {
- const BufSize = 1000;
- b, err := NewWriterSize(new(bytes.Buffer), BufSize);
+ const BufSize = 1000
+ b, err := NewWriterSize(new(bytes.Buffer), BufSize)
if err != nil {
t.Error("NewWriterSize create fail", err)
}
// Does it recognize itself?
- b1, err2 := NewWriterSize(b, BufSize);
+ b1, err2 := NewWriterSize(b, BufSize)
if err2 != nil {
t.Error("NewWriterSize #2 create fail", err2)
}
@@ -347,7 +347,7 @@ func TestNewWriterSizeIdempotent(t *testing.T) {
t.Error("NewWriterSize did not detect underlying Writer")
}
// Does it wrap if existing buffer is too small?
- b2, err3 := NewWriterSize(b, 2*BufSize);
+ b2, err3 := NewWriterSize(b, 2*BufSize)
if err3 != nil {
t.Error("NewWriterSize #3 create fail", err3)
}
@@ -357,22 +357,22 @@ func TestNewWriterSizeIdempotent(t *testing.T) {
}
func TestWriteString(t *testing.T) {
- const BufSize = 8;
- buf := new(bytes.Buffer);
- b, err := NewWriterSize(buf, BufSize);
+ const BufSize = 8
+ buf := new(bytes.Buffer)
+ b, err := NewWriterSize(buf, BufSize)
if err != nil {
t.Error("NewWriterSize create fail", err)
}
- b.WriteString("0"); // easy
- b.WriteString("123456"); // still easy
- b.WriteString("7890"); // easy after flush
- b.WriteString("abcdefghijklmnopqrstuvwxy"); // hard
- b.WriteString("z");
- b.Flush();
+ b.WriteString("0") // easy
+ b.WriteString("123456") // still easy
+ b.WriteString("7890") // easy after flush
+ b.WriteString("abcdefghijklmnopqrstuvwxy") // hard
+ b.WriteString("z")
+ b.Flush()
if b.err != nil {
t.Error("WriteString", b.err)
}
- s := "01234567890abcdefghijklmnopqrstuvwxyz";
+ s := "01234567890abcdefghijklmnopqrstuvwxyz"
if string(buf.Bytes()) != s {
t.Errorf("WriteString wants %q gets %q", s, string(buf.Bytes()))
}
diff --git a/src/pkg/bytes/buffer.go b/src/pkg/bytes/buffer.go
index b302b65fa5..bbca70b067 100644
--- a/src/pkg/bytes/buffer.go
+++ b/src/pkg/bytes/buffer.go
@@ -7,15 +7,15 @@ package bytes
// Simple byte buffer for marshaling data.
import (
- "io";
- "os";
+ "io"
+ "os"
)
// Copy from string to byte array at offset doff. Assume there's room.
func copyString(dst []byte, doff int, str string) {
for soff := 0; soff < len(str); soff++ {
- dst[doff] = str[soff];
- doff++;
+ dst[doff] = str[soff]
+ doff++
}
}
@@ -23,15 +23,15 @@ func copyString(dst []byte, doff int, str string) {
// with Read and Write methods.
// The zero value for Buffer is an empty buffer ready to use.
type Buffer struct {
- buf []byte; // contents are the bytes buf[off : len(buf)]
- off int; // read at &buf[off], write at &buf[len(buf)]
- oneByte [1]byte; // avoid allocation of slice on each WriteByte
- bootstrap [64]byte; // memory to hold first slice; helps small buffers (Printf) avoid allocation.
+ buf []byte // contents are the bytes buf[off : len(buf)]
+ off int // read at &buf[off], write at &buf[len(buf)]
+ oneByte [1]byte // avoid allocation of slice on each WriteByte
+ bootstrap [64]byte // memory to hold first slice; helps small buffers (Printf) avoid allocation.
}
// Bytes returns the contents of the unread portion of the buffer;
// len(b.Bytes()) == b.Len().
-func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
+func (b *Buffer) Bytes() []byte { return b.buf[b.off:] }
// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns "<nil>".
@@ -40,12 +40,12 @@ func (b *Buffer) String() string {
// Special case, useful in debugging.
return "<nil>"
}
- return string(b.buf[b.off:]);
+ return string(b.buf[b.off:])
}
// Len returns the number of bytes of the unread portion of the buffer;
// b.Len() == len(b.Bytes()).
-func (b *Buffer) Len() int { return len(b.buf) - b.off }
+func (b *Buffer) Len() int { return len(b.buf) - b.off }
// Truncate discards all but the first n unread bytes from the buffer.
// It is an error to call b.Truncate(n) with n > b.Len().
@@ -54,64 +54,64 @@ func (b *Buffer) Truncate(n int) {
// Reuse buffer space.
b.off = 0
}
- b.buf = b.buf[0 : b.off+n];
+ b.buf = b.buf[0 : b.off+n]
}
// Reset resets the buffer so it has no content.
// b.Reset() is the same as b.Truncate(0).
-func (b *Buffer) Reset() { b.Truncate(0) }
+func (b *Buffer) Reset() { b.Truncate(0) }
// Resize buffer to guarantee enough space for n more bytes.
// After this call, the state of b.buf is inconsistent.
// It must be fixed up as is done in Write and WriteString.
func (b *Buffer) resize(n int) {
- var buf []byte;
+ var buf []byte
if b.buf == nil && n <= len(b.bootstrap) {
buf = &b.bootstrap
} else {
- buf = b.buf;
+ buf = b.buf
if len(b.buf)+n > cap(b.buf) {
// not enough space anywhere
buf = make([]byte, 2*cap(b.buf)+n)
}
- copy(buf, b.buf[b.off:]);
+ copy(buf, b.buf[b.off:])
}
- b.buf = buf;
- b.off = 0;
+ b.buf = buf
+ b.off = 0
}
// Write appends the contents of p to the buffer. The return
// value n is the length of p; err is always nil.
func (b *Buffer) Write(p []byte) (n int, err os.Error) {
- m := b.Len();
+ m := b.Len()
// If buffer is empty, reset to recover space.
if m == 0 && b.off != 0 {
b.Truncate(0)
}
- n = len(p);
+ n = len(p)
if len(b.buf)+n > cap(b.buf) {
b.resize(n)
}
- b.buf = b.buf[0 : b.off+m+n];
- copy(b.buf[b.off+m:], p);
- return n, nil;
+ b.buf = b.buf[0 : b.off+m+n]
+ copy(b.buf[b.off+m:], p)
+ return n, nil
}
// WriteString appends the contents of s to the buffer. The return
// value n is the length of s; err is always nil.
func (b *Buffer) WriteString(s string) (n int, err os.Error) {
- m := b.Len();
+ m := b.Len()
// If buffer is empty, reset to recover space.
if m == 0 && b.off != 0 {
b.Truncate(0)
}
- n = len(s);
+ n = len(s)
if len(b.buf)+n > cap(b.buf) {
b.resize(n)
}
- b.buf = b.buf[0 : b.off+m+n];
- copyString(b.buf, b.off+m, s);
- return n, nil;
+ b.buf = b.buf[0 : b.off+m+n]
+ copyString(b.buf, b.off+m, s)
+ return n, nil
}
// MinRead is the minimum slice size passed to a Read call by
@@ -131,7 +131,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
}
for {
if cap(b.buf)-len(b.buf) < MinRead {
- var newBuf []byte;
+ var newBuf []byte
// can we get space without allocation?
if b.off+cap(b.buf)-len(b.buf) >= MinRead {
// reuse beginning of buffer
@@ -140,13 +140,13 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
// not enough space at end; put space on end
newBuf = make([]byte, len(b.buf)-b.off, 2*(cap(b.buf)-b.off)+MinRead)
}
- copy(newBuf, b.buf[b.off:]);
- b.buf = newBuf;
- b.off = 0;
+ copy(newBuf, b.buf[b.off:])
+ b.buf = newBuf
+ b.off = 0
}
- m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]);
- b.buf = b.buf[b.off : len(b.buf)+m];
- n += int64(m);
+ m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
+ b.buf = b.buf[b.off : len(b.buf)+m]
+ n += int64(m)
if e == os.EOF {
break
}
@@ -154,7 +154,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
return n, e
}
}
- return n, nil; // err is EOF, so return nil explicitly
+ return n, nil // err is EOF, so return nil explicitly
}
// WriteTo writes data to w until the buffer is drained or an error
@@ -162,25 +162,25 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
// Any error encountered during the write is also returned.
func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) {
for b.off < len(b.buf) {
- m, e := w.Write(b.buf[b.off:]);
- n += int64(m);
- b.off += m;
+ m, e := w.Write(b.buf[b.off:])
+ n += int64(m)
+ b.off += m
if e != nil {
return n, e
}
}
// Buffer is now empty; reset.
- b.Truncate(0);
- return;
+ b.Truncate(0)
+ return
}
// WriteByte appends the byte c to the buffer.
// The returned error is always nil, but is included
// to match bufio.Writer's WriteByte.
func (b *Buffer) WriteByte(c byte) os.Error {
- b.oneByte[0] = c;
- b.Write(&b.oneByte);
- return nil;
+ b.oneByte[0] = c
+ b.Write(&b.oneByte)
+ return nil
}
// Read reads the next len(p) bytes from the buffer or until the buffer
@@ -190,20 +190,20 @@ func (b *Buffer) WriteByte(c byte) os.Error {
func (b *Buffer) Read(p []byte) (n int, err os.Error) {
if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space.
- b.Truncate(0);
- return 0, os.EOF;
+ b.Truncate(0)
+ return 0, os.EOF
}
- m := b.Len();
- n = len(p);
+ m := b.Len()
+ n = len(p)
if n > m {
// more bytes requested than available
n = m
}
- copy(p, b.buf[b.off:b.off+n]);
- b.off += n;
- return n, err;
+ copy(p, b.buf[b.off:b.off+n])
+ b.off += n
+ return n, err
}
// ReadByte reads and returns the next byte from the buffer.
@@ -211,22 +211,22 @@ func (b *Buffer) Read(p []byte) (n int, err os.Error) {
func (b *Buffer) ReadByte() (c byte, err os.Error) {
if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space.
- b.Truncate(0);
- return 0, os.EOF;
+ b.Truncate(0)
+ return 0, os.EOF
}
- c = b.buf[b.off];
- b.off++;
- return c, nil;
+ c = b.buf[b.off]
+ b.off++
+ return c, nil
}
// NewBuffer creates and initializes a new Buffer
// using buf as its initial contents.
-func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
+func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }
// NewBufferString creates and initializes a new Buffer
// using string s as its initial contents.
func NewBufferString(s string) *Buffer {
- buf := make([]byte, len(s));
- copyString(buf, 0, s);
- return &Buffer{buf: buf};
+ buf := make([]byte, len(s))
+ copyString(buf, 0, s)
+ return &Buffer{buf: buf}
}
diff --git a/src/pkg/bytes/buffer_test.go b/src/pkg/bytes/buffer_test.go
index c9dafad402..af637cf63c 100644
--- a/src/pkg/bytes/buffer_test.go
+++ b/src/pkg/bytes/buffer_test.go
@@ -5,29 +5,29 @@
package bytes_test
import (
- . "bytes";
- "rand";
- "testing";
+ . "bytes"
+ "rand"
+ "testing"
)
-const N = 10000 // make this bigger for a larger (and slower) test
-var data string // test data for write tests
-var bytes []byte // test data; same as data but as a slice.
+const N = 10000 // make this bigger for a larger (and slower) test
+var data string // test data for write tests
+var bytes []byte // test data; same as data but as a slice.
func init() {
- bytes = make([]byte, N);
+ bytes = make([]byte, N)
for i := 0; i < N; i++ {
bytes[i] = 'a' + byte(i%26)
}
- data = string(bytes);
+ data = string(bytes)
}
// Verify that contents of buf match the string s.
func check(t *testing.T, testname string, buf *Buffer, s string) {
- bytes := buf.Bytes();
- str := buf.String();
+ bytes := buf.Bytes()
+ str := buf.String()
if buf.Len() != len(bytes) {
t.Errorf("%s: buf.Len() == %d, len(buf.Bytes()) == %d\n", testname, buf.Len(), len(bytes))
}
@@ -50,19 +50,19 @@ func check(t *testing.T, testname string, buf *Buffer, s string) {
// The initial contents of buf corresponds to the string s;
// the result is the final contents of buf returned as a string.
func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus string) string {
- check(t, testname+" (fill 1)", buf, s);
+ check(t, testname+" (fill 1)", buf, s)
for ; n > 0; n-- {
- m, err := buf.WriteString(fus);
+ m, err := buf.WriteString(fus)
if m != len(fus) {
t.Errorf(testname+" (fill 2): m == %d, expected %d\n", m, len(fus))
}
if err != nil {
t.Errorf(testname+" (fill 3): err should always be nil, found err == %s\n", err)
}
- s += fus;
- check(t, testname+" (fill 4)", buf, s);
+ s += fus
+ check(t, testname+" (fill 4)", buf, s)
}
- return s;
+ return s
}
@@ -70,103 +70,103 @@ func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus
// The initial contents of buf corresponds to the string s;
// the result is the final contents of buf returned as a string.
func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub []byte) string {
- check(t, testname+" (fill 1)", buf, s);
+ check(t, testname+" (fill 1)", buf, s)
for ; n > 0; n-- {
- m, err := buf.Write(fub);
+ m, err := buf.Write(fub)
if m != len(fub) {
t.Errorf(testname+" (fill 2): m == %d, expected %d\n", m, len(fub))
}
if err != nil {
t.Errorf(testname+" (fill 3): err should always be nil, found err == %s\n", err)
}
- s += string(fub);
- check(t, testname+" (fill 4)", buf, s);
+ s += string(fub)
+ check(t, testname+" (fill 4)", buf, s)
}
- return s;
+ return s
}
func TestNewBuffer(t *testing.T) {
- buf := NewBuffer(bytes);
- check(t, "NewBuffer", buf, data);
+ buf := NewBuffer(bytes)
+ check(t, "NewBuffer", buf, data)
}
func TestNewBufferString(t *testing.T) {
- buf := NewBufferString(data);
- check(t, "NewBufferString", buf, data);
+ buf := NewBufferString(data)
+ check(t, "NewBufferString", buf, data)
}
// Empty buf through repeated reads into fub.
// The initial contents of buf corresponds to the string s.
func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) {
- check(t, testname+" (empty 1)", buf, s);
+ check(t, testname+" (empty 1)", buf, s)
for {
- n, err := buf.Read(fub);
+ n, err := buf.Read(fub)
if n == 0 {
break
}
if err != nil {
t.Errorf(testname+" (empty 2): err should always be nil, found err == %s\n", err)
}
- s = s[n:];
- check(t, testname+" (empty 3)", buf, s);
+ s = s[n:]
+ check(t, testname+" (empty 3)", buf, s)
}
- check(t, testname+" (empty 4)", buf, "");
+ check(t, testname+" (empty 4)", buf, "")
}
func TestBasicOperations(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 0; i < 5; i++ {
- check(t, "TestBasicOperations (1)", &buf, "");
+ check(t, "TestBasicOperations (1)", &buf, "")
- buf.Reset();
- check(t, "TestBasicOperations (2)", &buf, "");
+ buf.Reset()
+ check(t, "TestBasicOperations (2)", &buf, "")
- buf.Truncate(0);
- check(t, "TestBasicOperations (3)", &buf, "");
+ buf.Truncate(0)
+ check(t, "TestBasicOperations (3)", &buf, "")
- n, err := buf.Write(Bytes(data[0:1]));
+ n, err := buf.Write(Bytes(data[0:1]))
if n != 1 {
t.Errorf("wrote 1 byte, but n == %d\n", n)
}
if err != nil {
t.Errorf("err should always be nil, but err == %s\n", err)
}
- check(t, "TestBasicOperations (4)", &buf, "a");
+ check(t, "TestBasicOperations (4)", &buf, "a")
- buf.WriteByte(data[1]);
- check(t, "TestBasicOperations (5)", &buf, "ab");
+ buf.WriteByte(data[1])
+ check(t, "TestBasicOperations (5)", &buf, "ab")
- n, err = buf.Write(Bytes(data[2:26]));
+ n, err = buf.Write(Bytes(data[2:26]))
if n != 24 {
t.Errorf("wrote 25 bytes, but n == %d\n", n)
}
- check(t, "TestBasicOperations (6)", &buf, string(data[0:26]));
+ check(t, "TestBasicOperations (6)", &buf, string(data[0:26]))
- buf.Truncate(26);
- check(t, "TestBasicOperations (7)", &buf, string(data[0:26]));
+ buf.Truncate(26)
+ check(t, "TestBasicOperations (7)", &buf, string(data[0:26]))
- buf.Truncate(20);
- check(t, "TestBasicOperations (8)", &buf, string(data[0:20]));
+ buf.Truncate(20)
+ check(t, "TestBasicOperations (8)", &buf, string(data[0:20]))
- empty(t, "TestBasicOperations (9)", &buf, string(data[0:20]), make([]byte, 5));
- empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100));
+ empty(t, "TestBasicOperations (9)", &buf, string(data[0:20]), make([]byte, 5))
+ empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100))
- buf.WriteByte(data[1]);
- c, err := buf.ReadByte();
+ buf.WriteByte(data[1])
+ c, err := buf.ReadByte()
if err != nil {
t.Errorf("ReadByte unexpected eof\n")
}
if c != data[1] {
t.Errorf("ReadByte wrong value c=%v\n", c)
}
- c, err = buf.ReadByte();
+ c, err = buf.ReadByte()
if err == nil {
t.Errorf("ReadByte unexpected not eof\n")
}
@@ -175,67 +175,67 @@ func TestBasicOperations(t *testing.T) {
func TestLargeStringWrites(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 3; i < 30; i += 3 {
- s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, data);
- empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(data)/i));
+ s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, data)
+ empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(data)/i))
}
- check(t, "TestLargeStringWrites (3)", &buf, "");
+ check(t, "TestLargeStringWrites (3)", &buf, "")
}
func TestLargeByteWrites(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 3; i < 30; i += 3 {
- s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, bytes);
- empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(data)/i));
+ s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, bytes)
+ empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(data)/i))
}
- check(t, "TestLargeByteWrites (3)", &buf, "");
+ check(t, "TestLargeByteWrites (3)", &buf, "")
}
func TestLargeStringReads(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 3; i < 30; i += 3 {
- s := fillString(t, "TestLargeReads (1)", &buf, "", 5, data[0:len(data)/i]);
- empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data)));
+ s := fillString(t, "TestLargeReads (1)", &buf, "", 5, data[0:len(data)/i])
+ empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data)))
}
- check(t, "TestLargeStringReads (3)", &buf, "");
+ check(t, "TestLargeStringReads (3)", &buf, "")
}
func TestLargeByteReads(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 3; i < 30; i += 3 {
- s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, bytes[0:len(bytes)/i]);
- empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data)));
+ s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, bytes[0:len(bytes)/i])
+ empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data)))
}
- check(t, "TestLargeByteReads (3)", &buf, "");
+ check(t, "TestLargeByteReads (3)", &buf, "")
}
func TestMixedReadsAndWrites(t *testing.T) {
- var buf Buffer;
- s := "";
+ var buf Buffer
+ s := ""
for i := 0; i < 50; i++ {
- wlen := rand.Intn(len(data));
+ wlen := rand.Intn(len(data))
if i%2 == 0 {
s = fillString(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, data[0:wlen])
} else {
s = fillBytes(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, bytes[0:wlen])
}
- rlen := rand.Intn(len(data));
- fub := make([]byte, rlen);
- n, _ := buf.Read(fub);
- s = s[n:];
+ rlen := rand.Intn(len(data))
+ fub := make([]byte, rlen)
+ n, _ := buf.Read(fub)
+ s = s[n:]
}
- empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()));
+ empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len()))
}
func TestNil(t *testing.T) {
- var b *Buffer;
+ var b *Buffer
if b.String() != "<nil>" {
t.Error("expcted <nil>; got %q", b.String())
}
@@ -243,22 +243,22 @@ func TestNil(t *testing.T) {
func TestReadFrom(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 3; i < 30; i += 3 {
- s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, bytes[0:len(bytes)/i]);
- var b Buffer;
- b.ReadFrom(&buf);
- empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data)));
+ s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, bytes[0:len(bytes)/i])
+ var b Buffer
+ b.ReadFrom(&buf)
+ empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data)))
}
}
func TestWriteTo(t *testing.T) {
- var buf Buffer;
+ var buf Buffer
for i := 3; i < 30; i += 3 {
- s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, bytes[0:len(bytes)/i]);
- var b Buffer;
- buf.WriteTo(&b);
- empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data)));
+ s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, bytes[0:len(bytes)/i])
+ var b Buffer
+ buf.WriteTo(&b)
+ empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data)))
}
}
diff --git a/src/pkg/bytes/bytes.go b/src/pkg/bytes/bytes.go
index 85d4f9fd76..0a21464133 100644
--- a/src/pkg/bytes/bytes.go
+++ b/src/pkg/bytes/bytes.go
@@ -7,8 +7,8 @@
package bytes
import (
- "unicode";
- "utf8";
+ "unicode"
+ "utf8"
)
// Compare returns an integer comparing the two byte arrays lexicographically.
@@ -28,7 +28,7 @@ func Compare(a, b []byte) int {
case len(a) > len(b):
return 1
}
- return 0;
+ return 0
}
// Equal returns a boolean reporting whether a == b.
@@ -41,7 +41,7 @@ func Equal(a, b []byte) bool {
return false
}
}
- return true;
+ return true
}
// explode splits s into an array of UTF-8 sequences, one per Unicode character (still arrays of bytes),
@@ -50,21 +50,21 @@ func explode(s []byte, n int) [][]byte {
if n <= 0 {
n = len(s)
}
- a := make([][]byte, n);
- var size int;
- na := 0;
+ a := make([][]byte, n)
+ var size int
+ na := 0
for len(s) > 0 {
if na+1 >= n {
- a[na] = s;
- na++;
- break;
+ a[na] = s
+ na++
+ break
}
- _, size = utf8.DecodeRune(s);
- a[na] = s[0:size];
- s = s[size:];
- na++;
+ _, size = utf8.DecodeRune(s)
+ a[na] = s[0:size]
+ s = s[size:]
+ na++
}
- return a[0:na];
+ return a[0:na]
}
// Count counts the number of non-overlapping instances of sep in s.
@@ -72,34 +72,34 @@ func Count(s, sep []byte) int {
if len(sep) == 0 {
return utf8.RuneCount(s) + 1
}
- c := sep[0];
- n := 0;
+ c := sep[0]
+ n := 0
for i := 0; i+len(sep) <= len(s); i++ {
if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) {
- n++;
- i += len(sep) - 1;
+ n++
+ i += len(sep) - 1
}
}
- return n;
+ return n
}
// Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
func Index(s, sep []byte) int {
- n := len(sep);
+ n := len(sep)
if n == 0 {
return 0
}
- c := sep[0];
+ c := sep[0]
for i := 0; i+n <= len(s); i++ {
if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) {
return i
}
}
- return -1;
+ return -1
}
// IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s.
-func IndexByte(s []byte, c byte) int // asm_$GOARCH.s
+func IndexByte(s []byte, c byte) int // asm_$GOARCH.s
func indexBytePortable(s []byte, c byte) int {
for i, b := range s {
@@ -107,22 +107,22 @@ func indexBytePortable(s []byte, c byte) int {
return i
}
}
- return -1;
+ return -1
}
// LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.
func LastIndex(s, sep []byte) int {
- n := len(sep);
+ n := len(sep)
if n == 0 {
return len(s)
}
- c := sep[0];
+ c := sep[0]
for i := len(s) - n; i >= 0; i-- {
if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) {
return i
}
}
- return -1;
+ return -1
}
// Generic split: splits after each instance of sep,
@@ -134,26 +134,26 @@ func genSplit(s, sep []byte, sepSave, n int) [][]byte {
if n <= 0 {
n = Count(s, sep) + 1
}
- c := sep[0];
- start := 0;
- a := make([][]byte, n);
- na := 0;
+ c := sep[0]
+ start := 0
+ a := make([][]byte, n)
+ na := 0
for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) {
- a[na] = s[start : i+sepSave];
- na++;
- start = i + len(sep);
- i += len(sep) - 1;
+ a[na] = s[start : i+sepSave]
+ na++
+ start = i + len(sep)
+ i += len(sep) - 1
}
}
- a[na] = s[start:];
- return a[0 : na+1];
+ a[na] = s[start:]
+ return a[0 : na+1]
}
// Split splits the array s around each instance of sep, returning an array of subarrays of s.
// If sep is empty, Split splits s after each UTF-8 sequence.
// If n > 0, Split splits s into at most n subarrays; the last subarray will contain an unsplit remainder.
-func Split(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) }
+func Split(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) }
// SplitAfter splits the array s after each instance of sep, returning an array of subarrays of s.
// If sep is empty, SplitAfter splits s after each UTF-8 sequence.
@@ -172,28 +172,28 @@ func Join(a [][]byte, sep []byte) []byte {
if len(a) == 1 {
return a[0]
}
- n := len(sep) * (len(a) - 1);
+ n := len(sep) * (len(a) - 1)
for i := 0; i < len(a); i++ {
n += len(a[i])
}
- b := make([]byte, n);
- bp := 0;
+ b := make([]byte, n)
+ bp := 0
for i := 0; i < len(a); i++ {
- s := a[i];
+ s := a[i]
for j := 0; j < len(s); j++ {
- b[bp] = s[j];
- bp++;
+ b[bp] = s[j]
+ bp++
}
if i+1 < len(a) {
- s = sep;
+ s = sep
for j := 0; j < len(s); j++ {
- b[bp] = s[j];
- bp++;
+ b[bp] = s[j]
+ bp++
}
}
}
- return b;
+ return b
}
// HasPrefix tests whether the byte array s begins with prefix.
@@ -213,88 +213,88 @@ func Map(mapping func(rune int) int, s []byte) []byte {
// In the worst case, the array can grow when mapped, making
// things unpleasant. But it's so rare we barge in assuming it's
// fine. It could also shrink but that falls out naturally.
- maxbytes := len(s); // length of b
- nbytes := 0; // number of bytes encoded in b
- b := make([]byte, maxbytes);
+ maxbytes := len(s) // length of b
+ nbytes := 0 // number of bytes encoded in b
+ b := make([]byte, maxbytes)
for i := 0; i < len(s); {
- wid := 1;
- rune := int(s[i]);
+ wid := 1
+ rune := int(s[i])
if rune >= utf8.RuneSelf {
rune, wid = utf8.DecodeRune(s[i:])
}
- rune = mapping(rune);
+ rune = mapping(rune)
if rune >= 0 {
if nbytes+utf8.RuneLen(rune) > maxbytes {
// Grow the buffer.
- maxbytes = maxbytes*2 + utf8.UTFMax;
- nb := make([]byte, maxbytes);
+ maxbytes = maxbytes*2 + utf8.UTFMax
+ nb := make([]byte, maxbytes)
for i, c := range b[0:nbytes] {
nb[i] = c
}
- b = nb;
+ b = nb
}
- nbytes += utf8.EncodeRune(rune, b[nbytes:maxbytes]);
+ nbytes += utf8.EncodeRune(rune, b[nbytes:maxbytes])
}
- i += wid;
+ i += wid
}
- return b[0:nbytes];
+ return b[0:nbytes]
}
// Repeat returns a new byte array consisting of count copies of b.
func Repeat(b []byte, count int) []byte {
- nb := make([]byte, len(b)*count);
- bp := 0;
+ nb := make([]byte, len(b)*count)
+ bp := 0
for i := 0; i < count; i++ {
for j := 0; j < len(b); j++ {
- nb[bp] = b[j];
- bp++;
+ nb[bp] = b[j]
+ bp++
}
}
- return nb;
+ return nb
}
// ToUpper returns a copy of the byte array s with all Unicode letters mapped to their upper case.
-func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) }
+func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) }
// ToUpper returns a copy of the byte array s with all Unicode letters mapped to their lower case.
-func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) }
+func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) }
// ToTitle returns a copy of the byte array s with all Unicode letters mapped to their title case.
-func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
+func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
// Trim returns a slice of the string s, with all leading and trailing white space
// removed, as defined by Unicode.
func TrimSpace(s []byte) []byte {
- start, end := 0, len(s);
+ start, end := 0, len(s)
for start < end {
- wid := 1;
- rune := int(s[start]);
+ wid := 1
+ rune := int(s[start])
if rune >= utf8.RuneSelf {
rune, wid = utf8.DecodeRune(s[start:end])
}
if !unicode.IsSpace(rune) {
break
}
- start += wid;
+ start += wid
}
for start < end {
- wid := 1;
- rune := int(s[end-1]);
+ wid := 1
+ rune := int(s[end-1])
if rune >= utf8.RuneSelf {
// Back up carefully looking for beginning of rune. Mustn't pass start.
for wid = 2; start <= end-wid && !utf8.RuneStart(s[end-wid]); wid++ {
}
- if start > end-wid { // invalid UTF-8 sequence; stop processing
+ if start > end-wid { // invalid UTF-8 sequence; stop processing
return s[start:end]
}
- rune, wid = utf8.DecodeRune(s[end-wid : end]);
+ rune, wid = utf8.DecodeRune(s[end-wid : end])
}
if !unicode.IsSpace(rune) {
break
}
- end -= wid;
+ end -= wid
}
- return s[start:end];
+ return s[start:end]
}
// How big to make a byte array when growing.
@@ -303,51 +303,51 @@ func resize(n int) int {
if n < 16 {
n = 16
}
- return n + n/2;
+ return n + n/2
}
// Add appends the contents of t to the end of s and returns the result.
// If s has enough capacity, it is extended in place; otherwise a
// new array is allocated and returned.
func Add(s, t []byte) []byte {
- lens := len(s);
- lent := len(t);
+ lens := len(s)
+ lent := len(t)
if lens+lent <= cap(s) {
s = s[0 : lens+lent]
} else {
- news := make([]byte, lens+lent, resize(lens+lent));
- copy(news, s);
- s = news;
+ news := make([]byte, lens+lent, resize(lens+lent))
+ copy(news, s)
+ s = news
}
- copy(s[lens:lens+lent], t);
- return s;
+ copy(s[lens:lens+lent], t)
+ return s
}
// AddByte appends byte b to the end of s and returns the result.
// If s has enough capacity, it is extended in place; otherwise a
// new array is allocated and returned.
func AddByte(s []byte, t byte) []byte {
- lens := len(s);
+ lens := len(s)
if lens+1 <= cap(s) {
s = s[0 : lens+1]
} else {
- news := make([]byte, lens+1, resize(lens+1));
- copy(news, s);
- s = news;
+ news := make([]byte, lens+1, resize(lens+1))
+ copy(news, s)
+ s = news
}
- s[lens] = t;
- return s;
+ s[lens] = t
+ return s
}
// Runes returns a slice of runes (Unicode code points) equivalent to s.
func Runes(s []byte) []int {
- t := make([]int, utf8.RuneCount(s));
- i := 0;
+ t := make([]int, utf8.RuneCount(s))
+ i := 0
for len(s) > 0 {
- r, l := utf8.DecodeRune(s);
- t[i] = r;
- i++;
- s = s[l:];
+ r, l := utf8.DecodeRune(s)
+ t[i] = r
+ i++
+ s = s[l:]
}
- return t;
+ return t
}
diff --git a/src/pkg/bytes/bytes_test.go b/src/pkg/bytes/bytes_test.go
index 3f77e6e9ff..4c6d4166a0 100644
--- a/src/pkg/bytes/bytes_test.go
+++ b/src/pkg/bytes/bytes_test.go
@@ -5,10 +5,10 @@
package bytes_test
import (
- . "bytes";
- "strings";
- "testing";
- "unicode";
+ . "bytes"
+ "strings"
+ "testing"
+ "unicode"
)
func eq(a, b []string) bool {
@@ -20,15 +20,15 @@ func eq(a, b []string) bool {
return false
}
}
- return true;
+ return true
}
func arrayOfString(a [][]byte) []string {
- result := make([]string, len(a));
+ result := make([]string, len(a))
for j := 0; j < len(a); j++ {
result[j] = string(a[j])
}
- return result;
+ return result
}
// For ease of reading, the test cases use strings that are converted to byte
@@ -40,9 +40,9 @@ var commas = "1,2,3,4"
var dots = "1....2....3....4"
type BinOpTest struct {
- a string;
- b string;
- i int;
+ a string
+ b string
+ i int
}
var comparetests = []BinOpTest{
@@ -60,10 +60,10 @@ var comparetests = []BinOpTest{
func TestCompare(t *testing.T) {
for _, tt := range comparetests {
- a := strings.Bytes(tt.a);
- b := strings.Bytes(tt.b);
- cmp := Compare(a, b);
- eql := Equal(a, b);
+ a := strings.Bytes(tt.a)
+ b := strings.Bytes(tt.b)
+ cmp := Compare(a, b)
+ eql := Equal(a, b)
if cmp != tt.i {
t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp)
}
@@ -94,9 +94,9 @@ var indextests = []BinOpTest{
func TestIndex(t *testing.T) {
for _, tt := range indextests {
- a := strings.Bytes(tt.a);
- b := strings.Bytes(tt.b);
- pos := Index(a, b);
+ a := strings.Bytes(tt.a)
+ b := strings.Bytes(tt.b)
+ pos := Index(a, b)
if pos != tt.i {
t.Errorf(`Index(%q, %q) = %v`, tt.a, tt.b, pos)
}
@@ -108,24 +108,24 @@ func TestIndexByte(t *testing.T) {
if len(tt.b) != 1 {
continue
}
- a := strings.Bytes(tt.a);
- b := tt.b[0];
- pos := IndexByte(a, b);
+ a := strings.Bytes(tt.a)
+ b := tt.b[0]
+ pos := IndexByte(a, b)
if pos != tt.i {
t.Errorf(`IndexByte(%q, '%c') = %v`, tt.a, b, pos)
}
- posp := IndexBytePortable(a, b);
+ posp := IndexBytePortable(a, b)
if posp != tt.i {
t.Errorf(`indexBytePortable(%q, '%c') = %v`, tt.a, b, posp)
}
}
}
-func BenchmarkIndexByte4K(b *testing.B) { bmIndex(b, IndexByte, 4<<10) }
+func BenchmarkIndexByte4K(b *testing.B) { bmIndex(b, IndexByte, 4<<10) }
-func BenchmarkIndexByte4M(b *testing.B) { bmIndex(b, IndexByte, 4<<20) }
+func BenchmarkIndexByte4M(b *testing.B) { bmIndex(b, IndexByte, 4<<20) }
-func BenchmarkIndexByte64M(b *testing.B) { bmIndex(b, IndexByte, 64<<20) }
+func BenchmarkIndexByte64M(b *testing.B) { bmIndex(b, IndexByte, 64<<20) }
func BenchmarkIndexBytePortable4K(b *testing.B) {
bmIndex(b, IndexBytePortable, 4<<10)
@@ -145,22 +145,22 @@ func bmIndex(b *testing.B, index func([]byte, byte) int, n int) {
if len(bmbuf) < n {
bmbuf = make([]byte, n)
}
- b.SetBytes(int64(n));
- buf := bmbuf[0:n];
- buf[n-1] = 'x';
+ b.SetBytes(int64(n))
+ buf := bmbuf[0:n]
+ buf[n-1] = 'x'
for i := 0; i < b.N; i++ {
- j := index(buf, 'x');
+ j := index(buf, 'x')
if j != n-1 {
panic("bad index", j)
}
}
- buf[n-1] = '0';
+ buf[n-1] = '0'
}
type ExplodeTest struct {
- s string;
- n int;
- a []string;
+ s string
+ n int
+ a []string
}
var explodetests = []ExplodeTest{
@@ -171,13 +171,13 @@ var explodetests = []ExplodeTest{
func TestExplode(t *testing.T) {
for _, tt := range (explodetests) {
- a := Split(strings.Bytes(tt.s), nil, tt.n);
- result := arrayOfString(a);
+ a := Split(strings.Bytes(tt.s), nil, tt.n)
+ result := arrayOfString(a)
if !eq(result, tt.a) {
- t.Errorf(`Explode("%s", %d) = %v; want %v`, tt.s, tt.n, result, tt.a);
- continue;
+ t.Errorf(`Explode("%s", %d) = %v; want %v`, tt.s, tt.n, result, tt.a)
+ continue
}
- s := Join(a, []byte{});
+ s := Join(a, []byte{})
if string(s) != tt.s {
t.Errorf(`Join(Explode("%s", %d), "") = "%s"`, tt.s, tt.n, s)
}
@@ -186,10 +186,10 @@ func TestExplode(t *testing.T) {
type SplitTest struct {
- s string;
- sep string;
- n int;
- a []string;
+ s string
+ sep string
+ n int
+ a []string
}
var splittests = []SplitTest{
@@ -210,13 +210,13 @@ var splittests = []SplitTest{
func TestSplit(t *testing.T) {
for _, tt := range splittests {
- a := Split(strings.Bytes(tt.s), strings.Bytes(tt.sep), tt.n);
- result := arrayOfString(a);
+ a := Split(strings.Bytes(tt.s), strings.Bytes(tt.sep), tt.n)
+ result := arrayOfString(a)
if !eq(result, tt.a) {
- t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a);
- continue;
+ t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
+ continue
}
- s := Join(a, strings.Bytes(tt.sep));
+ s := Join(a, strings.Bytes(tt.sep))
if string(s) != tt.s {
t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
}
@@ -241,13 +241,13 @@ var splitaftertests = []SplitTest{
func TestSplitAfter(t *testing.T) {
for _, tt := range splitaftertests {
- a := SplitAfter(strings.Bytes(tt.s), strings.Bytes(tt.sep), tt.n);
- result := arrayOfString(a);
+ a := SplitAfter(strings.Bytes(tt.s), strings.Bytes(tt.sep), tt.n)
+ result := arrayOfString(a)
if !eq(result, tt.a) {
- t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a);
- continue;
+ t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
+ continue
}
- s := Join(a, nil);
+ s := Join(a, nil)
if string(s) != tt.s {
t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
}
@@ -257,7 +257,7 @@ func TestSplitAfter(t *testing.T) {
// Test case for any function which accepts and returns a byte array.
// For ease of creation, we write the byte arrays as strings.
type StringTest struct {
- in, out string;
+ in, out string
}
var upperTests = []StringTest{
@@ -265,7 +265,7 @@ var upperTests = []StringTest{
StringTest{"abc", "ABC"},
StringTest{"AbC123", "ABC123"},
StringTest{"azAZ09_", "AZAZ09_"},
- StringTest{"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char
+ StringTest{"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char
}
var lowerTests = []StringTest{
@@ -273,7 +273,7 @@ var lowerTests = []StringTest{
StringTest{"abc", "abc"},
StringTest{"AbC123", "abc123"},
StringTest{"azAZ09_", "azaz09_"},
- StringTest{"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"}, // shrinks one byte per char
+ StringTest{"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"}, // shrinks one byte per char
}
const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
@@ -287,25 +287,25 @@ var trimSpaceTests = []StringTest{
StringTest{" \t\r\n x\t\t\r\r\n\n ", "x"},
StringTest{" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", "x\t\t\r\r\ny"},
StringTest{"1 \t\r\n2", "1 \t\r\n2"},
- StringTest{" x\x80", "x\x80"}, // invalid UTF-8 on end
- StringTest{" x\xc0", "x\xc0"}, // invalid UTF-8 on end
+ StringTest{" x\x80", "x\x80"}, // invalid UTF-8 on end
+ StringTest{" x\xc0", "x\xc0"}, // invalid UTF-8 on end
}
// Bytes returns a new slice containing the bytes in s.
// Borrowed from strings to avoid dependency.
func Bytes(s string) []byte {
- b := make([]byte, len(s));
+ b := make([]byte, len(s))
for i := 0; i < len(s); i++ {
b[i] = s[i]
}
- return b;
+ return b
}
// Execute f on each test case. funcName should be the name of f; it's used
// in failure reports.
func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCases []StringTest) {
for _, tc := range testCases {
- actual := string(f(Bytes(tc.in)));
+ actual := string(f(Bytes(tc.in)))
if actual != tc.out {
t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
}
@@ -313,55 +313,55 @@ func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCa
}
func tenRunes(rune int) string {
- r := make([]int, 10);
+ r := make([]int, 10)
for i := range r {
r[i] = rune
}
- return string(r);
+ return string(r)
}
// User-defined self-inverse mapping function
func rot13(rune int) int {
- step := 13;
+ step := 13
if rune >= 'a' && rune <= 'z' {
return ((rune - 'a' + step) % 26) + 'a'
}
if rune >= 'A' && rune <= 'Z' {
return ((rune - 'A' + step) % 26) + 'A'
}
- return rune;
+ return rune
}
func TestMap(t *testing.T) {
// Run a couple of awful growth/shrinkage tests
- a := tenRunes('a');
+ a := tenRunes('a')
// 1. Grow. This triggers two reallocations in Map.
- maxRune := func(rune int) int { return unicode.MaxRune };
- m := Map(maxRune, Bytes(a));
- expect := tenRunes(unicode.MaxRune);
+ maxRune := func(rune int) int { return unicode.MaxRune }
+ m := Map(maxRune, Bytes(a))
+ expect := tenRunes(unicode.MaxRune)
if string(m) != expect {
t.Errorf("growing: expected %q got %q", expect, m)
}
// 2. Shrink
- minRune := func(rune int) int { return 'a' };
- m = Map(minRune, Bytes(tenRunes(unicode.MaxRune)));
- expect = a;
+ minRune := func(rune int) int { return 'a' }
+ m = Map(minRune, Bytes(tenRunes(unicode.MaxRune)))
+ expect = a
if string(m) != expect {
t.Errorf("shrinking: expected %q got %q", expect, m)
}
// 3. Rot13
- m = Map(rot13, Bytes("a to zed"));
- expect = "n gb mrq";
+ m = Map(rot13, Bytes("a to zed"))
+ expect = "n gb mrq"
if string(m) != expect {
t.Errorf("rot13: expected %q got %q", expect, m)
}
// 4. Rot13^2
- m = Map(rot13, Map(rot13, Bytes("a to zed")));
- expect = "a to zed";
+ m = Map(rot13, Map(rot13, Bytes("a to zed")))
+ expect = "a to zed"
if string(m) != expect {
t.Errorf("rot13: expected %q got %q", expect, m)
}
@@ -371,24 +371,24 @@ func TestMap(t *testing.T) {
if unicode.Is(unicode.Latin, rune) {
return rune
}
- return -1;
- };
- m = Map(dropNotLatin, Bytes("Hello, 세계"));
- expect = "Hello";
+ return -1
+ }
+ m = Map(dropNotLatin, Bytes("Hello, 세계"))
+ expect = "Hello"
if string(m) != expect {
t.Errorf("drop: expected %q got %q", expect, m)
}
}
-func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
+func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
-func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
+func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
-func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
+func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
type AddTest struct {
- s, t string;
- cap int;
+ s, t string
+ cap int
}
var addtests = []AddTest{
@@ -400,11 +400,11 @@ var addtests = []AddTest{
func TestAdd(t *testing.T) {
for _, test := range addtests {
- b := make([]byte, len(test.s), test.cap);
+ b := make([]byte, len(test.s), test.cap)
for i := 0; i < len(test.s); i++ {
b[i] = test.s[i]
}
- b = Add(b, strings.Bytes(test.t));
+ b = Add(b, strings.Bytes(test.t))
if string(b) != test.s+test.t {
t.Errorf("Add(%q,%q) = %q", test.s, test.t, string(b))
}
@@ -412,8 +412,8 @@ func TestAdd(t *testing.T) {
}
func TestAddByte(t *testing.T) {
- const N = 2e5;
- b := make([]byte, 0);
+ const N = 2e5
+ b := make([]byte, 0)
for i := 0; i < N; i++ {
b = AddByte(b, byte(i))
}
@@ -428,8 +428,8 @@ func TestAddByte(t *testing.T) {
}
type RepeatTest struct {
- in, out string;
- count int;
+ in, out string
+ count int
}
var RepeatTests = []RepeatTest{
@@ -444,12 +444,12 @@ var RepeatTests = []RepeatTest{
func TestRepeat(t *testing.T) {
for _, tt := range RepeatTests {
- tin := strings.Bytes(tt.in);
- tout := strings.Bytes(tt.out);
- a := Repeat(tin, tt.count);
+ tin := strings.Bytes(tt.in)
+ tout := strings.Bytes(tt.out)
+ a := Repeat(tin, tt.count)
if !Equal(a, tout) {
- t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout);
- continue;
+ t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout)
+ continue
}
}
}
@@ -463,13 +463,13 @@ func runesEqual(a, b []int) bool {
return false
}
}
- return true;
+ return true
}
type RunesTest struct {
- in string;
- out []int;
- lossy bool;
+ in string
+ out []int
+ lossy bool
}
var RunesTests = []RunesTest{
@@ -484,15 +484,15 @@ var RunesTests = []RunesTest{
func TestRunes(t *testing.T) {
for _, tt := range RunesTests {
- tin := strings.Bytes(tt.in);
- a := Runes(tin);
+ tin := strings.Bytes(tt.in)
+ a := Runes(tin)
if !runesEqual(a, tt.out) {
- t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out);
- continue;
+ t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out)
+ continue
}
if !tt.lossy {
// can only test reassembly if we didn't lose information
- s := string(a);
+ s := string(a)
if s != tt.in {
t.Errorf("string(Runes(%q)) = %x; want %x", tin, s, tin)
}
diff --git a/src/pkg/compress/flate/deflate.go b/src/pkg/compress/flate/deflate.go
index d07e465254..18bb353d22 100644
--- a/src/pkg/compress/flate/deflate.go
+++ b/src/pkg/compress/flate/deflate.go
@@ -5,55 +5,55 @@
package flate
import (
- "io";
- "math";
- "os";
+ "io"
+ "math"
+ "os"
)
const (
- NoCompression = 0;
- BestSpeed = 1;
- fastCompression = 3;
- BestCompression = 9;
- DefaultCompression = -1;
- logMaxOffsetSize = 15; // Standard DEFLATE
- wideLogMaxOffsetSize = 22; // Wide DEFLATE
- minMatchLength = 3; // The smallest match that the deflater looks for
- maxMatchLength = 258; // The longest match for the deflater
- minOffsetSize = 1; // The shortest offset that makes any sence
+ NoCompression = 0
+ BestSpeed = 1
+ fastCompression = 3
+ BestCompression = 9
+ DefaultCompression = -1
+ logMaxOffsetSize = 15 // Standard DEFLATE
+ wideLogMaxOffsetSize = 22 // Wide DEFLATE
+ minMatchLength = 3 // The smallest match that the deflater looks for
+ maxMatchLength = 258 // The longest match for the deflater
+ minOffsetSize = 1 // The shortest offset that makes any sence
// The maximum number of tokens we put into a single flat block, just too
// stop things from getting too large.
- maxFlateBlockTokens = 1 << 14;
- maxStoreBlockSize = 65535;
- hashBits = 15;
- hashSize = 1 << hashBits;
- hashMask = (1 << hashBits) - 1;
- hashShift = (hashBits + minMatchLength - 1) / minMatchLength;
+ maxFlateBlockTokens = 1 << 14
+ maxStoreBlockSize = 65535
+ hashBits = 15
+ hashSize = 1 << hashBits
+ hashMask = (1 << hashBits) - 1
+ hashShift = (hashBits + minMatchLength - 1) / minMatchLength
)
type syncPipeReader struct {
- *io.PipeReader;
- closeChan chan bool;
+ *io.PipeReader
+ closeChan chan bool
}
func (sr *syncPipeReader) CloseWithError(err os.Error) os.Error {
- retErr := sr.PipeReader.CloseWithError(err);
- sr.closeChan <- true; // finish writer close
- return retErr;
+ retErr := sr.PipeReader.CloseWithError(err)
+ sr.closeChan <- true // finish writer close
+ return retErr
}
type syncPipeWriter struct {
- *io.PipeWriter;
- closeChan chan bool;
+ *io.PipeWriter
+ closeChan chan bool
}
type compressionLevel struct {
- good, lazy, nice, chain, fastSkipHashing int;
+ good, lazy, nice, chain, fastSkipHashing int
}
var levels = []compressionLevel{
- compressionLevel{}, // 0
+ compressionLevel{}, // 0
// For levels 1-3 we don't bother trying with lazy matches
compressionLevel{3, 0, 8, 4, 4},
compressionLevel{3, 0, 16, 8, 5},
@@ -69,67 +69,67 @@ var levels = []compressionLevel{
}
func (sw *syncPipeWriter) Close() os.Error {
- err := sw.PipeWriter.Close();
- <-sw.closeChan; // wait for reader close
- return err;
+ err := sw.PipeWriter.Close()
+ <-sw.closeChan // wait for reader close
+ return err
}
func syncPipe() (*syncPipeReader, *syncPipeWriter) {
- r, w := io.Pipe();
- sr := &syncPipeReader{r, make(chan bool, 1)};
- sw := &syncPipeWriter{w, sr.closeChan};
- return sr, sw;
+ r, w := io.Pipe()
+ sr := &syncPipeReader{r, make(chan bool, 1)}
+ sw := &syncPipeWriter{w, sr.closeChan}
+ return sr, sw
}
type deflater struct {
- level int;
- logWindowSize uint;
- w *huffmanBitWriter;
- r io.Reader;
+ level int
+ logWindowSize uint
+ w *huffmanBitWriter
+ r io.Reader
// (1 << logWindowSize) - 1.
- windowMask int;
+ windowMask int
// hashHead[hashValue] contains the largest inputIndex with the specified hash value
- hashHead []int;
+ hashHead []int
// If hashHead[hashValue] is within the current window, then
// hashPrev[hashHead[hashValue] & windowMask] contains the previous index
// with the same hash value.
- hashPrev []int;
+ hashPrev []int
// If we find a match of length >= niceMatch, then we don't bother searching
// any further.
- niceMatch int;
+ niceMatch int
// If we find a match of length >= goodMatch, we only do a half-hearted
// effort at doing lazy matching starting at the next character
- goodMatch int;
+ goodMatch int
// The maximum number of chains we look at when finding a match
- maxChainLength int;
+ maxChainLength int
// The sliding window we use for matching
- window []byte;
+ window []byte
// The index just past the last valid character
- windowEnd int;
+ windowEnd int
// index in "window" at which current block starts
- blockStart int;
+ blockStart int
}
func (d *deflater) flush() os.Error {
- d.w.flush();
- return d.w.err;
+ d.w.flush()
+ return d.w.err
}
func (d *deflater) fillWindow(index int) (int, os.Error) {
- wSize := d.windowMask + 1;
+ wSize := d.windowMask + 1
if index >= wSize+wSize-(minMatchLength+maxMatchLength) {
// shift the window by wSize
- copy(d.window, d.window[wSize:2*wSize]);
- index -= wSize;
- d.windowEnd -= wSize;
+ copy(d.window, d.window[wSize:2*wSize])
+ index -= wSize
+ d.windowEnd -= wSize
if d.blockStart >= wSize {
d.blockStart -= wSize
} else {
@@ -142,66 +142,66 @@ func (d *deflater) fillWindow(index int) (int, os.Error) {
d.hashPrev[i] = max(h-wSize, -1)
}
}
- var count int;
- var err os.Error;
- count, err = io.ReadAtLeast(d.r, d.window[d.windowEnd:], 1);
- d.windowEnd += count;
+ var count int
+ var err os.Error
+ count, err = io.ReadAtLeast(d.r, d.window[d.windowEnd:], 1)
+ d.windowEnd += count
if err == os.EOF {
return index, nil
}
- return index, err;
+ return index, err
}
func (d *deflater) writeBlock(tokens []token, index int, eof bool) os.Error {
if index > 0 || eof {
- var window []byte;
+ var window []byte
if d.blockStart <= index {
window = d.window[d.blockStart:index]
}
- d.blockStart = index;
- d.w.writeBlock(tokens, eof, window);
- return d.w.err;
+ d.blockStart = index
+ d.w.writeBlock(tokens, eof, window)
+ return d.w.err
}
- return nil;
+ return nil
}
// Try to find a match starting at index whose length is greater than prevSize.
// We only look at chainCount possibilities before giving up.
func (d *deflater) findMatch(pos int, prevHead int, prevLength int, lookahead int) (length, offset int, ok bool) {
- win := d.window[0 : pos+min(maxMatchLength, lookahead)];
+ win := d.window[0 : pos+min(maxMatchLength, lookahead)]
// We quit when we get a match that's at least nice long
- nice := min(d.niceMatch, len(win)-pos);
+ nice := min(d.niceMatch, len(win)-pos)
// If we've got a match that's good enough, only look in 1/4 the chain.
- tries := d.maxChainLength;
- length = prevLength;
+ tries := d.maxChainLength
+ length = prevLength
if length >= d.goodMatch {
tries >>= 2
}
- w0 := win[pos];
- w1 := win[pos+1];
- wEnd := win[pos+length];
- minIndex := pos - (d.windowMask + 1);
+ w0 := win[pos]
+ w1 := win[pos+1]
+ wEnd := win[pos+length]
+ minIndex := pos - (d.windowMask + 1)
for i := prevHead; tries > 0; tries-- {
if w0 == win[i] && w1 == win[i+1] && wEnd == win[i+length] {
// The hash function ensures that if win[i] and win[i+1] match, win[i+2] matches
- n := 3;
+ n := 3
for pos+n < len(win) && win[i+n] == win[pos+n] {
n++
}
if n > length && (n > 3 || pos-i <= 4096) {
- length = n;
- offset = pos - i;
- ok = true;
+ length = n
+ offset = pos - i
+ ok = true
if n >= nice {
// The match is good enough that we don't try to find a better one.
break
}
- wEnd = win[pos+n];
+ wEnd = win[pos+n]
}
}
if i == minIndex {
@@ -212,21 +212,21 @@ func (d *deflater) findMatch(pos int, prevHead int, prevLength int, lookahead in
break
}
}
- return;
+ return
}
func (d *deflater) writeStoredBlock(buf []byte) os.Error {
if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
return d.w.err
}
- d.w.writeBytes(buf);
- return d.w.err;
+ d.w.writeBytes(buf)
+ return d.w.err
}
func (d *deflater) storedDeflate() os.Error {
- buf := make([]byte, maxStoreBlockSize);
+ buf := make([]byte, maxStoreBlockSize)
for {
- n, err := d.r.Read(buf);
+ n, err := d.r.Read(buf)
if n > 0 {
if err := d.writeStoredBlock(buf[0:n]); err != nil {
return err
@@ -236,83 +236,83 @@ func (d *deflater) storedDeflate() os.Error {
if err == os.EOF {
break
}
- return err;
+ return err
}
}
- return nil;
+ return nil
}
func (d *deflater) doDeflate() (err os.Error) {
// init
- d.windowMask = 1<<d.logWindowSize - 1;
- d.hashHead = make([]int, hashSize);
- d.hashPrev = make([]int, 1<<d.logWindowSize);
- d.window = make([]byte, 2<<d.logWindowSize);
- fillInts(d.hashHead, -1);
- tokens := make([]token, maxFlateBlockTokens, maxFlateBlockTokens+1);
- l := levels[d.level];
- d.goodMatch = l.good;
- d.niceMatch = l.nice;
- d.maxChainLength = l.chain;
- lazyMatch := l.lazy;
- length := minMatchLength - 1;
- offset := 0;
- byteAvailable := false;
- isFastDeflate := l.fastSkipHashing != 0;
- index := 0;
+ d.windowMask = 1<<d.logWindowSize - 1
+ d.hashHead = make([]int, hashSize)
+ d.hashPrev = make([]int, 1<<d.logWindowSize)
+ d.window = make([]byte, 2<<d.logWindowSize)
+ fillInts(d.hashHead, -1)
+ tokens := make([]token, maxFlateBlockTokens, maxFlateBlockTokens+1)
+ l := levels[d.level]
+ d.goodMatch = l.good
+ d.niceMatch = l.nice
+ d.maxChainLength = l.chain
+ lazyMatch := l.lazy
+ length := minMatchLength - 1
+ offset := 0
+ byteAvailable := false
+ isFastDeflate := l.fastSkipHashing != 0
+ index := 0
// run
if index, err = d.fillWindow(index); err != nil {
return
}
- maxOffset := d.windowMask + 1; // (1 << logWindowSize);
+ maxOffset := d.windowMask + 1 // (1 << logWindowSize);
// only need to change when you refill the window
- windowEnd := d.windowEnd;
- maxInsertIndex := windowEnd - (minMatchLength - 1);
- ti := 0;
+ windowEnd := d.windowEnd
+ maxInsertIndex := windowEnd - (minMatchLength - 1)
+ ti := 0
- hash := int(0);
+ hash := int(0)
if index < maxInsertIndex {
hash = int(d.window[index])<<hashShift + int(d.window[index+1])
}
- chainHead := -1;
+ chainHead := -1
for {
if index > windowEnd {
panic("index > windowEnd")
}
- lookahead := windowEnd - index;
+ lookahead := windowEnd - index
if lookahead < minMatchLength+maxMatchLength {
if index, err = d.fillWindow(index); err != nil {
return
}
- windowEnd = d.windowEnd;
+ windowEnd = d.windowEnd
if index > windowEnd {
panic("index > windowEnd")
}
- maxInsertIndex = windowEnd - (minMatchLength - 1);
- lookahead = windowEnd - index;
+ maxInsertIndex = windowEnd - (minMatchLength - 1)
+ lookahead = windowEnd - index
if lookahead == 0 {
break
}
}
if index < maxInsertIndex {
// Update the hash
- hash = (hash<<hashShift + int(d.window[index+2])) & hashMask;
- chainHead = d.hashHead[hash];
- d.hashPrev[index&d.windowMask] = chainHead;
- d.hashHead[hash] = index;
+ hash = (hash<<hashShift + int(d.window[index+2])) & hashMask
+ chainHead = d.hashHead[hash]
+ d.hashPrev[index&d.windowMask] = chainHead
+ d.hashHead[hash] = index
}
- prevLength := length;
- prevOffset := offset;
- minIndex := max(index-maxOffset, 0);
- length = minMatchLength - 1;
- offset = 0;
+ prevLength := length
+ prevOffset := offset
+ minIndex := max(index-maxOffset, 0)
+ length = minMatchLength - 1
+ offset = 0
if chainHead >= minIndex &&
(isFastDeflate && lookahead > minMatchLength-1 ||
!isFastDeflate && lookahead > prevLength && prevLength < lazyMatch) {
if newLength, newOffset, ok := d.findMatch(index, chainHead, minMatchLength-1, lookahead); ok {
- length = newLength;
- offset = newOffset;
+ length = newLength
+ offset = newOffset
}
}
if isFastDeflate && length >= minMatchLength ||
@@ -324,13 +324,13 @@ func (d *deflater) doDeflate() (err os.Error) {
} else {
tokens[ti] = matchToken(uint32(prevLength-minMatchLength), uint32(prevOffset-minOffsetSize))
}
- ti++;
+ ti++
// Insert in the hash table all strings up to the end of the match.
// index and index-1 are already inserted. If there is not enough
// lookahead, the last two strings are not inserted into the hash
// table.
if length <= l.fastSkipHashing {
- var newIndex int;
+ var newIndex int
if isFastDeflate {
newIndex = index + length
} else {
@@ -338,47 +338,47 @@ func (d *deflater) doDeflate() (err os.Error) {
}
for index++; index < newIndex; index++ {
if index < maxInsertIndex {
- hash = (hash<<hashShift + int(d.window[index+2])) & hashMask;
+ hash = (hash<<hashShift + int(d.window[index+2])) & hashMask
// Get previous value with the same hash.
// Our chain should point to the previous value.
- d.hashPrev[index&d.windowMask] = d.hashHead[hash];
+ d.hashPrev[index&d.windowMask] = d.hashHead[hash]
// Set the head of the hash chain to us.
- d.hashHead[hash] = index;
+ d.hashHead[hash] = index
}
}
if !isFastDeflate {
- byteAvailable = false;
- length = minMatchLength - 1;
+ byteAvailable = false
+ length = minMatchLength - 1
}
} else {
// For matches this long, we don't bother inserting each individual
// item into the table.
- index += length;
- hash = (int(d.window[index])<<hashShift + int(d.window[index+1]));
+ index += length
+ hash = (int(d.window[index])<<hashShift + int(d.window[index+1]))
}
if ti == maxFlateBlockTokens {
// The block includes the current character
if err = d.writeBlock(tokens, index, false); err != nil {
return
}
- ti = 0;
+ ti = 0
}
} else {
if isFastDeflate || byteAvailable {
- i := index - 1;
+ i := index - 1
if isFastDeflate {
i = index
}
- tokens[ti] = literalToken(uint32(d.window[i]) & 0xFF);
- ti++;
+ tokens[ti] = literalToken(uint32(d.window[i]) & 0xFF)
+ ti++
if ti == maxFlateBlockTokens {
if err = d.writeBlock(tokens, i+1, false); err != nil {
return
}
- ti = 0;
+ ti = 0
}
}
- index++;
+ index++
if !isFastDeflate {
byteAvailable = true
}
@@ -387,8 +387,8 @@ func (d *deflater) doDeflate() (err os.Error) {
}
if byteAvailable {
// There is still one pending token that needs to be flushed
- tokens[ti] = literalToken(uint32(d.window[index-1]) & 0xFF);
- ti++;
+ tokens[ti] = literalToken(uint32(d.window[index-1]) & 0xFF)
+ ti++
}
if ti > 0 {
@@ -396,21 +396,21 @@ func (d *deflater) doDeflate() (err os.Error) {
return
}
}
- return;
+ return
}
func (d *deflater) deflater(r io.Reader, w io.Writer, level int, logWindowSize uint) (err os.Error) {
- d.r = r;
- d.w = newHuffmanBitWriter(w);
- d.level = level;
- d.logWindowSize = logWindowSize;
+ d.r = r
+ d.w = newHuffmanBitWriter(w)
+ d.level = level
+ d.logWindowSize = logWindowSize
switch {
case level == NoCompression:
err = d.storedDeflate()
case level == DefaultCompression:
- d.level = 6;
- fallthrough;
+ d.level = 6
+ fallthrough
case 1 <= level && level <= 9:
err = d.doDeflate()
default:
@@ -423,17 +423,17 @@ func (d *deflater) deflater(r io.Reader, w io.Writer, level int, logWindowSize u
if d.w.writeStoredHeader(0, true); d.w.err != nil {
return d.w.err
}
- return d.flush();
+ return d.flush()
}
func newDeflater(w io.Writer, level int, logWindowSize uint) io.WriteCloser {
- var d deflater;
- pr, pw := syncPipe();
+ var d deflater
+ pr, pw := syncPipe()
go func() {
- err := d.deflater(pr, w, level, logWindowSize);
- pr.CloseWithError(err);
- }();
- return pw;
+ err := d.deflater(pr, w, level, logWindowSize)
+ pr.CloseWithError(err)
+ }()
+ return pw
}
func NewDeflater(w io.Writer, level int) io.WriteCloser {
diff --git a/src/pkg/compress/flate/deflate_test.go b/src/pkg/compress/flate/deflate_test.go
index 9d5ada9945..1ac8059b38 100644
--- a/src/pkg/compress/flate/deflate_test.go
+++ b/src/pkg/compress/flate/deflate_test.go
@@ -5,27 +5,27 @@
package flate
import (
- "bytes";
- "fmt";
- "io/ioutil";
- "os";
- "testing";
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "testing"
)
type deflateTest struct {
- in []byte;
- level int;
- out []byte;
+ in []byte
+ level int
+ out []byte
}
type deflateInflateTest struct {
- in []byte;
+ in []byte
}
type reverseBitsTest struct {
- in uint16;
- bitCount uint8;
- out uint16;
+ in uint16
+ bitCount uint8
+ out uint16
}
var deflateTests = []*deflateTest{
@@ -70,19 +70,19 @@ var reverseBitsTests = []*reverseBitsTest{
}
func getLargeDataChunk() []byte {
- result := make([]byte, 100000);
+ result := make([]byte, 100000)
for i := range result {
result[i] = byte(int64(i) * int64(i) & 0xFF)
}
- return result;
+ return result
}
func TestDeflate(t *testing.T) {
for _, h := range deflateTests {
- buffer := bytes.NewBuffer([]byte{});
- w := NewDeflater(buffer, h.level);
- w.Write(h.in);
- w.Close();
+ buffer := bytes.NewBuffer([]byte{})
+ w := NewDeflater(buffer, h.level)
+ w.Write(h.in)
+ w.Close()
if bytes.Compare(buffer.Bytes(), h.out) != 0 {
t.Errorf("buffer is wrong; level = %v, buffer.Bytes() = %v, expected output = %v",
h.level, buffer.Bytes(), h.out)
@@ -91,21 +91,21 @@ func TestDeflate(t *testing.T) {
}
func testToFromWithLevel(t *testing.T, level int, input []byte, name string) os.Error {
- buffer := bytes.NewBuffer([]byte{});
- w := NewDeflater(buffer, level);
- w.Write(input);
- w.Close();
- inflater := NewInflater(buffer);
- decompressed, err := ioutil.ReadAll(inflater);
+ buffer := bytes.NewBuffer([]byte{})
+ w := NewDeflater(buffer, level)
+ w.Write(input)
+ w.Close()
+ inflater := NewInflater(buffer)
+ decompressed, err := ioutil.ReadAll(inflater)
if err != nil {
- t.Errorf("reading inflater: %s", err);
- return err;
+ t.Errorf("reading inflater: %s", err)
+ return err
}
- inflater.Close();
+ inflater.Close()
if bytes.Compare(input, decompressed) != 0 {
t.Errorf("decompress(compress(data)) != data: level=%d input=%s", level, name)
}
- return nil;
+ return nil
}
func testToFrom(t *testing.T, input []byte, name string) {
@@ -130,8 +130,8 @@ func TestReverseBits(t *testing.T) {
}
func TestDeflateInflateString(t *testing.T) {
- gold := bytes.NewBufferString(getEdata()).Bytes();
- testToFromWithLevel(t, 1, gold, "2.718281828...");
+ gold := bytes.NewBufferString(getEdata()).Bytes()
+ testToFromWithLevel(t, 1, gold, "2.718281828...")
}
func getEdata() string {
diff --git a/src/pkg/compress/flate/flate_test.go b/src/pkg/compress/flate/flate_test.go
index e2a97b368e..d7a9a3d24b 100644
--- a/src/pkg/compress/flate/flate_test.go
+++ b/src/pkg/compress/flate/flate_test.go
@@ -9,9 +9,9 @@
package flate
import (
- "bytes";
- "reflect";
- "testing";
+ "bytes"
+ "reflect"
+ "testing"
)
// The Huffman code lengths used by the fixed-format Huffman blocks.
@@ -45,9 +45,9 @@ var fixedHuffmanBits = [...]int{
}
type InitDecoderTest struct {
- in []int;
- out huffmanDecoder;
- ok bool;
+ in []int
+ out huffmanDecoder
+ ok bool
}
var initDecoderTests = []*InitDecoderTest{
@@ -115,10 +115,10 @@ var initDecoderTests = []*InitDecoderTest{
func TestInitDecoder(t *testing.T) {
for i, tt := range initDecoderTests {
- var h huffmanDecoder;
+ var h huffmanDecoder
if h.init(tt.in) != tt.ok {
- t.Errorf("test %d: init = %v", i, !tt.ok);
- continue;
+ t.Errorf("test %d: init = %v", i, !tt.ok)
+ continue
}
if !reflect.DeepEqual(&h, &tt.out) {
t.Errorf("test %d:\nhave %v\nwant %v", i, h, tt.out)
@@ -127,9 +127,9 @@ func TestInitDecoder(t *testing.T) {
}
func TestUncompressedSource(t *testing.T) {
- decoder := NewInflater(bytes.NewBuffer([]byte{0x01, 0x01, 0x00, 0xfe, 0xff, 0x11}));
- output := make([]byte, 1);
- n, error := decoder.Read(output);
+ decoder := NewInflater(bytes.NewBuffer([]byte{0x01, 0x01, 0x00, 0xfe, 0xff, 0x11}))
+ output := make([]byte, 1)
+ n, error := decoder.Read(output)
if n != 1 || error != nil {
t.Fatalf("decoder.Read() = %d, %v, want 1, nil", n, error)
}
diff --git a/src/pkg/compress/flate/huffman_bit_writer.go b/src/pkg/compress/flate/huffman_bit_writer.go
index a1ef3694cf..eac196dfcd 100644
--- a/src/pkg/compress/flate/huffman_bit_writer.go
+++ b/src/pkg/compress/flate/huffman_bit_writer.go
@@ -5,28 +5,28 @@
package flate
import (
- "io";
- "math";
- "os";
- "strconv";
+ "io"
+ "math"
+ "os"
+ "strconv"
)
const (
// The largest offset code.
- offsetCodeCount = 30;
+ offsetCodeCount = 30
// The largest offset code in the extensions.
- extendedOffsetCodeCount = 42;
+ extendedOffsetCodeCount = 42
// The special code used to mark the end of a block.
- endBlockMarker = 256;
+ endBlockMarker = 256
// The first length code.
- lengthCodesStart = 257;
+ lengthCodesStart = 257
// The number of codegen codes.
- codegenCodeCount = 19;
- badCode = 255;
+ codegenCodeCount = 19
+ badCode = 255
)
// The number of extra bits needed by length code X - LENGTH_CODES_START.
@@ -72,28 +72,28 @@ var offsetBase = []uint32{
var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
type huffmanBitWriter struct {
- w io.Writer;
+ w io.Writer
// Data waiting to be written is bytes[0:nbytes]
// and then the low nbits of bits.
- bits uint32;
- nbits uint32;
- bytes [64]byte;
- nbytes int;
- literalFreq []int32;
- offsetFreq []int32;
- codegen []uint8;
- codegenFreq []int32;
- literalEncoding *huffmanEncoder;
- offsetEncoding *huffmanEncoder;
- codegenEncoding *huffmanEncoder;
- err os.Error;
+ bits uint32
+ nbits uint32
+ bytes [64]byte
+ nbytes int
+ literalFreq []int32
+ offsetFreq []int32
+ codegen []uint8
+ codegenFreq []int32
+ literalEncoding *huffmanEncoder
+ offsetEncoding *huffmanEncoder
+ codegenEncoding *huffmanEncoder
+ err os.Error
}
type WrongValueError struct {
- name string;
- from int32;
- to int32;
- value int32;
+ name string
+ from int32
+ to int32
+ value int32
}
func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
@@ -116,46 +116,46 @@ func (err WrongValueError) String() string {
func (w *huffmanBitWriter) flushBits() {
if w.err != nil {
- w.nbits = 0;
- return;
+ w.nbits = 0
+ return
}
- bits := w.bits;
- w.bits >>= 16;
- w.nbits -= 16;
- n := w.nbytes;
- w.bytes[n] = byte(bits);
- w.bytes[n+1] = byte(bits >> 8);
+ bits := w.bits
+ w.bits >>= 16
+ w.nbits -= 16
+ n := w.nbytes
+ w.bytes[n] = byte(bits)
+ w.bytes[n+1] = byte(bits >> 8)
if n += 2; n >= len(w.bytes) {
- _, w.err = w.w.Write(&w.bytes);
- n = 0;
+ _, w.err = w.w.Write(&w.bytes)
+ n = 0
}
- w.nbytes = n;
+ w.nbytes = n
}
func (w *huffmanBitWriter) flush() {
if w.err != nil {
- w.nbits = 0;
- return;
+ w.nbits = 0
+ return
}
- n := w.nbytes;
+ n := w.nbytes
if w.nbits > 8 {
- w.bytes[n] = byte(w.bits);
- w.bits >>= 8;
- w.nbits -= 8;
- n++;
+ w.bytes[n] = byte(w.bits)
+ w.bits >>= 8
+ w.nbits -= 8
+ n++
}
if w.nbits > 0 {
- w.bytes[n] = byte(w.bits);
- w.nbits = 0;
- n++;
+ w.bytes[n] = byte(w.bits)
+ w.nbits = 0
+ n++
}
- w.bits = 0;
- _, w.err = w.w.Write(w.bytes[0:n]);
- w.nbytes = 0;
+ w.bits = 0
+ _, w.err = w.w.Write(w.bytes[0:n])
+ w.nbytes = 0
}
func (w *huffmanBitWriter) writeBits(b, nb int32) {
- w.bits |= uint32(b) << w.nbits;
+ w.bits |= uint32(b) << w.nbits
if w.nbits += uint32(nb); w.nbits >= 16 {
w.flushBits()
}
@@ -165,24 +165,24 @@ func (w *huffmanBitWriter) writeBytes(bytes []byte) {
if w.err != nil {
return
}
- n := w.nbytes;
+ n := w.nbytes
if w.nbits == 8 {
- w.bytes[n] = byte(w.bits);
- w.nbits = 0;
- n++;
+ w.bytes[n] = byte(w.bits)
+ w.nbits = 0
+ n++
}
if w.nbits != 0 {
- w.err = InternalError("writeBytes with unfinished bits");
- return;
+ w.err = InternalError("writeBytes with unfinished bits")
+ return
}
if n != 0 {
- _, w.err = w.w.Write(w.bytes[0:n]);
+ _, w.err = w.w.Write(w.bytes[0:n])
if w.err != nil {
return
}
}
- w.nbytes = 0;
- _, w.err = w.w.Write(bytes);
+ w.nbytes = 0
+ _, w.err = w.w.Write(bytes)
}
// RFC 1951 3.2.7 specifies a special run-length encoding for specifiying
@@ -197,82 +197,82 @@ func (w *huffmanBitWriter) writeBytes(bytes []byte) {
// numLiterals The number of literals in literalEncoding
// numOffsets The number of offsets in offsetEncoding
func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int) {
- fillInt32s(w.codegenFreq, 0);
+ fillInt32s(w.codegenFreq, 0)
// Note that we are using codegen both as a temporary variable for holding
// a copy of the frequencies, and as the place where we put the result.
// This is fine because the output is always shorter than the input used
// so far.
- codegen := w.codegen; // cache
+ codegen := w.codegen // cache
// Copy the concatenated code sizes to codegen. Put a marker at the end.
- copyUint8s(codegen[0:numLiterals], w.literalEncoding.codeBits);
- copyUint8s(codegen[numLiterals:numLiterals+numOffsets], w.offsetEncoding.codeBits);
- codegen[numLiterals+numOffsets] = badCode;
+ copyUint8s(codegen[0:numLiterals], w.literalEncoding.codeBits)
+ copyUint8s(codegen[numLiterals:numLiterals+numOffsets], w.offsetEncoding.codeBits)
+ codegen[numLiterals+numOffsets] = badCode
- size := codegen[0];
- count := 1;
- outIndex := 0;
+ size := codegen[0]
+ count := 1
+ outIndex := 0
for inIndex := 1; size != badCode; inIndex++ {
// INVARIANT: We have seen "count" copies of size that have not yet
// had output generated for them.
- nextSize := codegen[inIndex];
+ nextSize := codegen[inIndex]
if nextSize == size {
- count++;
- continue;
+ count++
+ continue
}
// We need to generate codegen indicating "count" of size.
if size != 0 {
- codegen[outIndex] = size;
- outIndex++;
- w.codegenFreq[size]++;
- count--;
+ codegen[outIndex] = size
+ outIndex++
+ w.codegenFreq[size]++
+ count--
for count >= 3 {
- n := min(count, 6);
- codegen[outIndex] = 16;
- outIndex++;
- codegen[outIndex] = uint8(n - 3);
- outIndex++;
- w.codegenFreq[16]++;
- count -= n;
+ n := min(count, 6)
+ codegen[outIndex] = 16
+ outIndex++
+ codegen[outIndex] = uint8(n - 3)
+ outIndex++
+ w.codegenFreq[16]++
+ count -= n
}
} else {
for count >= 11 {
- n := min(count, 138);
- codegen[outIndex] = 18;
- outIndex++;
- codegen[outIndex] = uint8(n - 11);
- outIndex++;
- w.codegenFreq[18]++;
- count -= n;
+ n := min(count, 138)
+ codegen[outIndex] = 18
+ outIndex++
+ codegen[outIndex] = uint8(n - 11)
+ outIndex++
+ w.codegenFreq[18]++
+ count -= n
}
if count >= 3 {
// count >= 3 && count <= 10
- codegen[outIndex] = 17;
- outIndex++;
- codegen[outIndex] = uint8(count - 3);
- outIndex++;
- w.codegenFreq[17]++;
- count = 0;
+ codegen[outIndex] = 17
+ outIndex++
+ codegen[outIndex] = uint8(count - 3)
+ outIndex++
+ w.codegenFreq[17]++
+ count = 0
}
}
- count--;
+ count--
for ; count >= 0; count-- {
- codegen[outIndex] = size;
- outIndex++;
- w.codegenFreq[size]++;
+ codegen[outIndex] = size
+ outIndex++
+ w.codegenFreq[size]++
}
// Set up invariant for next time through the loop.
- size = nextSize;
- count = 1;
+ size = nextSize
+ count = 1
}
// Marker indicating the end of the codegen.
- codegen[outIndex] = badCode;
+ codegen[outIndex] = badCode
}
func (w *huffmanBitWriter) writeCode(code *huffmanEncoder, literal uint32) {
if w.err != nil {
return
}
- w.writeBits(int32(code.code[literal]), int32(code.codeBits[literal]));
+ w.writeBits(int32(code.code[literal]), int32(code.codeBits[literal]))
}
// Write the header of a dynamic Huffman block to the output stream.
@@ -284,49 +284,49 @@ func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, n
if w.err != nil {
return
}
- var firstBits int32 = 4;
+ var firstBits int32 = 4
if isEof {
firstBits = 5
}
- w.writeBits(firstBits, 3);
- w.writeBits(int32(numLiterals-257), 5);
+ w.writeBits(firstBits, 3)
+ w.writeBits(int32(numLiterals-257), 5)
if numOffsets > offsetCodeCount {
// Extended version of deflater
- w.writeBits(int32(offsetCodeCount+((numOffsets-(1+offsetCodeCount))>>3)), 5);
- w.writeBits(int32((numOffsets-(1+offsetCodeCount))&0x7), 3);
+ w.writeBits(int32(offsetCodeCount+((numOffsets-(1+offsetCodeCount))>>3)), 5)
+ w.writeBits(int32((numOffsets-(1+offsetCodeCount))&0x7), 3)
} else {
w.writeBits(int32(numOffsets-1), 5)
}
- w.writeBits(int32(numCodegens-4), 4);
+ w.writeBits(int32(numCodegens-4), 4)
for i := 0; i < numCodegens; i++ {
- value := w.codegenEncoding.codeBits[codegenOrder[i]];
- w.writeBits(int32(value), 3);
+ value := w.codegenEncoding.codeBits[codegenOrder[i]]
+ w.writeBits(int32(value), 3)
}
- i := 0;
+ i := 0
for {
- var codeWord int = int(w.codegen[i]);
- i++;
+ var codeWord int = int(w.codegen[i])
+ i++
if codeWord == badCode {
break
}
// The low byte contains the actual code to generate.
- w.writeCode(w.codegenEncoding, uint32(codeWord));
+ w.writeCode(w.codegenEncoding, uint32(codeWord))
switch codeWord {
case 16:
- w.writeBits(int32(w.codegen[i]), 2);
- i++;
- break;
+ w.writeBits(int32(w.codegen[i]), 2)
+ i++
+ break
case 17:
- w.writeBits(int32(w.codegen[i]), 3);
- i++;
- break;
+ w.writeBits(int32(w.codegen[i]), 3)
+ i++
+ break
case 18:
- w.writeBits(int32(w.codegen[i]), 7);
- i++;
- break;
+ w.writeBits(int32(w.codegen[i]), 7)
+ i++
+ break
}
}
}
@@ -335,14 +335,14 @@ func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) {
if w.err != nil {
return
}
- var flag int32;
+ var flag int32
if isEof {
flag = 1
}
- w.writeBits(flag, 3);
- w.flush();
- w.writeBits(int32(length), 16);
- w.writeBits(int32(^uint16(length)), 16);
+ w.writeBits(flag, 3)
+ w.flush()
+ w.writeBits(int32(length), 16)
+ w.writeBits(int32(^uint16(length)), 16)
}
func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
@@ -350,61 +350,61 @@ func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
return
}
// Indicate that we are a fixed Huffman block
- var value int32 = 2;
+ var value int32 = 2
if isEof {
value = 3
}
- w.writeBits(value, 3);
+ w.writeBits(value, 3)
}
func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte) {
if w.err != nil {
return
}
- fillInt32s(w.literalFreq, 0);
- fillInt32s(w.offsetFreq, 0);
+ fillInt32s(w.literalFreq, 0)
+ fillInt32s(w.offsetFreq, 0)
- n := len(tokens);
- tokens = tokens[0 : n+1];
- tokens[n] = endBlockMarker;
+ n := len(tokens)
+ tokens = tokens[0 : n+1]
+ tokens[n] = endBlockMarker
- totalLength := -1; // Subtract 1 for endBlock.
+ totalLength := -1 // Subtract 1 for endBlock.
for _, t := range tokens {
switch t.typ() {
case literalType:
- w.literalFreq[t.literal()]++;
- totalLength++;
- break;
+ w.literalFreq[t.literal()]++
+ totalLength++
+ break
case matchType:
- length := t.length();
- offset := t.offset();
- totalLength += int(length + 3);
- w.literalFreq[lengthCodesStart+lengthCode(length)]++;
- w.offsetFreq[offsetCode(offset)]++;
- break;
+ length := t.length()
+ offset := t.offset()
+ totalLength += int(length + 3)
+ w.literalFreq[lengthCodesStart+lengthCode(length)]++
+ w.offsetFreq[offsetCode(offset)]++
+ break
}
}
- w.literalEncoding.generate(w.literalFreq, 15);
- w.offsetEncoding.generate(w.offsetFreq, 15);
+ w.literalEncoding.generate(w.literalFreq, 15)
+ w.offsetEncoding.generate(w.offsetFreq, 15)
// get the number of literals
- numLiterals := len(w.literalFreq);
+ numLiterals := len(w.literalFreq)
for w.literalFreq[numLiterals-1] == 0 {
numLiterals--
}
// get the number of offsets
- numOffsets := len(w.offsetFreq);
+ numOffsets := len(w.offsetFreq)
for numOffsets > 1 && w.offsetFreq[numOffsets-1] == 0 {
numOffsets--
}
- storedBytes := 0;
+ storedBytes := 0
if input != nil {
storedBytes = len(input)
}
- var extraBits int64;
- var storedSize int64;
+ var extraBits int64
+ var storedSize int64
if storedBytes <= maxStoreBlockSize && input != nil {
- storedSize = int64((storedBytes + 5) * 8);
+ storedSize = int64((storedBytes + 5) * 8)
// We only bother calculating the costs of the extra bits required by
// the length of offset fields (which will be the same for both fixed
// and dynamic encoding), if we need to compare those two encodings
@@ -423,7 +423,7 @@ func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte) {
// Figure out which generates smaller code, fixed Huffman, dynamic
// Huffman, or just storing the data.
- var fixedSize int64 = math.MaxInt64;
+ var fixedSize int64 = math.MaxInt64
if numOffsets <= offsetCodeCount {
fixedSize = int64(3) +
fixedLiteralEncoding.bitLength(w.literalFreq) +
@@ -432,13 +432,13 @@ func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte) {
}
// Generate codegen and codegenFrequencies, which indicates how to encode
// the literalEncoding and the offsetEncoding.
- w.generateCodegen(numLiterals, numOffsets);
- w.codegenEncoding.generate(w.codegenFreq, 7);
- numCodegens := len(w.codegenFreq);
+ w.generateCodegen(numLiterals, numOffsets)
+ w.codegenEncoding.generate(w.codegenFreq, 7)
+ numCodegens := len(w.codegenFreq)
for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
numCodegens--
}
- extensionSummand := 0;
+ extensionSummand := 0
if numOffsets > offsetCodeCount {
extensionSummand = 3
}
@@ -449,56 +449,56 @@ func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte) {
int64(extraBits) +
int64(w.codegenFreq[16]*2) +
int64(w.codegenFreq[17]*3) +
- int64(w.codegenFreq[18]*7);
+ int64(w.codegenFreq[18]*7)
dynamicSize := dynamicHeader +
w.literalEncoding.bitLength(w.literalFreq) +
- w.offsetEncoding.bitLength(w.offsetFreq);
+ w.offsetEncoding.bitLength(w.offsetFreq)
if storedSize < fixedSize && storedSize < dynamicSize {
- w.writeStoredHeader(storedBytes, eof);
- w.writeBytes(input[0:storedBytes]);
- return;
+ w.writeStoredHeader(storedBytes, eof)
+ w.writeBytes(input[0:storedBytes])
+ return
}
- var literalEncoding *huffmanEncoder;
- var offsetEncoding *huffmanEncoder;
+ var literalEncoding *huffmanEncoder
+ var offsetEncoding *huffmanEncoder
if fixedSize <= dynamicSize {
- w.writeFixedHeader(eof);
- literalEncoding = fixedLiteralEncoding;
- offsetEncoding = fixedOffsetEncoding;
+ w.writeFixedHeader(eof)
+ literalEncoding = fixedLiteralEncoding
+ offsetEncoding = fixedOffsetEncoding
} else {
// Write the header.
- w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof);
- literalEncoding = w.literalEncoding;
- offsetEncoding = w.offsetEncoding;
+ w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
+ literalEncoding = w.literalEncoding
+ offsetEncoding = w.offsetEncoding
}
// Write the tokens.
for _, t := range tokens {
switch t.typ() {
case literalType:
- w.writeCode(literalEncoding, t.literal());
- break;
+ w.writeCode(literalEncoding, t.literal())
+ break
case matchType:
// Write the length
- length := t.length();
- lengthCode := lengthCode(length);
- w.writeCode(literalEncoding, lengthCode+lengthCodesStart);
- extraLengthBits := int32(lengthExtraBits[lengthCode]);
+ length := t.length()
+ lengthCode := lengthCode(length)
+ w.writeCode(literalEncoding, lengthCode+lengthCodesStart)
+ extraLengthBits := int32(lengthExtraBits[lengthCode])
if extraLengthBits > 0 {
- extraLength := int32(length - lengthBase[lengthCode]);
- w.writeBits(extraLength, extraLengthBits);
+ extraLength := int32(length - lengthBase[lengthCode])
+ w.writeBits(extraLength, extraLengthBits)
}
// Write the offset
- offset := t.offset();
- offsetCode := offsetCode(offset);
- w.writeCode(offsetEncoding, offsetCode);
- extraOffsetBits := int32(offsetExtraBits[offsetCode]);
+ offset := t.offset()
+ offsetCode := offsetCode(offset)
+ w.writeCode(offsetEncoding, offsetCode)
+ extraOffsetBits := int32(offsetExtraBits[offsetCode])
if extraOffsetBits > 0 {
- extraOffset := int32(offset - offsetBase[offsetCode]);
- w.writeBits(extraOffset, extraOffsetBits);
+ extraOffset := int32(offset - offsetBase[offsetCode])
+ w.writeBits(extraOffset, extraOffsetBits)
}
- break;
+ break
default:
panic("unknown token type: " + string(t))
}
diff --git a/src/pkg/compress/flate/huffman_code.go b/src/pkg/compress/flate/huffman_code.go
index f212d059de..94ff2dfb8b 100644
--- a/src/pkg/compress/flate/huffman_code.go
+++ b/src/pkg/compress/flate/huffman_code.go
@@ -5,57 +5,57 @@
package flate
import (
- "math";
- "sort";
+ "math"
+ "sort"
)
type huffmanEncoder struct {
- codeBits []uint8;
- code []uint16;
+ codeBits []uint8
+ code []uint16
}
type literalNode struct {
- literal uint16;
- freq int32;
+ literal uint16
+ freq int32
}
type chain struct {
// The sum of the leaves in this tree
- freq int32;
+ freq int32
// The number of literals to the left of this item at this level
- leafCount int32;
+ leafCount int32
// The right child of this chain in the previous level.
- up *chain;
+ up *chain
}
type levelInfo struct {
// Our level. for better printing
- level int32;
+ level int32
// The most recent chain generated for this level
- lastChain *chain;
+ lastChain *chain
// The frequency of the next character to add to this level
- nextCharFreq int32;
+ nextCharFreq int32
// The frequency of the next pair (from level below) to add to this level.
// Only valid if the "needed" value of the next lower level is 0.
- nextPairFreq int32;
+ nextPairFreq int32
// The number of chains remaining to generate for this level before moving
// up to the next level
- needed int32;
+ needed int32
// The levelInfo for level+1
- up *levelInfo;
+ up *levelInfo
// The levelInfo for level-1
- down *levelInfo;
+ down *levelInfo
}
-func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxInt32} }
+func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxInt32} }
func newHuffmanEncoder(size int) *huffmanEncoder {
return &huffmanEncoder{make([]uint8, size), make([]uint16, size)}
@@ -63,96 +63,96 @@ func newHuffmanEncoder(size int) *huffmanEncoder {
// Generates a HuffmanCode corresponding to the fixed literal table
func generateFixedLiteralEncoding() *huffmanEncoder {
- h := newHuffmanEncoder(maxLit);
- codeBits := h.codeBits;
- code := h.code;
- var ch uint16;
+ h := newHuffmanEncoder(maxLit)
+ codeBits := h.codeBits
+ code := h.code
+ var ch uint16
for ch = 0; ch < maxLit; ch++ {
- var bits uint16;
- var size uint8;
+ var bits uint16
+ var size uint8
switch {
case ch < 144:
// size 8, 000110000 .. 10111111
- bits = ch + 48;
- size = 8;
- break;
+ bits = ch + 48
+ size = 8
+ break
case ch < 256:
// size 9, 110010000 .. 111111111
- bits = ch + 400 - 144;
- size = 9;
- break;
+ bits = ch + 400 - 144
+ size = 9
+ break
case ch < 280:
// size 7, 0000000 .. 0010111
- bits = ch - 256;
- size = 7;
- break;
+ bits = ch - 256
+ size = 7
+ break
default:
// size 8, 11000000 .. 11000111
- bits = ch + 192 - 280;
- size = 8;
+ bits = ch + 192 - 280
+ size = 8
}
- codeBits[ch] = size;
- code[ch] = reverseBits(bits, size);
+ codeBits[ch] = size
+ code[ch] = reverseBits(bits, size)
}
- return h;
+ return h
}
func generateFixedOffsetEncoding() *huffmanEncoder {
- h := newHuffmanEncoder(30);
- codeBits := h.codeBits;
- code := h.code;
+ h := newHuffmanEncoder(30)
+ codeBits := h.codeBits
+ code := h.code
for ch := uint16(0); ch < 30; ch++ {
- codeBits[ch] = 5;
- code[ch] = reverseBits(ch, 5);
+ codeBits[ch] = 5
+ code[ch] = reverseBits(ch, 5)
}
- return h;
+ return h
}
var fixedLiteralEncoding *huffmanEncoder = generateFixedLiteralEncoding()
var fixedOffsetEncoding *huffmanEncoder = generateFixedOffsetEncoding()
func (h *huffmanEncoder) bitLength(freq []int32) int64 {
- var total int64;
+ var total int64
for i, f := range freq {
if f != 0 {
total += int64(f) * int64(h.codeBits[i])
}
}
- return total;
+ return total
}
// Generate elements in the chain using an iterative algorithm.
func (h *huffmanEncoder) generateChains(top *levelInfo, list []literalNode) {
- n := len(list);
- list = list[0 : n+1];
- list[n] = maxNode();
+ n := len(list)
+ list = list[0 : n+1]
+ list[n] = maxNode()
- l := top;
+ l := top
for {
if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 {
// We've run out of both leafs and pairs.
// End all calculations for this level.
// To m sure we never come back to this level or any lower level,
// set nextPairFreq impossibly large.
- l.lastChain = nil;
- l.needed = 0;
- l = l.up;
- l.nextPairFreq = math.MaxInt32;
- continue;
+ l.lastChain = nil
+ l.needed = 0
+ l = l.up
+ l.nextPairFreq = math.MaxInt32
+ continue
}
- prevFreq := l.lastChain.freq;
+ prevFreq := l.lastChain.freq
if l.nextCharFreq < l.nextPairFreq {
// The next item on this row is a leaf node.
- n := l.lastChain.leafCount + 1;
- l.lastChain = &chain{l.nextCharFreq, n, l.lastChain.up};
- l.nextCharFreq = list[n].freq;
+ n := l.lastChain.leafCount + 1
+ l.lastChain = &chain{l.nextCharFreq, n, l.lastChain.up}
+ l.nextCharFreq = list[n].freq
} else {
// The next item on this row is a pair from the previous row.
// nextPairFreq isn't valid until we generate two
// more values in the level below
- l.lastChain = &chain{l.nextPairFreq, l.lastChain.leafCount, l.down.lastChain};
- l.down.needed = 2;
+ l.lastChain = &chain{l.nextPairFreq, l.lastChain.leafCount, l.down.lastChain}
+ l.down.needed = 2
}
if l.needed--; l.needed == 0 {
@@ -160,13 +160,13 @@ func (h *huffmanEncoder) generateChains(top *levelInfo, list []literalNode) {
// Continue calculating one level up. Fill in nextPairFreq
// of that level with the sum of the two nodes we've just calculated on
// this level.
- up := l.up;
+ up := l.up
if up == nil {
// All done!
return
}
- up.nextPairFreq = prevFreq + l.lastChain.freq;
- l = up;
+ up.nextPairFreq = prevFreq + l.lastChain.freq
+ l = up
} else {
// If we stole from below, move down temporarily to replenish it.
for l.down.needed > 0 {
@@ -189,20 +189,20 @@ func (h *huffmanEncoder) generateChains(top *levelInfo, list []literalNode) {
// return An integer array in which array[i] indicates the number of literals
// that should be encoded in i bits.
func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
- n := int32(len(list));
- list = list[0 : n+1];
- list[n] = maxNode();
+ n := int32(len(list))
+ list = list[0 : n+1]
+ list[n] = maxNode()
// The tree can't have greater depth than n - 1, no matter what. This
// saves a little bit of work in some small cases
- maxBits = minInt32(maxBits, n-1);
+ maxBits = minInt32(maxBits, n-1)
// Create information about each of the levels.
// A bogus "Level 0" whose sole purpose is so that
// level1.prev.needed==0. This makes level1.nextPairFreq
// be a legitimate value that never gets chosen.
- top := &levelInfo{needed: 0};
- chain2 := &chain{list[1].freq, 2, new(chain)};
+ top := &levelInfo{needed: 0}
+ chain2 := &chain{list[1].freq, 2, new(chain)}
for level := int32(1); level <= maxBits; level++ {
// For every level, the first two items are the first two characters.
// We initialize the levels as if we had already figured this out.
@@ -212,42 +212,42 @@ func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
nextCharFreq: list[2].freq,
nextPairFreq: list[0].freq + list[1].freq,
down: top,
- };
- top.down.up = top;
+ }
+ top.down.up = top
if level == 1 {
top.nextPairFreq = math.MaxInt32
}
}
// We need a total of 2*n - 2 items at top level and have already generated 2.
- top.needed = 2*n - 4;
+ top.needed = 2*n - 4
- l := top;
+ l := top
for {
if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 {
// We've run out of both leafs and pairs.
// End all calculations for this level.
// To m sure we never come back to this level or any lower level,
// set nextPairFreq impossibly large.
- l.lastChain = nil;
- l.needed = 0;
- l = l.up;
- l.nextPairFreq = math.MaxInt32;
- continue;
+ l.lastChain = nil
+ l.needed = 0
+ l = l.up
+ l.nextPairFreq = math.MaxInt32
+ continue
}
- prevFreq := l.lastChain.freq;
+ prevFreq := l.lastChain.freq
if l.nextCharFreq < l.nextPairFreq {
// The next item on this row is a leaf node.
- n := l.lastChain.leafCount + 1;
- l.lastChain = &chain{l.nextCharFreq, n, l.lastChain.up};
- l.nextCharFreq = list[n].freq;
+ n := l.lastChain.leafCount + 1
+ l.lastChain = &chain{l.nextCharFreq, n, l.lastChain.up}
+ l.nextCharFreq = list[n].freq
} else {
// The next item on this row is a pair from the previous row.
// nextPairFreq isn't valid until we generate two
// more values in the level below
- l.lastChain = &chain{l.nextPairFreq, l.lastChain.leafCount, l.down.lastChain};
- l.down.needed = 2;
+ l.lastChain = &chain{l.nextPairFreq, l.lastChain.leafCount, l.down.lastChain}
+ l.down.needed = 2
}
if l.needed--; l.needed == 0 {
@@ -255,13 +255,13 @@ func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
// Continue calculating one level up. Fill in nextPairFreq
// of that level with the sum of the two nodes we've just calculated on
// this level.
- up := l.up;
+ up := l.up
if up == nil {
// All done!
break
}
- up.nextPairFreq = prevFreq + l.lastChain.freq;
- l = up;
+ up.nextPairFreq = prevFreq + l.lastChain.freq
+ l = up
} else {
// If we stole from below, move down temporarily to replenish it.
for l.down.needed > 0 {
@@ -277,23 +277,23 @@ func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
panic("top.lastChain.leafCount != n")
}
- bitCount := make([]int32, maxBits+1);
- bits := 1;
+ bitCount := make([]int32, maxBits+1)
+ bits := 1
for chain := top.lastChain; chain.up != nil; chain = chain.up {
// chain.leafCount gives the number of literals requiring at least "bits"
// bits to encode.
- bitCount[bits] = chain.leafCount - chain.up.leafCount;
- bits++;
+ bitCount[bits] = chain.leafCount - chain.up.leafCount
+ bits++
}
- return bitCount;
+ return bitCount
}
// Look at the leaves and assign them a bit count and an encoding as specified
// in RFC 1951 3.2.2
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
- code := uint16(0);
+ code := uint16(0)
for n, bits := range bitCount {
- code <<= 1;
+ code <<= 1
if n == 0 || bits == 0 {
continue
}
@@ -301,14 +301,14 @@ func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalN
// are encoded using "bits" bits, and get the values
// code, code + 1, .... The code values are
// assigned in literal order (not frequency order).
- chunk := list[len(list)-int(bits):];
- sortByLiteral(chunk);
+ chunk := list[len(list)-int(bits):]
+ sortByLiteral(chunk)
for _, node := range chunk {
- h.codeBits[node.literal] = uint8(n);
- h.code[node.literal] = reverseBits(code, uint8(n));
- code++;
+ h.codeBits[node.literal] = uint8(n)
+ h.code[node.literal] = reverseBits(code, uint8(n))
+ code++
}
- list = list[0 : len(list)-int(bits)];
+ list = list[0 : len(list)-int(bits)]
}
}
@@ -317,58 +317,58 @@ func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalN
// freq An array of frequencies, in which frequency[i] gives the frequency of literal i.
// maxBits The maximum number of bits to use for any literal.
func (h *huffmanEncoder) generate(freq []int32, maxBits int32) {
- list := make([]literalNode, len(freq)+1);
+ list := make([]literalNode, len(freq)+1)
// Number of non-zero literals
- count := 0;
+ count := 0
// Set list to be the set of all non-zero literals and their frequencies
for i, f := range freq {
if f != 0 {
- list[count] = literalNode{uint16(i), f};
- count++;
+ list[count] = literalNode{uint16(i), f}
+ count++
} else {
h.codeBits[i] = 0
}
}
// If freq[] is shorter than codeBits[], fill rest of codeBits[] with zeros
- h.codeBits = h.codeBits[0:len(freq)];
- list = list[0:count];
+ h.codeBits = h.codeBits[0:len(freq)]
+ list = list[0:count]
if count <= 2 {
// Handle the small cases here, because they are awkward for the general case code. With
// two or fewer literals, everything has bit length 1.
for i, node := range list {
// "list" is in order of increasing literal value.
- h.codeBits[node.literal] = 1;
- h.code[node.literal] = uint16(i);
+ h.codeBits[node.literal] = 1
+ h.code[node.literal] = uint16(i)
}
- return;
+ return
}
- sortByFreq(list);
+ sortByFreq(list)
// Get the number of literals for each bit count
- bitCount := h.bitCounts(list, maxBits);
+ bitCount := h.bitCounts(list, maxBits)
// And do the assignment
- h.assignEncodingAndSize(bitCount, list);
+ h.assignEncodingAndSize(bitCount, list)
}
type literalNodeSorter struct {
- a []literalNode;
- less func(i, j int) bool;
+ a []literalNode
+ less func(i, j int) bool
}
-func (s literalNodeSorter) Len() int { return len(s.a) }
+func (s literalNodeSorter) Len() int { return len(s.a) }
func (s literalNodeSorter) Less(i, j int) bool {
return s.less(i, j)
}
-func (s literalNodeSorter) Swap(i, j int) { s.a[i], s.a[j] = s.a[j], s.a[i] }
+func (s literalNodeSorter) Swap(i, j int) { s.a[i], s.a[j] = s.a[j], s.a[i] }
func sortByFreq(a []literalNode) {
- s := &literalNodeSorter{a, func(i, j int) bool { return a[i].freq < a[j].freq }};
- sort.Sort(s);
+ s := &literalNodeSorter{a, func(i, j int) bool { return a[i].freq < a[j].freq }}
+ sort.Sort(s)
}
func sortByLiteral(a []literalNode) {
- s := &literalNodeSorter{a, func(i, j int) bool { return a[i].literal < a[j].literal }};
- sort.Sort(s);
+ s := &literalNodeSorter{a, func(i, j int) bool { return a[i].literal < a[j].literal }}
+ sort.Sort(s)
}
diff --git a/src/pkg/compress/flate/inflate.go b/src/pkg/compress/flate/inflate.go
index 213846688f..371fe94c59 100644
--- a/src/pkg/compress/flate/inflate.go
+++ b/src/pkg/compress/flate/inflate.go
@@ -8,18 +8,18 @@
package flate
import (
- "bufio";
- "io";
- "os";
- "strconv";
+ "bufio"
+ "io"
+ "os"
+ "strconv"
)
const (
- maxCodeLen = 16; // max length of Huffman code
- maxHist = 32768; // max history required
- maxLit = 286;
- maxDist = 32;
- numCodes = 19; // number of codes in Huffman meta-code
+ maxCodeLen = 16 // max length of Huffman code
+ maxHist = 32768 // max history required
+ maxLit = 286
+ maxDist = 32
+ numCodes = 19 // number of codes in Huffman meta-code
)
// A CorruptInputError reports the presence of corrupt input at a given offset.
@@ -32,12 +32,12 @@ func (e CorruptInputError) String() string {
// An InternalError reports an error in the flate code itself.
type InternalError string
-func (e InternalError) String() string { return "flate: internal error: " + string(e) }
+func (e InternalError) String() string { return "flate: internal error: " + string(e) }
// A ReadError reports an error encountered while reading input.
type ReadError struct {
- Offset int64; // byte offset where error occurred
- Error os.Error; // error returned by underlying Read
+ Offset int64 // byte offset where error occurred
+ Error os.Error // error returned by underlying Read
}
func (e *ReadError) String() string {
@@ -46,8 +46,8 @@ func (e *ReadError) String() string {
// A WriteError reports an error encountered while writing output.
type WriteError struct {
- Offset int64; // byte offset where error occurred
- Error os.Error; // error returned by underlying Read
+ Offset int64 // byte offset where error occurred
+ Error os.Error // error returned by underlying Read
}
func (e *WriteError) String() string {
@@ -59,20 +59,20 @@ func (e *WriteError) String() string {
// Proceedings of the IEEE, 61(7) (July 1973), pp 1046-1047.
type huffmanDecoder struct {
// min, max code length
- min, max int;
+ min, max int
// limit[i] = largest code word of length i
// Given code v of length n,
// need more bits if v > limit[n].
- limit [maxCodeLen + 1]int;
+ limit [maxCodeLen + 1]int
// base[i] = smallest code word of length i - seq number
- base [maxCodeLen + 1]int;
+ base [maxCodeLen + 1]int
// codes[seq number] = output code.
// Given code v of length n, value is
// codes[v - base[n]].
- codes []int;
+ codes []int
}
// Initialize Huffman decoding tables from array of code lengths.
@@ -81,8 +81,8 @@ func (h *huffmanDecoder) init(bits []int) bool {
// Count number of codes of each length,
// compute min and max length.
- var count [maxCodeLen + 1]int;
- var min, max int;
+ var count [maxCodeLen + 1]int
+ var min, max int
for _, n := range bits {
if n == 0 {
continue
@@ -93,31 +93,31 @@ func (h *huffmanDecoder) init(bits []int) bool {
if n > max {
max = n
}
- count[n]++;
+ count[n]++
}
if max == 0 {
return false
}
- h.min = min;
- h.max = max;
+ h.min = min
+ h.max = max
// For each code range, compute
// nextcode (first code of that length),
// limit (last code of that length), and
// base (offset from first code to sequence number).
- code := 0;
- seq := 0;
- var nextcode [maxCodeLen]int;
+ code := 0
+ seq := 0
+ var nextcode [maxCodeLen]int
for i := min; i <= max; i++ {
- n := count[i];
- nextcode[i] = code;
- h.base[i] = code - seq;
- code += n;
- seq += n;
- h.limit[i] = code - 1;
- code <<= 1;
+ n := count[i]
+ nextcode[i] = code
+ h.base[i] = code - seq
+ code += n
+ seq += n
+ h.limit[i] = code - 1
+ code <<= 1
}
// Make array mapping sequence numbers to codes.
@@ -128,12 +128,12 @@ func (h *huffmanDecoder) init(bits []int) bool {
if n == 0 {
continue
}
- code := nextcode[n];
- nextcode[n]++;
- seq := code - h.base[n];
- h.codes[seq] = i;
+ code := nextcode[n]
+ nextcode[n]++
+ seq := code - h.base[n]
+ h.codes[seq] = i
}
- return true;
+ return true
}
// Hard-coded Huffman tables for DEFLATE algorithm.
@@ -192,51 +192,51 @@ var fixedHuffmanDecoder = huffmanDecoder{
// If the passed in io.Reader does not also have ReadByte,
// the NewInflater will introduce its own buffering.
type Reader interface {
- io.Reader;
- ReadByte() (c byte, err os.Error);
+ io.Reader
+ ReadByte() (c byte, err os.Error)
}
// Inflate state.
type inflater struct {
// Input/output sources.
- r Reader;
- w io.Writer;
- roffset int64;
- woffset int64;
+ r Reader
+ w io.Writer
+ roffset int64
+ woffset int64
// Input bits, in top of b.
- b uint32;
- nb uint;
+ b uint32
+ nb uint
// Huffman decoders for literal/length, distance.
- h1, h2 huffmanDecoder;
+ h1, h2 huffmanDecoder
// Length arrays used to define Huffman codes.
- bits [maxLit + maxDist]int;
- codebits [numCodes]int;
+ bits [maxLit + maxDist]int
+ codebits [numCodes]int
// Output history, buffer.
- hist [maxHist]byte;
- hp int; // current output position in buffer
- hfull bool; // buffer has filled at least once
+ hist [maxHist]byte
+ hp int // current output position in buffer
+ hfull bool // buffer has filled at least once
// Temporary buffer (avoids repeated allocation).
- buf [4]byte;
+ buf [4]byte
}
func (f *inflater) inflate() (err os.Error) {
- final := false;
+ final := false
for err == nil && !final {
for f.nb < 1+2 {
if err = f.moreBits(); err != nil {
return
}
}
- final = f.b&1 == 1;
- f.b >>= 1;
- typ := f.b & 3;
- f.b >>= 2;
- f.nb -= 1 + 2;
+ final = f.b&1 == 1
+ f.b >>= 1
+ typ := f.b & 3
+ f.b >>= 2
+ f.nb -= 1 + 2
switch typ {
case 0:
err = f.dataBlock()
@@ -253,7 +253,7 @@ func (f *inflater) inflate() (err os.Error) {
err = CorruptInputError(f.roffset)
}
}
- return;
+ return
}
// RFC 1951 section 3.2.7.
@@ -268,13 +268,13 @@ func (f *inflater) readHuffman() os.Error {
return err
}
}
- nlit := int(f.b&0x1F) + 257;
- f.b >>= 5;
- ndist := int(f.b&0x1F) + 1;
- f.b >>= 5;
- nclen := int(f.b&0xF) + 4;
- f.b >>= 4;
- f.nb -= 5 + 5 + 4;
+ nlit := int(f.b&0x1F) + 257
+ f.b >>= 5
+ ndist := int(f.b&0x1F) + 1
+ f.b >>= 5
+ nclen := int(f.b&0xF) + 4
+ f.b >>= 4
+ f.nb -= 5 + 5 + 4
// (HCLEN+4)*3 bits: code lengths in the magic codeOrder order.
for i := 0; i < nclen; i++ {
@@ -283,9 +283,9 @@ func (f *inflater) readHuffman() os.Error {
return err
}
}
- f.codebits[codeOrder[i]] = int(f.b & 0x7);
- f.b >>= 3;
- f.nb -= 3;
+ f.codebits[codeOrder[i]] = int(f.b & 0x7)
+ f.b >>= 3
+ f.nb -= 3
}
for i := nclen; i < len(codeOrder); i++ {
f.codebits[codeOrder[i]] = 0
@@ -297,53 +297,53 @@ func (f *inflater) readHuffman() os.Error {
// HLIT + 257 code lengths, HDIST + 1 code lengths,
// using the code length Huffman code.
for i, n := 0, nlit+ndist; i < n; {
- x, err := f.huffSym(&f.h1);
+ x, err := f.huffSym(&f.h1)
if err != nil {
return err
}
if x < 16 {
// Actual length.
- f.bits[i] = x;
- i++;
- continue;
+ f.bits[i] = x
+ i++
+ continue
}
// Repeat previous length or zero.
- var rep int;
- var nb uint;
- var b int;
+ var rep int
+ var nb uint
+ var b int
switch x {
default:
return InternalError("unexpected length code")
case 16:
- rep = 3;
- nb = 2;
+ rep = 3
+ nb = 2
if i == 0 {
return CorruptInputError(f.roffset)
}
- b = f.bits[i-1];
+ b = f.bits[i-1]
case 17:
- rep = 3;
- nb = 3;
- b = 0;
+ rep = 3
+ nb = 3
+ b = 0
case 18:
- rep = 11;
- nb = 7;
- b = 0;
+ rep = 11
+ nb = 7
+ b = 0
}
for f.nb < nb {
if err := f.moreBits(); err != nil {
return err
}
}
- rep += int(f.b & uint32(1<<nb-1));
- f.b >>= nb;
- f.nb -= nb;
+ rep += int(f.b & uint32(1<<nb-1))
+ f.b >>= nb
+ f.nb -= nb
if i+rep > n {
return CorruptInputError(f.roffset)
}
for j := 0; j < rep; j++ {
- f.bits[i] = b;
- i++;
+ f.bits[i] = b
+ i++
}
}
@@ -351,7 +351,7 @@ func (f *inflater) readHuffman() os.Error {
return CorruptInputError(f.roffset)
}
- return nil;
+ return nil
}
// Decode a single Huffman block from f.
@@ -360,46 +360,46 @@ func (f *inflater) readHuffman() os.Error {
// fixed distance encoding associated with fixed Huffman blocks.
func (f *inflater) decodeBlock(hl, hd *huffmanDecoder) os.Error {
for {
- v, err := f.huffSym(hl);
+ v, err := f.huffSym(hl)
if err != nil {
return err
}
- var n uint; // number of bits extra
- var length int;
+ var n uint // number of bits extra
+ var length int
switch {
case v < 256:
- f.hist[f.hp] = byte(v);
- f.hp++;
+ f.hist[f.hp] = byte(v)
+ f.hp++
if f.hp == len(f.hist) {
if err = f.flush(); err != nil {
return err
}
}
- continue;
+ continue
case v == 256:
return nil
// otherwise, reference to older data
case v < 265:
- length = v - (257 - 3);
- n = 0;
+ length = v - (257 - 3)
+ n = 0
case v < 269:
- length = v*2 - (265*2 - 11);
- n = 1;
+ length = v*2 - (265*2 - 11)
+ n = 1
case v < 273:
- length = v*4 - (269*4 - 19);
- n = 2;
+ length = v*4 - (269*4 - 19)
+ n = 2
case v < 277:
- length = v*8 - (273*8 - 35);
- n = 3;
+ length = v*8 - (273*8 - 35)
+ n = 3
case v < 281:
- length = v*16 - (277*16 - 67);
- n = 4;
+ length = v*16 - (277*16 - 67)
+ n = 4
case v < 285:
- length = v*32 - (281*32 - 131);
- n = 5;
+ length = v*32 - (281*32 - 131)
+ n = 5
default:
- length = 258;
- n = 0;
+ length = 258
+ n = 0
}
if n > 0 {
for f.nb < n {
@@ -407,21 +407,21 @@ func (f *inflater) decodeBlock(hl, hd *huffmanDecoder) os.Error {
return err
}
}
- length += int(f.b & uint32(1<<n-1));
- f.b >>= n;
- f.nb -= n;
+ length += int(f.b & uint32(1<<n-1))
+ f.b >>= n
+ f.nb -= n
}
- var dist int;
+ var dist int
if hd == nil {
for f.nb < 5 {
if err = f.moreBits(); err != nil {
return err
}
}
- dist = int(reverseByte[(f.b&0x1F)<<3]);
- f.b >>= 5;
- f.nb -= 5;
+ dist = int(reverseByte[(f.b&0x1F)<<3])
+ f.b >>= 5
+ f.nb -= 5
} else {
if dist, err = f.huffSym(hd); err != nil {
return err
@@ -434,18 +434,18 @@ func (f *inflater) decodeBlock(hl, hd *huffmanDecoder) os.Error {
case dist >= 30:
return CorruptInputError(f.roffset)
default:
- nb := uint(dist-2) >> 1;
+ nb := uint(dist-2) >> 1
// have 1 bit in bottom of dist, need nb more.
- extra := (dist & 1) << nb;
+ extra := (dist & 1) << nb
for f.nb < nb {
if err = f.moreBits(); err != nil {
return err
}
}
- extra |= int(f.b & uint32(1<<nb-1));
- f.b >>= nb;
- f.nb -= nb;
- dist = 1<<(nb+1) + 1 + extra;
+ extra |= int(f.b & uint32(1<<nb-1))
+ f.b >>= nb
+ f.nb -= nb
+ dist = 1<<(nb+1) + 1 + extra
}
// Copy history[-dist:-dist+length] into output.
@@ -458,14 +458,14 @@ func (f *inflater) decodeBlock(hl, hd *huffmanDecoder) os.Error {
return CorruptInputError(f.roffset)
}
- p := f.hp - dist;
+ p := f.hp - dist
if p < 0 {
p += len(f.hist)
}
for i := 0; i < length; i++ {
- f.hist[f.hp] = f.hist[p];
- f.hp++;
- p++;
+ f.hist[f.hp] = f.hist[p]
+ f.hp++
+ p++
if f.hp == len(f.hist) {
if err = f.flush(); err != nil {
return err
@@ -476,24 +476,24 @@ func (f *inflater) decodeBlock(hl, hd *huffmanDecoder) os.Error {
}
}
}
- panic("unreached");
+ panic("unreached")
}
// Copy a single uncompressed data block from input to output.
func (f *inflater) dataBlock() os.Error {
// Uncompressed.
// Discard current half-byte.
- f.nb = 0;
- f.b = 0;
+ f.nb = 0
+ f.b = 0
// Length then ones-complement of length.
- nr, err := io.ReadFull(f.r, f.buf[0:4]);
- f.roffset += int64(nr);
+ nr, err := io.ReadFull(f.r, f.buf[0:4])
+ f.roffset += int64(nr)
if err != nil {
return &ReadError{f.roffset, err}
}
- n := int(f.buf[0]) | int(f.buf[1])<<8;
- nn := int(f.buf[2]) | int(f.buf[3])<<8;
+ n := int(f.buf[0]) | int(f.buf[1])<<8
+ nn := int(f.buf[2]) | int(f.buf[3])<<8
if uint16(nn) != uint16(^n) {
return CorruptInputError(f.roffset)
}
@@ -501,44 +501,44 @@ func (f *inflater) dataBlock() os.Error {
// Read len bytes into history,
// writing as history fills.
for n > 0 {
- m := len(f.hist) - f.hp;
+ m := len(f.hist) - f.hp
if m > n {
m = n
}
- m, err := io.ReadFull(f.r, f.hist[f.hp:f.hp+m]);
- f.roffset += int64(m);
+ m, err := io.ReadFull(f.r, f.hist[f.hp:f.hp+m])
+ f.roffset += int64(m)
if err != nil {
return &ReadError{f.roffset, err}
}
- n -= m;
- f.hp += m;
+ n -= m
+ f.hp += m
if f.hp == len(f.hist) {
if err = f.flush(); err != nil {
return err
}
}
}
- return nil;
+ return nil
}
func (f *inflater) moreBits() os.Error {
- c, err := f.r.ReadByte();
+ c, err := f.r.ReadByte()
if err != nil {
if err == os.EOF {
err = io.ErrUnexpectedEOF
}
- return err;
+ return err
}
- f.roffset++;
- f.b |= uint32(c) << f.nb;
- f.nb += 8;
- return nil;
+ f.roffset++
+ f.b |= uint32(c) << f.nb
+ f.nb += 8
+ return nil
}
// Read the next Huffman-encoded symbol from f according to h.
func (f *inflater) huffSym(h *huffmanDecoder) (int, os.Error) {
for n := uint(h.min); n <= uint(h.max); n++ {
- lim := h.limit[n];
+ lim := h.limit[n]
if lim == -1 {
continue
}
@@ -547,16 +547,16 @@ func (f *inflater) huffSym(h *huffmanDecoder) (int, os.Error) {
return 0, err
}
}
- v := int(f.b & uint32(1<<n-1));
- v <<= 16 - n;
- v = int(reverseByte[v>>8]) | int(reverseByte[v&0xFF])<<8; // reverse bits
+ v := int(f.b & uint32(1<<n-1))
+ v <<= 16 - n
+ v = int(reverseByte[v>>8]) | int(reverseByte[v&0xFF])<<8 // reverse bits
if v <= lim {
- f.b >>= n;
- f.nb -= n;
- return h.codes[v-h.base[n]], nil;
+ f.b >>= n
+ f.nb -= n
+ return h.codes[v-h.base[n]], nil
}
}
- return 0, CorruptInputError(f.roffset);
+ return 0, CorruptInputError(f.roffset)
}
// Flush any buffered output to the underlying writer.
@@ -564,39 +564,39 @@ func (f *inflater) flush() os.Error {
if f.hp == 0 {
return nil
}
- n, err := f.w.Write(f.hist[0:f.hp]);
+ n, err := f.w.Write(f.hist[0:f.hp])
if n != f.hp && err == nil {
err = io.ErrShortWrite
}
if err != nil {
return &WriteError{f.woffset, err}
}
- f.woffset += int64(f.hp);
- f.hp = 0;
- f.hfull = true;
- return nil;
+ f.woffset += int64(f.hp)
+ f.hp = 0
+ f.hfull = true
+ return nil
}
func makeReader(r io.Reader) Reader {
if rr, ok := r.(Reader); ok {
return rr
}
- return bufio.NewReader(r);
+ return bufio.NewReader(r)
}
// Inflate reads DEFLATE-compressed data from r and writes
// the uncompressed data to w.
func (f *inflater) inflater(r io.Reader, w io.Writer) os.Error {
- f.r = makeReader(r);
- f.w = w;
- f.woffset = 0;
+ f.r = makeReader(r)
+ f.w = w
+ f.woffset = 0
if err := f.inflate(); err != nil {
return err
}
if err := f.flush(); err != nil {
return err
}
- return nil;
+ return nil
}
// NewInflater returns a new ReadCloser that can be used
@@ -604,8 +604,8 @@ func (f *inflater) inflater(r io.Reader, w io.Writer) os.Error {
// responsibility to call Close on the ReadCloser when
// finished reading.
func NewInflater(r io.Reader) io.ReadCloser {
- var f inflater;
- pr, pw := io.Pipe();
- go func() { pw.CloseWithError(f.inflater(r, pw)) }();
- return pr;
+ var f inflater
+ pr, pw := io.Pipe()
+ go func() { pw.CloseWithError(f.inflater(r, pw)) }()
+ return pr
}
diff --git a/src/pkg/compress/flate/token.go b/src/pkg/compress/flate/token.go
index 139e1d0da0..38aea5fa65 100644
--- a/src/pkg/compress/flate/token.go
+++ b/src/pkg/compress/flate/token.go
@@ -8,11 +8,11 @@ const (
// 2 bits: type 0 = literal 1=EOF 2=Match 3=Unused
// 8 bits: xlength = length - MIN_MATCH_LENGTH
// 22 bits xoffset = offset - MIN_OFFSET_SIZE, or literal
- lengthShift = 22;
- offsetMask = 1<<lengthShift - 1;
- typeMask = 3 << 30;
- literalType = 0 << 30;
- matchType = 1 << 30;
+ lengthShift = 22
+ offsetMask = 1<<lengthShift - 1
+ typeMask = 3 << 30
+ literalType = 0 << 30
+ matchType = 1 << 30
)
// The length code for length X (MIN_MATCH_LENGTH <= X <= MAX_MATCH_LENGTH)
@@ -68,7 +68,7 @@ var offsetCodes = [...]uint32{
type token uint32
// Convert a literal into a literal token.
-func literalToken(literal uint32) token { return token(literalType + literal) }
+func literalToken(literal uint32) token { return token(literalType + literal) }
// Convert a < xlength, xoffset > pair into a match token.
func matchToken(xlength uint32, xoffset uint32) token {
@@ -76,21 +76,21 @@ func matchToken(xlength uint32, xoffset uint32) token {
}
// Returns the type of a token
-func (t token) typ() uint32 { return uint32(t) & typeMask }
+func (t token) typ() uint32 { return uint32(t) & typeMask }
// Returns the literal of a literal token
-func (t token) literal() uint32 { return uint32(t - literalType) }
+func (t token) literal() uint32 { return uint32(t - literalType) }
// Returns the extra offset of a match token
-func (t token) offset() uint32 { return uint32(t) & offsetMask }
+func (t token) offset() uint32 { return uint32(t) & offsetMask }
-func (t token) length() uint32 { return uint32((t - matchType) >> lengthShift) }
+func (t token) length() uint32 { return uint32((t - matchType) >> lengthShift) }
-func lengthCode(len uint32) uint32 { return lengthCodes[len] }
+func lengthCode(len uint32) uint32 { return lengthCodes[len] }
// Returns the offset code corresponding to a specific offset
func offsetCode(off uint32) uint32 {
- const n = uint32(len(offsetCodes));
+ const n = uint32(len(offsetCodes))
switch {
case off < n:
return offsetCodes[off]
@@ -99,5 +99,5 @@ func offsetCode(off uint32) uint32 {
default:
return offsetCodes[off>>14] + 28
}
- panic("unreachable");
+ panic("unreachable")
}
diff --git a/src/pkg/compress/flate/util.go b/src/pkg/compress/flate/util.go
index f4e0b9ba38..aca5c78b2d 100644
--- a/src/pkg/compress/flate/util.go
+++ b/src/pkg/compress/flate/util.go
@@ -8,21 +8,21 @@ func min(left int, right int) int {
if left < right {
return left
}
- return right;
+ return right
}
func minInt32(left int32, right int32) int32 {
if left < right {
return left
}
- return right;
+ return right
}
func max(left int, right int) int {
if left > right {
return left
}
- return right;
+ return right
}
func fillInts(a []int, value int) {
@@ -56,17 +56,17 @@ func fillUint8s(a []uint8, value uint8) {
}
func copyInt8s(dst []int8, src []int8) int {
- cnt := min(len(dst), len(src));
+ cnt := min(len(dst), len(src))
for i := 0; i < cnt; i++ {
dst[i] = src[i]
}
- return cnt;
+ return cnt
}
func copyUint8s(dst []uint8, src []uint8) int {
- cnt := min(len(dst), len(src));
+ cnt := min(len(dst), len(src))
for i := 0; i < cnt; i++ {
dst[i] = src[i]
}
- return cnt;
+ return cnt
}
diff --git a/src/pkg/compress/gzip/gunzip.go b/src/pkg/compress/gzip/gunzip.go
index ef84f16fc9..b2a08830c9 100644
--- a/src/pkg/compress/gzip/gunzip.go
+++ b/src/pkg/compress/gzip/gunzip.go
@@ -7,30 +7,30 @@
package gzip
import (
- "bufio";
- "compress/flate";
- "hash";
- "hash/crc32";
- "io";
- "os";
+ "bufio"
+ "compress/flate"
+ "hash"
+ "hash/crc32"
+ "io"
+ "os"
)
const (
- gzipID1 = 0x1f;
- gzipID2 = 0x8b;
- gzipDeflate = 8;
- flagText = 1 << 0;
- flagHdrCrc = 1 << 1;
- flagExtra = 1 << 2;
- flagName = 1 << 3;
- flagComment = 1 << 4;
+ gzipID1 = 0x1f
+ gzipID2 = 0x8b
+ gzipDeflate = 8
+ flagText = 1 << 0
+ flagHdrCrc = 1 << 1
+ flagExtra = 1 << 2
+ flagName = 1 << 3
+ flagComment = 1 << 4
)
func makeReader(r io.Reader) flate.Reader {
if rr, ok := r.(flate.Reader); ok {
return rr
}
- return bufio.NewReader(r);
+ return bufio.NewReader(r)
}
var HeaderError os.Error = os.ErrorString("invalid gzip header")
@@ -53,34 +53,34 @@ var ChecksumError os.Error = os.ErrorString("gzip checksum error")
// returned by Read as tentative until they receive the successful
// (zero length, nil error) Read marking the end of the data.
type Inflater struct {
- Comment string; // comment
- Extra []byte; // "extra data"
- Mtime uint32; // modification time (seconds since January 1, 1970)
- Name string; // file name
- OS byte; // operating system type
+ Comment string // comment
+ Extra []byte // "extra data"
+ Mtime uint32 // modification time (seconds since January 1, 1970)
+ Name string // file name
+ OS byte // operating system type
- r flate.Reader;
- inflater io.ReadCloser;
- digest hash.Hash32;
- size uint32;
- flg byte;
- buf [512]byte;
- err os.Error;
- eof bool;
+ r flate.Reader
+ inflater io.ReadCloser
+ digest hash.Hash32
+ size uint32
+ flg byte
+ buf [512]byte
+ err os.Error
+ eof bool
}
// NewInflater creates a new Inflater reading the given reader.
// The implementation buffers input and may read more data than necessary from r.
// It is the caller's responsibility to call Close on the Inflater when done.
func NewInflater(r io.Reader) (*Inflater, os.Error) {
- z := new(Inflater);
- z.r = makeReader(r);
- z.digest = crc32.NewIEEE();
+ z := new(Inflater)
+ z.r = makeReader(r)
+ z.digest = crc32.NewIEEE()
if err := z.readHeader(true); err != nil {
- z.err = err;
- return nil, err;
+ z.err = err
+ return nil, err
}
- return z, nil;
+ return z, nil
}
// GZIP (RFC 1952) is little-endian, unlike ZLIB (RFC 1950).
@@ -89,12 +89,12 @@ func get4(p []byte) uint32 {
}
func (z *Inflater) readString() (string, os.Error) {
- var err os.Error;
+ var err os.Error
for i := 0; ; i++ {
if i >= len(z.buf) {
return "", HeaderError
}
- z.buf[i], err = z.r.ReadByte();
+ z.buf[i], err = z.r.ReadByte()
if err != nil {
return "", err
}
@@ -102,40 +102,40 @@ func (z *Inflater) readString() (string, os.Error) {
return string(z.buf[0:i]), nil
}
}
- panic("not reached");
+ panic("not reached")
}
func (z *Inflater) read2() (uint32, os.Error) {
- _, err := z.r.Read(z.buf[0:2]);
+ _, err := z.r.Read(z.buf[0:2])
if err != nil {
return 0, err
}
- return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil;
+ return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil
}
func (z *Inflater) readHeader(save bool) os.Error {
- _, err := io.ReadFull(z.r, z.buf[0:10]);
+ _, err := io.ReadFull(z.r, z.buf[0:10])
if err != nil {
return err
}
if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
return HeaderError
}
- z.flg = z.buf[3];
+ z.flg = z.buf[3]
if save {
- z.Mtime = get4(z.buf[4:8]);
+ z.Mtime = get4(z.buf[4:8])
// z.buf[8] is xfl, ignored
- z.OS = z.buf[9];
+ z.OS = z.buf[9]
}
- z.digest.Reset();
- z.digest.Write(z.buf[0:10]);
+ z.digest.Reset()
+ z.digest.Write(z.buf[0:10])
if z.flg&flagExtra != 0 {
- n, err := z.read2();
+ n, err := z.read2()
if err != nil {
return err
}
- data := make([]byte, n);
+ data := make([]byte, n)
if _, err = io.ReadFull(z.r, data); err != nil {
return err
}
@@ -144,7 +144,7 @@ func (z *Inflater) readHeader(save bool) os.Error {
}
}
- var s string;
+ var s string
if z.flg&flagName != 0 {
if s, err = z.readString(); err != nil {
return err
@@ -164,19 +164,19 @@ func (z *Inflater) readHeader(save bool) os.Error {
}
if z.flg&flagHdrCrc != 0 {
- n, err := z.read2();
+ n, err := z.read2()
if err != nil {
return err
}
- sum := z.digest.Sum32() & 0xFFFF;
+ sum := z.digest.Sum32() & 0xFFFF
if n != sum {
return HeaderError
}
}
- z.digest.Reset();
- z.inflater = flate.NewInflater(z.r);
- return nil;
+ z.digest.Reset()
+ z.inflater = flate.NewInflater(z.r)
+ return nil
}
func (z *Inflater) Read(p []byte) (n int, err os.Error) {
@@ -187,37 +187,37 @@ func (z *Inflater) Read(p []byte) (n int, err os.Error) {
return 0, nil
}
- n, err = z.inflater.Read(p);
- z.digest.Write(p[0:n]);
- z.size += uint32(n);
+ n, err = z.inflater.Read(p)
+ z.digest.Write(p[0:n])
+ z.size += uint32(n)
if n != 0 || err != os.EOF {
- z.err = err;
- return;
+ z.err = err
+ return
}
// Finished file; check checksum + size.
if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
- z.err = err;
- return 0, err;
+ z.err = err
+ return 0, err
}
- crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8]);
- sum := z.digest.Sum32();
+ crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8])
+ sum := z.digest.Sum32()
if sum != crc32 || isize != z.size {
- z.err = ChecksumError;
- return 0, z.err;
+ z.err = ChecksumError
+ return 0, z.err
}
// File is ok; is there another?
if err = z.readHeader(false); err != nil {
- z.err = err;
- return;
+ z.err = err
+ return
}
// Yes. Reset and read from it.
- z.digest.Reset();
- z.size = 0;
- return z.Read(p);
+ z.digest.Reset()
+ z.size = 0
+ return z.Read(p)
}
// Calling Close does not close the wrapped io.Reader originally passed to NewInflater.
-func (z *Inflater) Close() os.Error { return z.inflater.Close() }
+func (z *Inflater) Close() os.Error { return z.inflater.Close() }
diff --git a/src/pkg/compress/gzip/gunzip_test.go b/src/pkg/compress/gzip/gunzip_test.go
index 67b3b3ce24..3930985e37 100644
--- a/src/pkg/compress/gzip/gunzip_test.go
+++ b/src/pkg/compress/gzip/gunzip_test.go
@@ -5,22 +5,22 @@
package gzip
import (
- "bytes";
- "io";
- "os";
- "testing";
+ "bytes"
+ "io"
+ "os"
+ "testing"
)
type gzipTest struct {
- name string;
- desc string;
- raw string;
- gzip []byte;
- err os.Error;
+ name string
+ desc string
+ raw string
+ gzip []byte
+ err os.Error
}
var gzipTests = []gzipTest{
- gzipTest{ // has 1 empty fixed-huffman block
+ gzipTest{ // has 1 empty fixed-huffman block
"empty.txt",
"empty.txt",
"",
@@ -32,7 +32,7 @@ var gzipTests = []gzipTest{
},
nil,
},
- gzipTest{ // has 1 non-empty fixed huffman block
+ gzipTest{ // has 1 non-empty fixed huffman block
"hello.txt",
"hello.txt",
"hello world\n",
@@ -46,7 +46,7 @@ var gzipTests = []gzipTest{
},
nil,
},
- gzipTest{ // concatenation
+ gzipTest{ // concatenation
"hello.txt",
"hello.txt x2",
"hello world\n" +
@@ -67,7 +67,7 @@ var gzipTests = []gzipTest{
},
nil,
},
- gzipTest{ // has a fixed huffman block with some length-distance pairs
+ gzipTest{ // has a fixed huffman block with some length-distance pairs
"shesells.txt",
"shesells.txt",
"she sells seashells by the seashore\n",
@@ -83,7 +83,7 @@ var gzipTests = []gzipTest{
},
nil,
},
- gzipTest{ // has dynamic huffman blocks
+ gzipTest{ // has dynamic huffman blocks
"gettysburg",
"gettysburg",
" Four score and seven years ago our fathers brought forth on\n" +
@@ -221,7 +221,7 @@ var gzipTests = []gzipTest{
},
nil,
},
- gzipTest{ // has 1 non-empty fixed huffman block then garbage
+ gzipTest{ // has 1 non-empty fixed huffman block then garbage
"hello.txt",
"hello.txt + garbage",
"hello world\n",
@@ -235,7 +235,7 @@ var gzipTests = []gzipTest{
},
HeaderError,
},
- gzipTest{ // has 1 non-empty fixed huffman block not enough header
+ gzipTest{ // has 1 non-empty fixed huffman block not enough header
"hello.txt",
"hello.txt + garbage",
"hello world\n",
@@ -249,7 +249,7 @@ var gzipTests = []gzipTest{
},
io.ErrUnexpectedEOF,
},
- gzipTest{ // has 1 non-empty fixed huffman block but corrupt checksum
+ gzipTest{ // has 1 non-empty fixed huffman block but corrupt checksum
"hello.txt",
"hello.txt + corrupt checksum",
"hello world\n",
@@ -263,7 +263,7 @@ var gzipTests = []gzipTest{
},
ChecksumError,
},
- gzipTest{ // has 1 non-empty fixed huffman block but corrupt size
+ gzipTest{ // has 1 non-empty fixed huffman block but corrupt size
"hello.txt",
"hello.txt + corrupt size",
"hello world\n",
@@ -280,24 +280,24 @@ var gzipTests = []gzipTest{
}
func TestInflater(t *testing.T) {
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for _, tt := range gzipTests {
- in := bytes.NewBuffer(tt.gzip);
- gzip, err := NewInflater(in);
+ in := bytes.NewBuffer(tt.gzip)
+ gzip, err := NewInflater(in)
if err != nil {
- t.Errorf("%s: NewInflater: %s", tt.name, err);
- continue;
+ t.Errorf("%s: NewInflater: %s", tt.name, err)
+ continue
}
- defer gzip.Close();
+ defer gzip.Close()
if tt.name != gzip.Name {
t.Errorf("%s: got name %s", tt.name, gzip.Name)
}
- b.Reset();
- n, err := io.Copy(b, gzip);
+ b.Reset()
+ n, err := io.Copy(b, gzip)
if err != tt.err {
t.Errorf("%s: io.Copy: %v want %v", tt.name, err, tt.err)
}
- s := b.String();
+ s := b.String()
if s != tt.raw {
t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.name, n, s, len(tt.raw), tt.raw)
}
diff --git a/src/pkg/compress/zlib/reader.go b/src/pkg/compress/zlib/reader.go
index ffe5cbafc7..c3a9d28ca6 100644
--- a/src/pkg/compress/zlib/reader.go
+++ b/src/pkg/compress/zlib/reader.go
@@ -7,12 +7,12 @@
package zlib
import (
- "bufio";
- "compress/flate";
- "hash";
- "hash/adler32";
- "io";
- "os";
+ "bufio"
+ "compress/flate"
+ "hash"
+ "hash/adler32"
+ "io"
+ "os"
)
const zlibDeflate = 8
@@ -22,28 +22,28 @@ var HeaderError os.Error = os.ErrorString("invalid zlib header")
var UnsupportedError os.Error = os.ErrorString("unsupported zlib format")
type reader struct {
- r flate.Reader;
- inflater io.ReadCloser;
- digest hash.Hash32;
- err os.Error;
- scratch [4]byte;
+ r flate.Reader
+ inflater io.ReadCloser
+ digest hash.Hash32
+ err os.Error
+ scratch [4]byte
}
// NewInflater creates a new io.ReadCloser that satisfies reads by decompressing data read from r.
// The implementation buffers input and may read more data than necessary from r.
// It is the caller's responsibility to call Close on the ReadCloser when done.
func NewInflater(r io.Reader) (io.ReadCloser, os.Error) {
- z := new(reader);
+ z := new(reader)
if fr, ok := r.(flate.Reader); ok {
z.r = fr
} else {
z.r = bufio.NewReader(r)
}
- _, err := io.ReadFull(z.r, z.scratch[0:2]);
+ _, err := io.ReadFull(z.r, z.scratch[0:2])
if err != nil {
return nil, err
}
- h := uint(z.scratch[0])<<8 | uint(z.scratch[1]);
+ h := uint(z.scratch[0])<<8 | uint(z.scratch[1])
if (z.scratch[0]&0x0f != zlibDeflate) || (h%31 != 0) {
return nil, HeaderError
}
@@ -51,9 +51,9 @@ func NewInflater(r io.Reader) (io.ReadCloser, os.Error) {
// BUG(nigeltao): The zlib package does not implement the FDICT flag.
return nil, UnsupportedError
}
- z.digest = adler32.New();
- z.inflater = flate.NewInflater(z.r);
- return z, nil;
+ z.digest = adler32.New()
+ z.inflater = flate.NewInflater(z.r)
+ return z, nil
}
func (z *reader) Read(p []byte) (n int, err os.Error) {
@@ -64,25 +64,25 @@ func (z *reader) Read(p []byte) (n int, err os.Error) {
return 0, nil
}
- n, err = z.inflater.Read(p);
- z.digest.Write(p[0:n]);
+ n, err = z.inflater.Read(p)
+ z.digest.Write(p[0:n])
if n != 0 || err != os.EOF {
- z.err = err;
- return;
+ z.err = err
+ return
}
// Finished file; check checksum.
if _, err := io.ReadFull(z.r, z.scratch[0:4]); err != nil {
- z.err = err;
- return 0, err;
+ z.err = err
+ return 0, err
}
// ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952).
- checksum := uint32(z.scratch[0])<<24 | uint32(z.scratch[1])<<16 | uint32(z.scratch[2])<<8 | uint32(z.scratch[3]);
+ checksum := uint32(z.scratch[0])<<24 | uint32(z.scratch[1])<<16 | uint32(z.scratch[2])<<8 | uint32(z.scratch[3])
if checksum != z.digest.Sum32() {
- z.err = ChecksumError;
- return 0, z.err;
+ z.err = ChecksumError
+ return 0, z.err
}
- return;
+ return
}
// Calling Close does not close the wrapped io.Reader originally passed to NewInflater.
@@ -90,6 +90,6 @@ func (z *reader) Close() os.Error {
if z.err != nil {
return z.err
}
- z.err = z.inflater.Close();
- return z.err;
+ z.err = z.inflater.Close()
+ return z.err
}
diff --git a/src/pkg/compress/zlib/reader_test.go b/src/pkg/compress/zlib/reader_test.go
index 5e057ee21b..3b349f5ee6 100644
--- a/src/pkg/compress/zlib/reader_test.go
+++ b/src/pkg/compress/zlib/reader_test.go
@@ -5,17 +5,17 @@
package zlib
import (
- "bytes";
- "io";
- "os";
- "testing";
+ "bytes"
+ "io"
+ "os"
+ "testing"
)
type zlibTest struct {
- desc string;
- raw string;
- compressed []byte;
- err os.Error;
+ desc string
+ raw string
+ compressed []byte
+ err os.Error
}
// Compare-to-golden test data was generated by the ZLIB example program at
@@ -68,26 +68,26 @@ var zlibTests = []zlibTest{
}
func TestInflater(t *testing.T) {
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for _, tt := range zlibTests {
- in := bytes.NewBuffer(tt.compressed);
- zlib, err := NewInflater(in);
+ in := bytes.NewBuffer(tt.compressed)
+ zlib, err := NewInflater(in)
if err != nil {
if err != tt.err {
t.Errorf("%s: NewInflater: %s", tt.desc, err)
}
- continue;
+ continue
}
- defer zlib.Close();
- b.Reset();
- n, err := io.Copy(b, zlib);
+ defer zlib.Close()
+ b.Reset()
+ n, err := io.Copy(b, zlib)
if err != nil {
if err != tt.err {
t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err)
}
- continue;
+ continue
}
- s := b.String();
+ s := b.String()
if s != tt.raw {
t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw)
}
diff --git a/src/pkg/compress/zlib/writer.go b/src/pkg/compress/zlib/writer.go
index 25abcde3bf..0441b04638 100644
--- a/src/pkg/compress/zlib/writer.go
+++ b/src/pkg/compress/zlib/writer.go
@@ -5,28 +5,28 @@
package zlib
import (
- "compress/flate";
- "hash";
- "hash/adler32";
- "io";
- "os";
+ "compress/flate"
+ "hash"
+ "hash/adler32"
+ "io"
+ "os"
)
// These constants are copied from the flate package, so that code that imports
// "compress/zlib" does not also have to import "compress/flate".
const (
- NoCompression = flate.NoCompression;
- BestSpeed = flate.BestSpeed;
- BestCompression = flate.BestCompression;
- DefaultCompression = flate.DefaultCompression;
+ NoCompression = flate.NoCompression
+ BestSpeed = flate.BestSpeed
+ BestCompression = flate.BestCompression
+ DefaultCompression = flate.DefaultCompression
)
type writer struct {
- w io.Writer;
- deflater io.WriteCloser;
- digest hash.Hash32;
- err os.Error;
- scratch [4]byte;
+ w io.Writer
+ deflater io.WriteCloser
+ digest hash.Hash32
+ err os.Error
+ scratch [4]byte
}
// NewDeflater calls NewDeflaterLevel with the default compression level.
@@ -39,11 +39,11 @@ func NewDeflater(w io.Writer) (io.WriteCloser, os.Error) {
// level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive).
func NewDeflaterLevel(w io.Writer, level int) (io.WriteCloser, os.Error) {
- z := new(writer);
+ z := new(writer)
// ZLIB has a two-byte header (as documented in RFC 1950).
// The first four bits is the CINFO (compression info), which is 7 for the default deflate window size.
// The next four bits is the CM (compression method), which is 8 for deflate.
- z.scratch[0] = 0x78;
+ z.scratch[0] = 0x78
// The next two bits is the FLEVEL (compression level). The four values are:
// 0=fastest, 1=fast, 2=default, 3=best.
// The next bit, FDICT, is unused, in this implementation.
@@ -60,14 +60,14 @@ func NewDeflaterLevel(w io.Writer, level int) (io.WriteCloser, os.Error) {
default:
return nil, os.NewError("level out of range")
}
- _, err := w.Write(z.scratch[0:2]);
+ _, err := w.Write(z.scratch[0:2])
if err != nil {
return nil, err
}
- z.w = w;
- z.deflater = flate.NewDeflater(w, level);
- z.digest = adler32.New();
- return z, nil;
+ z.w = w
+ z.deflater = flate.NewDeflater(w, level)
+ z.digest = adler32.New()
+ return z, nil
}
func (z *writer) Write(p []byte) (n int, err os.Error) {
@@ -77,13 +77,13 @@ func (z *writer) Write(p []byte) (n int, err os.Error) {
if len(p) == 0 {
return 0, nil
}
- n, err = z.deflater.Write(p);
+ n, err = z.deflater.Write(p)
if err != nil {
- z.err = err;
- return;
+ z.err = err
+ return
}
- z.digest.Write(p);
- return;
+ z.digest.Write(p)
+ return
}
// Calling Close does not close the wrapped io.Writer originally passed to NewDeflater.
@@ -91,16 +91,16 @@ func (z *writer) Close() os.Error {
if z.err != nil {
return z.err
}
- z.err = z.deflater.Close();
+ z.err = z.deflater.Close()
if z.err != nil {
return z.err
}
- checksum := z.digest.Sum32();
+ checksum := z.digest.Sum32()
// ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952).
- z.scratch[0] = uint8(checksum >> 24);
- z.scratch[1] = uint8(checksum >> 16);
- z.scratch[2] = uint8(checksum >> 8);
- z.scratch[3] = uint8(checksum >> 0);
- _, z.err = z.w.Write(z.scratch[0:4]);
- return z.err;
+ z.scratch[0] = uint8(checksum >> 24)
+ z.scratch[1] = uint8(checksum >> 16)
+ z.scratch[2] = uint8(checksum >> 8)
+ z.scratch[3] = uint8(checksum >> 0)
+ _, z.err = z.w.Write(z.scratch[0:4])
+ return z.err
}
diff --git a/src/pkg/compress/zlib/writer_test.go b/src/pkg/compress/zlib/writer_test.go
index 963a072e9d..97a9ed6190 100644
--- a/src/pkg/compress/zlib/writer_test.go
+++ b/src/pkg/compress/zlib/writer_test.go
@@ -5,10 +5,10 @@
package zlib
import (
- "io";
- "io/ioutil";
- "os";
- "testing";
+ "io"
+ "io/ioutil"
+ "os"
+ "testing"
)
var filenames = []string{
@@ -20,85 +20,85 @@ var filenames = []string{
// yields equivalent bytes to the original file.
func testFileLevel(t *testing.T, fn string, level int) {
// Read the file, as golden output.
- golden, err := os.Open(fn, os.O_RDONLY, 0444);
+ golden, err := os.Open(fn, os.O_RDONLY, 0444)
if err != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err)
+ return
}
- defer golden.Close();
+ defer golden.Close()
// Read the file again, and push it through a pipe that compresses at the write end, and decompresses at the read end.
- raw, err := os.Open(fn, os.O_RDONLY, 0444);
+ raw, err := os.Open(fn, os.O_RDONLY, 0444)
if err != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err)
+ return
}
- piper, pipew := io.Pipe();
- defer piper.Close();
+ piper, pipew := io.Pipe()
+ defer piper.Close()
go func() {
- defer raw.Close();
- defer pipew.Close();
- zlibw, err := NewDeflaterLevel(pipew, level);
+ defer raw.Close()
+ defer pipew.Close()
+ zlibw, err := NewDeflaterLevel(pipew, level)
if err != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err)
+ return
}
- defer zlibw.Close();
- var b [1024]byte;
+ defer zlibw.Close()
+ var b [1024]byte
for {
- n, err0 := raw.Read(&b);
+ n, err0 := raw.Read(&b)
if err0 != nil && err0 != os.EOF {
- t.Errorf("%s (level=%d): %v", fn, level, err0);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err0)
+ return
}
- _, err1 := zlibw.Write(b[0:n]);
+ _, err1 := zlibw.Write(b[0:n])
if err1 == os.EPIPE {
// Fail, but do not report the error, as some other (presumably reportable) error broke the pipe.
return
}
if err1 != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err1);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err1)
+ return
}
if err0 == os.EOF {
break
}
}
- }();
- zlibr, err := NewInflater(piper);
+ }()
+ zlibr, err := NewInflater(piper)
if err != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err)
+ return
}
- defer zlibr.Close();
+ defer zlibr.Close()
// Compare the two.
- b0, err0 := ioutil.ReadAll(golden);
- b1, err1 := ioutil.ReadAll(zlibr);
+ b0, err0 := ioutil.ReadAll(golden)
+ b1, err1 := ioutil.ReadAll(zlibr)
if err0 != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err0);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err0)
+ return
}
if err1 != nil {
- t.Errorf("%s (level=%d): %v", fn, level, err1);
- return;
+ t.Errorf("%s (level=%d): %v", fn, level, err1)
+ return
}
if len(b0) != len(b1) {
- t.Errorf("%s (level=%d): length mismatch %d versus %d", fn, level, len(b0), len(b1));
- return;
+ t.Errorf("%s (level=%d): length mismatch %d versus %d", fn, level, len(b0), len(b1))
+ return
}
for i := 0; i < len(b0); i++ {
if b0[i] != b1[i] {
- t.Errorf("%s (level=%d): mismatch at %d, 0x%02x versus 0x%02x\n", fn, level, i, b0[i], b1[i]);
- return;
+ t.Errorf("%s (level=%d): mismatch at %d, 0x%02x versus 0x%02x\n", fn, level, i, b0[i], b1[i])
+ return
}
}
}
func TestWriter(t *testing.T) {
for _, fn := range filenames {
- testFileLevel(t, fn, DefaultCompression);
- testFileLevel(t, fn, NoCompression);
+ testFileLevel(t, fn, DefaultCompression)
+ testFileLevel(t, fn, NoCompression)
for level := BestSpeed; level <= BestCompression; level++ {
testFileLevel(t, fn, level)
}
diff --git a/src/pkg/container/heap/heap.go b/src/pkg/container/heap/heap.go
index 7a7cb9b803..4435a57c4e 100644
--- a/src/pkg/container/heap/heap.go
+++ b/src/pkg/container/heap/heap.go
@@ -16,9 +16,9 @@ import "sort"
// !h.Less(j, i) for 0 <= i < h.Len() and j = 2*i+1 or 2*i+2 and j < h.Len()
//
type Interface interface {
- sort.Interface;
- Push(x interface{});
- Pop() interface{};
+ sort.Interface
+ Push(x interface{})
+ Pop() interface{}
}
@@ -29,7 +29,7 @@ type Interface interface {
//
func Init(h Interface) {
// heapify
- n := h.Len();
+ n := h.Len()
for i := n/2 - 1; i >= 0; i-- {
down(h, i, n)
}
@@ -40,8 +40,8 @@ func Init(h Interface) {
// O(log(n)) where n = h.Len().
//
func Push(h Interface, x interface{}) {
- h.Push(x);
- up(h, h.Len()-1);
+ h.Push(x)
+ up(h, h.Len()-1)
}
@@ -50,10 +50,10 @@ func Push(h Interface, x interface{}) {
// Same as Remove(h, 0).
//
func Pop(h Interface) interface{} {
- n := h.Len() - 1;
- h.Swap(0, n);
- down(h, 0, n);
- return h.Pop();
+ n := h.Len() - 1
+ h.Swap(0, n)
+ down(h, 0, n)
+ return h.Pop()
}
@@ -61,42 +61,42 @@ func Pop(h Interface) interface{} {
// The complexity is O(log(n)) where n = h.Len().
//
func Remove(h Interface, i int) interface{} {
- n := h.Len() - 1;
+ n := h.Len() - 1
if n != i {
- h.Swap(i, n);
- down(h, i, n);
- up(h, i);
+ h.Swap(i, n)
+ down(h, i, n)
+ up(h, i)
}
- return h.Pop();
+ return h.Pop()
}
func up(h Interface, j int) {
for {
- i := (j - 1) / 2; // parent
+ i := (j - 1) / 2 // parent
if i == j || h.Less(i, j) {
break
}
- h.Swap(i, j);
- j = i;
+ h.Swap(i, j)
+ j = i
}
}
func down(h Interface, i, n int) {
for {
- j1 := 2*i + 1;
+ j1 := 2*i + 1
if j1 >= n {
break
}
- j := j1; // left child
+ j := j1 // left child
if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) {
- j = j2 // = 2*i + 2 // right child
+ j = j2 // = 2*i + 2 // right child
}
if h.Less(i, j) {
break
}
- h.Swap(i, j);
- i = j;
+ h.Swap(i, j)
+ i = j
}
}
diff --git a/src/pkg/container/heap/heap_test.go b/src/pkg/container/heap/heap_test.go
index dc13201cd3..8130555f38 100644
--- a/src/pkg/container/heap/heap_test.go
+++ b/src/pkg/container/heap/heap_test.go
@@ -5,53 +5,53 @@
package heap
import (
- "testing";
- "container/vector";
+ "testing"
+ "container/vector"
)
type myHeap struct {
// A vector.Vector implements sort.Interface except for Less,
// and it implements Push and Pop as required for heap.Interface.
- vector.Vector;
+ vector.Vector
}
-func (h *myHeap) Less(i, j int) bool { return h.At(i).(int) < h.At(j).(int) }
+func (h *myHeap) Less(i, j int) bool { return h.At(i).(int) < h.At(j).(int) }
func (h *myHeap) verify(t *testing.T, i int) {
- n := h.Len();
- j1 := 2*i + 1;
- j2 := 2*i + 2;
+ n := h.Len()
+ j1 := 2*i + 1
+ j2 := 2*i + 2
if j1 < n {
if h.Less(j1, i) {
- t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h.At(i), j1, h.At(j1));
- return;
+ t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h.At(i), j1, h.At(j1))
+ return
}
- h.verify(t, j1);
+ h.verify(t, j1)
}
if j2 < n {
if h.Less(j2, i) {
- t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h.At(i), j1, h.At(j2));
- return;
+ t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h.At(i), j1, h.At(j2))
+ return
}
- h.verify(t, j2);
+ h.verify(t, j2)
}
}
func TestInit0(t *testing.T) {
- h := new(myHeap);
+ h := new(myHeap)
for i := 20; i > 0; i-- {
- h.Push(0) // all elements are the same
+ h.Push(0) // all elements are the same
}
- Init(h);
- h.verify(t, 0);
+ Init(h)
+ h.verify(t, 0)
for i := 1; h.Len() > 0; i++ {
- x := Pop(h).(int);
- h.verify(t, 0);
+ x := Pop(h).(int)
+ h.verify(t, 0)
if x != 0 {
t.Errorf("%d.th pop got %d; want %d", i, x, 0)
}
@@ -60,16 +60,16 @@ func TestInit0(t *testing.T) {
func TestInit1(t *testing.T) {
- h := new(myHeap);
+ h := new(myHeap)
for i := 20; i > 0; i-- {
- h.Push(i) // all elements are different
+ h.Push(i) // all elements are different
}
- Init(h);
- h.verify(t, 0);
+ Init(h)
+ h.verify(t, 0)
for i := 1; h.Len() > 0; i++ {
- x := Pop(h).(int);
- h.verify(t, 0);
+ x := Pop(h).(int)
+ h.verify(t, 0)
if x != i {
t.Errorf("%d.th pop got %d; want %d", i, x, i)
}
@@ -78,26 +78,26 @@ func TestInit1(t *testing.T) {
func Test(t *testing.T) {
- h := new(myHeap);
- h.verify(t, 0);
+ h := new(myHeap)
+ h.verify(t, 0)
for i := 20; i > 10; i-- {
h.Push(i)
}
- Init(h);
- h.verify(t, 0);
+ Init(h)
+ h.verify(t, 0)
for i := 10; i > 0; i-- {
- Push(h, i);
- h.verify(t, 0);
+ Push(h, i)
+ h.verify(t, 0)
}
for i := 1; h.Len() > 0; i++ {
- x := Pop(h).(int);
+ x := Pop(h).(int)
if i < 20 {
Push(h, 20+i)
}
- h.verify(t, 0);
+ h.verify(t, 0)
if x != i {
t.Errorf("%d.th pop got %d; want %d", i, x, i)
}
@@ -106,53 +106,53 @@ func Test(t *testing.T) {
func TestRemove0(t *testing.T) {
- h := new(myHeap);
+ h := new(myHeap)
for i := 0; i < 10; i++ {
h.Push(i)
}
- h.verify(t, 0);
+ h.verify(t, 0)
for h.Len() > 0 {
- i := h.Len() - 1;
- x := Remove(h, i).(int);
+ i := h.Len() - 1
+ x := Remove(h, i).(int)
if x != i {
t.Errorf("Remove(%d) got %d; want %d", i, x, i)
}
- h.verify(t, 0);
+ h.verify(t, 0)
}
}
func TestRemove1(t *testing.T) {
- h := new(myHeap);
+ h := new(myHeap)
for i := 0; i < 10; i++ {
h.Push(i)
}
- h.verify(t, 0);
+ h.verify(t, 0)
for i := 0; h.Len() > 0; i++ {
- x := Remove(h, 0).(int);
+ x := Remove(h, 0).(int)
if x != i {
t.Errorf("Remove(0) got %d; want %d", x, i)
}
- h.verify(t, 0);
+ h.verify(t, 0)
}
}
func TestRemove2(t *testing.T) {
- N := 10;
+ N := 10
- h := new(myHeap);
+ h := new(myHeap)
for i := 0; i < N; i++ {
h.Push(i)
}
- h.verify(t, 0);
+ h.verify(t, 0)
- m := make(map[int]int);
+ m := make(map[int]int)
for h.Len() > 0 {
- m[Remove(h, (h.Len()-1)/2).(int)] = 1;
- h.verify(t, 0);
+ m[Remove(h, (h.Len()-1)/2).(int)] = 1
+ h.verify(t, 0)
}
if len(m) != N {
diff --git a/src/pkg/container/list/list.go b/src/pkg/container/list/list.go
index b7b392ceaa..9429c90a72 100644
--- a/src/pkg/container/list/list.go
+++ b/src/pkg/container/list/list.go
@@ -9,45 +9,45 @@ package list
type Element struct {
// Next and previous pointers in the doubly-linked list of elements.
// The front of the list has prev = nil, and the back has next = nil.
- next, prev *Element;
+ next, prev *Element
// A unique ID for the list to which this element belongs.
- id *byte;
+ id *byte
// The contents of this list element.
- Value interface{};
+ Value interface{}
}
// Next returns the next list element or nil.
-func (e *Element) Next() *Element { return e.next }
+func (e *Element) Next() *Element { return e.next }
// Prev returns the previous list element or nil.
-func (e *Element) Prev() *Element { return e.prev }
+func (e *Element) Prev() *Element { return e.prev }
// List represents a doubly linked list.
type List struct {
- front, back *Element;
- len int;
- id *byte;
+ front, back *Element
+ len int
+ id *byte
}
// Init initializes or clears a List.
func (l *List) Init() *List {
- l.front = nil;
- l.back = nil;
- l.len = 0;
- l.id = new(byte);
- return l;
+ l.front = nil
+ l.back = nil
+ l.len = 0
+ l.id = new(byte)
+ return l
}
// New returns an initialized list.
-func New() *List { return new(List).Init() }
+func New() *List { return new(List).Init() }
// Front returns the first element in the list.
-func (l *List) Front() *Element { return l.front }
+func (l *List) Front() *Element { return l.front }
// Back returns the last element in the list.
-func (l *List) Back() *Element { return l.back }
+func (l *List) Back() *Element { return l.back }
// Remove removes the element from the list.
func (l *List) Remove(e *Element) {
@@ -65,9 +65,9 @@ func (l *List) Remove(e *Element) {
e.next.prev = e.prev
}
- e.prev = nil;
- e.next = nil;
- l.len--;
+ e.prev = nil
+ e.next = nil
+ l.len--
}
func (l *List) insertBefore(e *Element, mark *Element) {
@@ -77,10 +77,10 @@ func (l *List) insertBefore(e *Element, mark *Element) {
} else {
mark.prev.next = e
}
- e.prev = mark.prev;
- mark.prev = e;
- e.next = mark;
- l.len++;
+ e.prev = mark.prev
+ mark.prev = e
+ e.next = mark
+ l.len++
}
func (l *List) insertAfter(e *Element, mark *Element) {
@@ -90,32 +90,32 @@ func (l *List) insertAfter(e *Element, mark *Element) {
} else {
mark.next.prev = e
}
- e.next = mark.next;
- mark.next = e;
- e.prev = mark;
- l.len++;
+ e.next = mark.next
+ mark.next = e
+ e.prev = mark
+ l.len++
}
func (l *List) insertFront(e *Element) {
if l.front == nil {
// empty list
- l.front, l.back = e, e;
- e.prev, e.next = nil, nil;
- l.len = 1;
- return;
+ l.front, l.back = e, e
+ e.prev, e.next = nil, nil
+ l.len = 1
+ return
}
- l.insertBefore(e, l.front);
+ l.insertBefore(e, l.front)
}
func (l *List) insertBack(e *Element) {
if l.back == nil {
// empty list
- l.front, l.back = e, e;
- e.prev, e.next = nil, nil;
- l.len = 1;
- return;
+ l.front, l.back = e, e
+ e.prev, e.next = nil, nil
+ l.len = 1
+ return
}
- l.insertAfter(e, l.back);
+ l.insertAfter(e, l.back)
}
// PushFront inserts the value at the front of the list and returns a new Element containing the value.
@@ -123,9 +123,9 @@ func (l *List) PushFront(value interface{}) *Element {
if l.id == nil {
l.Init()
}
- e := &Element{nil, nil, l.id, value};
- l.insertFront(e);
- return e;
+ e := &Element{nil, nil, l.id, value}
+ l.insertFront(e)
+ return e
}
// PushBack inserts the value at the back of the list and returns a new Element containing the value.
@@ -133,9 +133,9 @@ func (l *List) PushBack(value interface{}) *Element {
if l.id == nil {
l.Init()
}
- e := &Element{nil, nil, l.id, value};
- l.insertBack(e);
- return e;
+ e := &Element{nil, nil, l.id, value}
+ l.insertBack(e)
+ return e
}
// InsertBefore inserts the value immediately before mark and returns a new Element containing the value.
@@ -143,9 +143,9 @@ func (l *List) InsertBefore(value interface{}, mark *Element) *Element {
if mark.id != l.id {
return nil
}
- e := &Element{nil, nil, l.id, value};
- l.insertBefore(e, mark);
- return e;
+ e := &Element{nil, nil, l.id, value}
+ l.insertBefore(e, mark)
+ return e
}
// InsertAfter inserts the value immediately after mark and returns a new Element containing the value.
@@ -153,9 +153,9 @@ func (l *List) InsertAfter(value interface{}, mark *Element) *Element {
if mark.id != l.id {
return nil
}
- e := &Element{nil, nil, l.id, value};
- l.insertAfter(e, mark);
- return e;
+ e := &Element{nil, nil, l.id, value}
+ l.insertAfter(e, mark)
+ return e
}
// MoveToFront moves the element to the front of the list.
@@ -163,8 +163,8 @@ func (l *List) MoveToFront(e *Element) {
if e.id != l.id || l.front == e {
return
}
- l.Remove(e);
- l.insertFront(e);
+ l.Remove(e)
+ l.insertFront(e)
}
// MoveToBack moves the element to the back of the list.
@@ -172,22 +172,22 @@ func (l *List) MoveToBack(e *Element) {
if e.id != l.id || l.back == e {
return
}
- l.Remove(e);
- l.insertBack(e);
+ l.Remove(e)
+ l.insertBack(e)
}
// Len returns the number of elements in the list.
-func (l *List) Len() int { return l.len }
+func (l *List) Len() int { return l.len }
func (l *List) iterate(c chan<- interface{}) {
for e := l.front; e != nil; e = e.next {
c <- e.Value
}
- close(c);
+ close(c)
}
func (l *List) Iter() <-chan interface{} {
- c := make(chan interface{});
- go l.iterate(c);
- return c;
+ c := make(chan interface{})
+ go l.iterate(c)
+ return c
}
diff --git a/src/pkg/container/list/list_test.go b/src/pkg/container/list/list_test.go
index 52df37f561..846937a383 100644
--- a/src/pkg/container/list/list_test.go
+++ b/src/pkg/container/list/list_test.go
@@ -5,7 +5,7 @@
package list
import (
- "testing";
+ "testing"
)
func checkListPointers(t *testing.T, l *List, es []*Element) {
@@ -13,7 +13,7 @@ func checkListPointers(t *testing.T, l *List, es []*Element) {
if l.front != nil || l.back != nil {
t.Errorf("l.front/l.back = %v/%v should be nil/nil", l.front, l.back)
}
- return;
+ return
}
if l.front != es[0] {
@@ -24,8 +24,8 @@ func checkListPointers(t *testing.T, l *List, es []*Element) {
}
for i := 0; i < len(es); i++ {
- e := es[i];
- var e_prev, e_next *Element = nil, nil;
+ e := es[i]
+ var e_prev, e_next *Element = nil, nil
if i > 0 {
e_prev = es[i-1]
}
@@ -48,74 +48,74 @@ func checkListLen(t *testing.T, l *List, n int) {
}
func TestList(t *testing.T) {
- l := New();
- checkListPointers(t, l, []*Element{});
- checkListLen(t, l, 0);
+ l := New()
+ checkListPointers(t, l, []*Element{})
+ checkListLen(t, l, 0)
// Single element list
- e := l.PushFront("a");
- checkListLen(t, l, 1);
- checkListPointers(t, l, []*Element{e});
- l.MoveToFront(e);
- checkListPointers(t, l, []*Element{e});
- l.MoveToBack(e);
- checkListPointers(t, l, []*Element{e});
- checkListLen(t, l, 1);
- l.Remove(e);
- checkListPointers(t, l, []*Element{});
- checkListLen(t, l, 0);
+ e := l.PushFront("a")
+ checkListLen(t, l, 1)
+ checkListPointers(t, l, []*Element{e})
+ l.MoveToFront(e)
+ checkListPointers(t, l, []*Element{e})
+ l.MoveToBack(e)
+ checkListPointers(t, l, []*Element{e})
+ checkListLen(t, l, 1)
+ l.Remove(e)
+ checkListPointers(t, l, []*Element{})
+ checkListLen(t, l, 0)
// Bigger list
- e2 := l.PushFront(2);
- e1 := l.PushFront(1);
- e3 := l.PushBack(3);
- e4 := l.PushBack("banana");
- checkListPointers(t, l, []*Element{e1, e2, e3, e4});
- checkListLen(t, l, 4);
+ e2 := l.PushFront(2)
+ e1 := l.PushFront(1)
+ e3 := l.PushBack(3)
+ e4 := l.PushBack("banana")
+ checkListPointers(t, l, []*Element{e1, e2, e3, e4})
+ checkListLen(t, l, 4)
- l.Remove(e2);
- checkListPointers(t, l, []*Element{e1, e3, e4});
- checkListLen(t, l, 3);
+ l.Remove(e2)
+ checkListPointers(t, l, []*Element{e1, e3, e4})
+ checkListLen(t, l, 3)
- l.MoveToFront(e3); // move from middle
- checkListPointers(t, l, []*Element{e3, e1, e4});
+ l.MoveToFront(e3) // move from middle
+ checkListPointers(t, l, []*Element{e3, e1, e4})
- l.MoveToFront(e1);
- l.MoveToBack(e3); // move from middle
- checkListPointers(t, l, []*Element{e1, e4, e3});
+ l.MoveToFront(e1)
+ l.MoveToBack(e3) // move from middle
+ checkListPointers(t, l, []*Element{e1, e4, e3})
- l.MoveToFront(e3); // move from back
- checkListPointers(t, l, []*Element{e3, e1, e4});
- l.MoveToFront(e3); // should be no-op
- checkListPointers(t, l, []*Element{e3, e1, e4});
+ l.MoveToFront(e3) // move from back
+ checkListPointers(t, l, []*Element{e3, e1, e4})
+ l.MoveToFront(e3) // should be no-op
+ checkListPointers(t, l, []*Element{e3, e1, e4})
- l.MoveToBack(e3); // move from front
- checkListPointers(t, l, []*Element{e1, e4, e3});
- l.MoveToBack(e3); // should be no-op
- checkListPointers(t, l, []*Element{e1, e4, e3});
+ l.MoveToBack(e3) // move from front
+ checkListPointers(t, l, []*Element{e1, e4, e3})
+ l.MoveToBack(e3) // should be no-op
+ checkListPointers(t, l, []*Element{e1, e4, e3})
- e2 = l.InsertBefore(2, e1); // insert before front
- checkListPointers(t, l, []*Element{e2, e1, e4, e3});
- l.Remove(e2);
- e2 = l.InsertBefore(2, e4); // insert before middle
- checkListPointers(t, l, []*Element{e1, e2, e4, e3});
- l.Remove(e2);
- e2 = l.InsertBefore(2, e3); // insert before back
- checkListPointers(t, l, []*Element{e1, e4, e2, e3});
- l.Remove(e2);
+ e2 = l.InsertBefore(2, e1) // insert before front
+ checkListPointers(t, l, []*Element{e2, e1, e4, e3})
+ l.Remove(e2)
+ e2 = l.InsertBefore(2, e4) // insert before middle
+ checkListPointers(t, l, []*Element{e1, e2, e4, e3})
+ l.Remove(e2)
+ e2 = l.InsertBefore(2, e3) // insert before back
+ checkListPointers(t, l, []*Element{e1, e4, e2, e3})
+ l.Remove(e2)
- e2 = l.InsertAfter(2, e1); // insert after front
- checkListPointers(t, l, []*Element{e1, e2, e4, e3});
- l.Remove(e2);
- e2 = l.InsertAfter(2, e4); // insert after middle
- checkListPointers(t, l, []*Element{e1, e4, e2, e3});
- l.Remove(e2);
- e2 = l.InsertAfter(2, e3); // insert after back
- checkListPointers(t, l, []*Element{e1, e4, e3, e2});
- l.Remove(e2);
+ e2 = l.InsertAfter(2, e1) // insert after front
+ checkListPointers(t, l, []*Element{e1, e2, e4, e3})
+ l.Remove(e2)
+ e2 = l.InsertAfter(2, e4) // insert after middle
+ checkListPointers(t, l, []*Element{e1, e4, e2, e3})
+ l.Remove(e2)
+ e2 = l.InsertAfter(2, e3) // insert after back
+ checkListPointers(t, l, []*Element{e1, e4, e3, e2})
+ l.Remove(e2)
// Check standard iteration.
- sum := 0;
+ sum := 0
for e := range l.Iter() {
if i, ok := e.(int); ok {
sum += i
@@ -126,11 +126,11 @@ func TestList(t *testing.T) {
}
// Clear all elements by iterating
- var next *Element;
+ var next *Element
for e := l.Front(); e != nil; e = next {
- next = e.Next();
- l.Remove(e);
+ next = e.Next()
+ l.Remove(e)
}
- checkListPointers(t, l, []*Element{});
- checkListLen(t, l, 0);
+ checkListPointers(t, l, []*Element{})
+ checkListLen(t, l, 0)
}
diff --git a/src/pkg/container/ring/ring.go b/src/pkg/container/ring/ring.go
index 5fcdfc366f..335afbc3cc 100644
--- a/src/pkg/container/ring/ring.go
+++ b/src/pkg/container/ring/ring.go
@@ -12,15 +12,15 @@ package ring
// ring with a nil Value.
//
type Ring struct {
- next, prev *Ring;
- Value interface{}; // for use by client; untouched by this library
+ next, prev *Ring
+ Value interface{} // for use by client; untouched by this library
}
func (r *Ring) init() *Ring {
- r.next = r;
- r.prev = r;
- return r;
+ r.next = r
+ r.prev = r
+ return r
}
@@ -29,7 +29,7 @@ func (r *Ring) Next() *Ring {
if r.next == nil {
return r.init()
}
- return r.next;
+ return r.next
}
@@ -38,7 +38,7 @@ func (r *Ring) Prev() *Ring {
if r.next == nil {
return r.init()
}
- return r.prev;
+ return r.prev
}
@@ -59,7 +59,7 @@ func (r *Ring) Move(n int) *Ring {
r = r.next
}
}
- return r;
+ return r
}
@@ -68,15 +68,15 @@ func New(n int) *Ring {
if n <= 0 {
return nil
}
- r := new(Ring);
- p := r;
+ r := new(Ring)
+ p := r
for i := 1; i < n; i++ {
- p.next = &Ring{prev: p};
- p = p.next;
+ p.next = &Ring{prev: p}
+ p = p.next
}
- p.next = r;
- r.prev = p;
- return r;
+ p.next = r
+ r.prev = p
+ return r
}
@@ -97,17 +97,17 @@ func New(n int) *Ring {
// last element of s after insertion.
//
func (r *Ring) Link(s *Ring) *Ring {
- n := r.Next();
+ n := r.Next()
if s != nil {
- p := s.Prev();
+ p := s.Prev()
// Note: Cannot use multiple assignment because
// evaluation order of LHS is not specified.
- r.next = s;
- s.prev = r;
- n.prev = p;
- p.next = n;
+ r.next = s
+ s.prev = r
+ n.prev = p
+ p.next = n
}
- return n;
+ return n
}
@@ -119,7 +119,7 @@ func (r *Ring) Unlink(n int) *Ring {
if n <= 0 {
return nil
}
- return r.Link(r.Move(n + 1));
+ return r.Link(r.Move(n + 1))
}
@@ -127,27 +127,27 @@ func (r *Ring) Unlink(n int) *Ring {
// It executes in time proportional to the number of elements.
//
func (r *Ring) Len() int {
- n := 0;
+ n := 0
if r != nil {
- n = 1;
+ n = 1
for p := r.Next(); p != r; p = p.next {
n++
}
}
- return n;
+ return n
}
func (r *Ring) Iter() <-chan interface{} {
- c := make(chan interface{});
+ c := make(chan interface{})
go func() {
if r != nil {
- c <- r.Value;
+ c <- r.Value
for p := r.Next(); p != r; p = p.next {
c <- p.Value
}
}
- close(c);
- }();
- return c;
+ close(c)
+ }()
+ return c
}
diff --git a/src/pkg/container/ring/ring_test.go b/src/pkg/container/ring/ring_test.go
index b55f438fa2..ee3c411283 100644
--- a/src/pkg/container/ring/ring_test.go
+++ b/src/pkg/container/ring/ring_test.go
@@ -5,38 +5,38 @@
package ring
import (
- "fmt";
- "testing";
+ "fmt"
+ "testing"
)
// For debugging - keep around.
func dump(r *Ring) {
if r == nil {
- fmt.Println("empty");
- return;
+ fmt.Println("empty")
+ return
}
- i, n := 0, r.Len();
+ i, n := 0, r.Len()
for p := r; i < n; p = p.next {
- fmt.Printf("%4d: %p = {<- %p | %p ->}\n", i, p, p.prev, p.next);
- i++;
+ fmt.Printf("%4d: %p = {<- %p | %p ->}\n", i, p, p.prev, p.next)
+ i++
}
- fmt.Println();
+ fmt.Println()
}
func verify(t *testing.T, r *Ring, N int, sum int) {
// Len
- n := r.Len();
+ n := r.Len()
if n != N {
t.Errorf("r.Len() == %d; expected %d", n, N)
}
// iteration
- n = 0;
- s := 0;
+ n = 0
+ s := 0
for p := range r.Iter() {
- n++;
+ n++
if p != nil {
s += p.(int)
}
@@ -54,12 +54,12 @@ func verify(t *testing.T, r *Ring, N int, sum int) {
// connections
if r.next != nil {
- var p *Ring; // previous element
+ var p *Ring // previous element
for q := r; p == nil || q != r; q = q.next {
if p != nil && p != q.prev {
t.Errorf("prev = %p, expected q.prev = %p\n", p, q.prev)
}
- p = q;
+ p = q
}
if p != r.prev {
t.Errorf("prev = %p, expected r.prev = %p\n", p, r.prev)
@@ -85,8 +85,8 @@ func verify(t *testing.T, r *Ring, N int, sum int) {
t.Errorf("r.Move(%d) != r", -N)
}
for i := 0; i < 10; i++ {
- ni := N + i;
- mi := ni % N;
+ ni := N + i
+ mi := ni % N
if r.Move(ni) != r.Move(mi) {
t.Errorf("r.Move(%d) != r.Move(%d)", ni, mi)
}
@@ -99,142 +99,142 @@ func verify(t *testing.T, r *Ring, N int, sum int) {
func TestCornerCases(t *testing.T) {
var (
- r0 *Ring;
- r1 Ring;
+ r0 *Ring
+ r1 Ring
)
// Basics
- verify(t, r0, 0, 0);
- verify(t, &r1, 1, 0);
+ verify(t, r0, 0, 0)
+ verify(t, &r1, 1, 0)
// Insert
- r1.Link(r0);
- verify(t, r0, 0, 0);
- verify(t, &r1, 1, 0);
+ r1.Link(r0)
+ verify(t, r0, 0, 0)
+ verify(t, &r1, 1, 0)
// Insert
- r1.Link(r0);
- verify(t, r0, 0, 0);
- verify(t, &r1, 1, 0);
+ r1.Link(r0)
+ verify(t, r0, 0, 0)
+ verify(t, &r1, 1, 0)
// Unlink
- r1.Unlink(0);
- verify(t, &r1, 1, 0);
+ r1.Unlink(0)
+ verify(t, &r1, 1, 0)
}
func makeN(n int) *Ring {
- r := New(n);
+ r := New(n)
for i := 1; i <= n; i++ {
- r.Value = i;
- r = r.Next();
+ r.Value = i
+ r = r.Next()
}
- return r;
+ return r
}
func sum(r *Ring) int {
- s := 0;
+ s := 0
for p := range r.Iter() {
s += p.(int)
}
- return s;
+ return s
}
-func sumN(n int) int { return (n*n + n) / 2 }
+func sumN(n int) int { return (n*n + n) / 2 }
func TestNew(t *testing.T) {
for i := 0; i < 10; i++ {
- r := New(i);
- verify(t, r, i, -1);
+ r := New(i)
+ verify(t, r, i, -1)
}
for i := 0; i < 10; i++ {
- r := makeN(i);
- verify(t, r, i, sumN(i));
+ r := makeN(i)
+ verify(t, r, i, sumN(i))
}
}
func TestLink1(t *testing.T) {
- r1a := makeN(1);
- var r1b Ring;
- r2a := r1a.Link(&r1b);
- verify(t, r2a, 2, 1);
+ r1a := makeN(1)
+ var r1b Ring
+ r2a := r1a.Link(&r1b)
+ verify(t, r2a, 2, 1)
if r2a != r1a {
t.Errorf("a) 2-element link failed")
}
- r2b := r2a.Link(r2a.Next());
- verify(t, r2b, 2, 1);
+ r2b := r2a.Link(r2a.Next())
+ verify(t, r2b, 2, 1)
if r2b != r2a.Next() {
t.Errorf("b) 2-element link failed")
}
- r1c := r2b.Link(r2b);
- verify(t, r1c, 1, 1);
- verify(t, r2b, 1, 0);
+ r1c := r2b.Link(r2b)
+ verify(t, r1c, 1, 1)
+ verify(t, r2b, 1, 0)
}
func TestLink2(t *testing.T) {
- var r0 *Ring;
- r1a := &Ring{Value: 42};
- r1b := &Ring{Value: 77};
- r10 := makeN(10);
+ var r0 *Ring
+ r1a := &Ring{Value: 42}
+ r1b := &Ring{Value: 77}
+ r10 := makeN(10)
- r1a.Link(r0);
- verify(t, r1a, 1, 42);
+ r1a.Link(r0)
+ verify(t, r1a, 1, 42)
- r1a.Link(r1b);
- verify(t, r1a, 2, 42+77);
+ r1a.Link(r1b)
+ verify(t, r1a, 2, 42+77)
- r10.Link(r0);
- verify(t, r10, 10, sumN(10));
+ r10.Link(r0)
+ verify(t, r10, 10, sumN(10))
- r10.Link(r1a);
- verify(t, r10, 12, sumN(10)+42+77);
+ r10.Link(r1a)
+ verify(t, r10, 12, sumN(10)+42+77)
}
func TestLink3(t *testing.T) {
- var r Ring;
- n := 1;
+ var r Ring
+ n := 1
for i := 1; i < 100; i++ {
- n += i;
- verify(t, r.Link(New(i)), n, -1);
+ n += i
+ verify(t, r.Link(New(i)), n, -1)
}
}
func TestUnlink(t *testing.T) {
- r10 := makeN(10);
- s10 := r10.Move(6);
+ r10 := makeN(10)
+ s10 := r10.Move(6)
- sum10 := sumN(10);
+ sum10 := sumN(10)
- verify(t, r10, 10, sum10);
- verify(t, s10, 10, sum10);
+ verify(t, r10, 10, sum10)
+ verify(t, s10, 10, sum10)
- r0 := r10.Unlink(0);
- verify(t, r0, 0, 0);
+ r0 := r10.Unlink(0)
+ verify(t, r0, 0, 0)
- r1 := r10.Unlink(1);
- verify(t, r1, 1, 2);
- verify(t, r10, 9, sum10-2);
+ r1 := r10.Unlink(1)
+ verify(t, r1, 1, 2)
+ verify(t, r10, 9, sum10-2)
- r9 := r10.Unlink(9);
- verify(t, r9, 9, sum10-2);
- verify(t, r10, 9, sum10-2);
+ r9 := r10.Unlink(9)
+ verify(t, r9, 9, sum10-2)
+ verify(t, r10, 9, sum10-2)
}
func TestLinkUnlink(t *testing.T) {
for i := 1; i < 4; i++ {
- ri := New(i);
+ ri := New(i)
for j := 0; j < i; j++ {
- rj := ri.Unlink(j);
- verify(t, rj, j, -1);
- verify(t, ri, i-j, -1);
- ri.Link(rj);
- verify(t, ri, i, -1);
+ rj := ri.Unlink(j)
+ verify(t, rj, j, -1)
+ verify(t, ri, i-j, -1)
+ ri.Link(rj)
+ verify(t, ri, i, -1)
}
}
}
diff --git a/src/pkg/container/vector/intvector.go b/src/pkg/container/vector/intvector.go
index 43f8ff8081..1ec4b85a9b 100644
--- a/src/pkg/container/vector/intvector.go
+++ b/src/pkg/container/vector/intvector.go
@@ -7,7 +7,7 @@ package vector
// IntVector is a specialization of Vector that hides the wrapping of Elements around ints.
type IntVector struct {
- Vector;
+ Vector
}
@@ -17,40 +17,40 @@ type IntVector struct {
// Resize adds 0 elements. The capacity parameter is ignored unless the
// new length or capacity is longer that the current capacity.
func (p *IntVector) Resize(length, capacity int) *IntVector {
- i := p.Len();
- p.Vector.Resize(length, capacity);
+ i := p.Len()
+ p.Vector.Resize(length, capacity)
for a := p.a; i < len(a); i++ {
a[i] = 0
}
- return p;
+ return p
}
// At returns the i'th element of the vector.
-func (p *IntVector) At(i int) int { return p.Vector.At(i).(int) }
+func (p *IntVector) At(i int) int { return p.Vector.At(i).(int) }
// Set sets the i'th element of the vector to value x.
-func (p *IntVector) Set(i int, x int) { p.a[i] = x }
+func (p *IntVector) Set(i int, x int) { p.a[i] = x }
// Last returns the element in the vector of highest index.
-func (p *IntVector) Last() int { return p.Vector.Last().(int) }
+func (p *IntVector) Last() int { return p.Vector.Last().(int) }
// Data returns all the elements as a slice.
func (p *IntVector) Data() []int {
- arr := make([]int, p.Len());
+ arr := make([]int, p.Len())
for i, v := range p.a {
arr[i] = v.(int)
}
- return arr;
+ return arr
}
// Insert inserts into the vector an element of value x before
// the current element at index i.
-func (p *IntVector) Insert(i int, x int) { p.Vector.Insert(i, x) }
+func (p *IntVector) Insert(i int, x int) { p.Vector.Insert(i, x) }
// InsertVector inserts into the vector the contents of the Vector
@@ -68,11 +68,11 @@ func (p *IntVector) Slice(i, j int) *IntVector {
// Push appends x to the end of the vector.
-func (p *IntVector) Push(x int) { p.Vector.Push(x) }
+func (p *IntVector) Push(x int) { p.Vector.Push(x) }
// Pop deletes and returns the last element of the vector.
-func (p *IntVector) Pop() int { return p.Vector.Pop().(int) }
+func (p *IntVector) Pop() int { return p.Vector.Pop().(int) }
// AppendVector appends the entire IntVector x to the end of this vector.
@@ -83,7 +83,7 @@ func (p *IntVector) AppendVector(x *IntVector) {
// sort.Interface support
// Less returns a boolean denoting whether the i'th element is less than the j'th element.
-func (p *IntVector) Less(i, j int) bool { return p.At(i) < p.At(j) }
+func (p *IntVector) Less(i, j int) bool { return p.At(i) < p.At(j) }
// Iterate over all elements; driver for range
@@ -91,13 +91,13 @@ func (p *IntVector) iterate(c chan<- int) {
for _, v := range p.a {
c <- v.(int)
}
- close(c);
+ close(c)
}
// Channel iterator for range.
func (p *IntVector) Iter() <-chan int {
- c := make(chan int);
- go p.iterate(c);
- return c;
+ c := make(chan int)
+ go p.iterate(c)
+ return c
}
diff --git a/src/pkg/container/vector/stringvector.go b/src/pkg/container/vector/stringvector.go
index 93a4197a58..821a7a101d 100644
--- a/src/pkg/container/vector/stringvector.go
+++ b/src/pkg/container/vector/stringvector.go
@@ -6,7 +6,7 @@ package vector
// StringVector is a specialization of Vector that hides the wrapping of Elements around strings.
type StringVector struct {
- Vector;
+ Vector
}
@@ -16,34 +16,34 @@ type StringVector struct {
// Resize adds "" elements. The capacity parameter is ignored unless the
// new length or capacity is longer that the current capacity.
func (p *StringVector) Resize(length, capacity int) *StringVector {
- i := p.Len();
- p.Vector.Resize(length, capacity);
+ i := p.Len()
+ p.Vector.Resize(length, capacity)
for a := p.a; i < len(a); i++ {
a[i] = ""
}
- return p;
+ return p
}
// At returns the i'th element of the vector.
-func (p *StringVector) At(i int) string { return p.Vector.At(i).(string) }
+func (p *StringVector) At(i int) string { return p.Vector.At(i).(string) }
// Set sets the i'th element of the vector to value x.
-func (p *StringVector) Set(i int, x string) { p.a[i] = x }
+func (p *StringVector) Set(i int, x string) { p.a[i] = x }
// Last returns the element in the vector of highest index.
-func (p *StringVector) Last() string { return p.Vector.Last().(string) }
+func (p *StringVector) Last() string { return p.Vector.Last().(string) }
// Data returns all the elements as a slice.
func (p *StringVector) Data() []string {
- arr := make([]string, p.Len());
+ arr := make([]string, p.Len())
for i, v := range p.a {
arr[i] = v.(string)
}
- return arr;
+ return arr
}
@@ -69,11 +69,11 @@ func (p *StringVector) Slice(i, j int) *StringVector {
// Push appends x to the end of the vector.
-func (p *StringVector) Push(x string) { p.Vector.Push(x) }
+func (p *StringVector) Push(x string) { p.Vector.Push(x) }
// Pop deletes and returns the last element of the vector.
-func (p *StringVector) Pop() string { return p.Vector.Pop().(string) }
+func (p *StringVector) Pop() string { return p.Vector.Pop().(string) }
// AppendVector appends the entire StringVector x to the end of this vector.
@@ -84,7 +84,7 @@ func (p *StringVector) AppendVector(x *StringVector) {
// sort.Interface support
// Less returns a boolean denoting whether the i'th element is less than the j'th element.
-func (p *StringVector) Less(i, j int) bool { return p.At(i) < p.At(j) }
+func (p *StringVector) Less(i, j int) bool { return p.At(i) < p.At(j) }
// Iterate over all elements; driver for range
@@ -92,13 +92,13 @@ func (p *StringVector) iterate(c chan<- string) {
for _, v := range p.a {
c <- v.(string)
}
- close(c);
+ close(c)
}
// Channel iterator for range.
func (p *StringVector) Iter() <-chan string {
- c := make(chan string);
- go p.iterate(c);
- return c;
+ c := make(chan string)
+ go p.iterate(c)
+ return c
}
diff --git a/src/pkg/container/vector/vector.go b/src/pkg/container/vector/vector.go
index 0408490bea..ed1845b27c 100644
--- a/src/pkg/container/vector/vector.go
+++ b/src/pkg/container/vector/vector.go
@@ -9,8 +9,8 @@ package vector
// Vector is the container itself.
// The zero value for Vector is an empty vector ready to use.
type Vector struct {
- a []interface{};
- bootstrap [8]interface{};
+ a []interface{}
+ bootstrap [8]interface{}
}
@@ -21,31 +21,31 @@ func (p *Vector) realloc(length, capacity int) (b []interface{}) {
} else {
b = make([]interface{}, length, capacity)
}
- copy(b, p.a);
- p.a = b;
- return;
+ copy(b, p.a)
+ p.a = b
+ return
}
// Insert n elements at position i.
func (p *Vector) expand(i, n int) {
- a := p.a;
+ a := p.a
// make sure we have enough space
- len0 := len(a);
- len1 := len0 + n;
+ len0 := len(a)
+ len1 := len0 + n
if len1 <= cap(a) {
// enough space - just expand
a = a[0:len1]
} else {
// not enough space - double capacity
- capb := cap(a) * 2;
+ capb := cap(a) * 2
if capb < len1 {
// still not enough - use required length
capb = len1
}
// capb >= len1
- a = p.realloc(len1, capb);
+ a = p.realloc(len1, capb)
}
// make a hole
@@ -53,7 +53,7 @@ func (p *Vector) expand(i, n int) {
a[j+n] = a[j]
}
- p.a = a;
+ p.a = a
}
@@ -64,7 +64,7 @@ func (p *Vector) expand(i, n int) {
// new length or capacity is longer that the current capacity. The resized
// vector's capacity may be larger than the requested capacity.
func (p *Vector) Resize(length, capacity int) *Vector {
- a := p.a;
+ a := p.a
if length > cap(a) || capacity > cap(a) {
// not enough space or larger capacity requested explicitly
@@ -76,91 +76,91 @@ func (p *Vector) Resize(length, capacity int) *Vector {
}
}
- p.a = a[0:length];
- return p;
+ p.a = a[0:length]
+ return p
}
// Len returns the number of elements in the vector.
-func (p *Vector) Len() int { return len(p.a) }
+func (p *Vector) Len() int { return len(p.a) }
// Cap returns the capacity of the vector; that is, the
// maximum length the vector can grow without resizing.
-func (p *Vector) Cap() int { return cap(p.a) }
+func (p *Vector) Cap() int { return cap(p.a) }
// At returns the i'th element of the vector.
-func (p *Vector) At(i int) interface{} { return p.a[i] }
+func (p *Vector) At(i int) interface{} { return p.a[i] }
// Set sets the i'th element of the vector to value x.
-func (p *Vector) Set(i int, x interface{}) { p.a[i] = x }
+func (p *Vector) Set(i int, x interface{}) { p.a[i] = x }
// Last returns the element in the vector of highest index.
-func (p *Vector) Last() interface{} { return p.a[len(p.a)-1] }
+func (p *Vector) Last() interface{} { return p.a[len(p.a)-1] }
// Data returns all the elements as a slice.
func (p *Vector) Data() []interface{} {
- arr := make([]interface{}, p.Len());
+ arr := make([]interface{}, p.Len())
for i, v := range p.a {
arr[i] = v
}
- return arr;
+ return arr
}
// Insert inserts into the vector an element of value x before
// the current element at index i.
func (p *Vector) Insert(i int, x interface{}) {
- p.expand(i, 1);
- p.a[i] = x;
+ p.expand(i, 1)
+ p.a[i] = x
}
// Delete deletes the i'th element of the vector. The gap is closed so the old
// element at index i+1 has index i afterwards.
func (p *Vector) Delete(i int) {
- a := p.a;
- n := len(a);
+ a := p.a
+ n := len(a)
- copy(a[i:n-1], a[i+1:n]);
- a[n-1] = nil; // support GC, nil out entry
- p.a = a[0 : n-1];
+ copy(a[i:n-1], a[i+1:n])
+ a[n-1] = nil // support GC, nil out entry
+ p.a = a[0 : n-1]
}
// InsertVector inserts into the vector the contents of the Vector
// x such that the 0th element of x appears at index i after insertion.
func (p *Vector) InsertVector(i int, x *Vector) {
- p.expand(i, len(x.a));
- copy(p.a[i:i+len(x.a)], x.a);
+ p.expand(i, len(x.a))
+ copy(p.a[i:i+len(x.a)], x.a)
}
// Cut deletes elements i through j-1, inclusive.
func (p *Vector) Cut(i, j int) {
- a := p.a;
- n := len(a);
- m := n - (j - i);
+ a := p.a
+ n := len(a)
+ m := n - (j - i)
- copy(a[i:m], a[j:n]);
+ copy(a[i:m], a[j:n])
for k := m; k < n; k++ {
- a[k] = nil // support GC, nil out entries
+ a[k] = nil // support GC, nil out entries
}
- p.a = a[0:m];
+ p.a = a[0:m]
}
// Slice returns a new Vector by slicing the old one to extract slice [i:j].
// The elements are copied. The original vector is unchanged.
func (p *Vector) Slice(i, j int) *Vector {
- s := new(Vector).Resize(j-i, 0); // will fail in Init() if j < i
- copy(s.a, p.a[i:j]);
- return s;
+ s := new(Vector).Resize(j-i, 0) // will fail in Init() if j < i
+ copy(s.a, p.a[i:j])
+ return s
}
@@ -168,7 +168,7 @@ func (p *Vector) Slice(i, j int) *Vector {
// The function should not change the indexing of the vector underfoot.
func (p *Vector) Do(f func(elem interface{})) {
for i := 0; i < len(p.a); i++ {
- f(p.a[i]) // not too safe if f changes the Vector
+ f(p.a[i]) // not too safe if f changes the Vector
}
}
@@ -176,39 +176,39 @@ func (p *Vector) Do(f func(elem interface{})) {
// Convenience wrappers
// Push appends x to the end of the vector.
-func (p *Vector) Push(x interface{}) { p.Insert(len(p.a), x) }
+func (p *Vector) Push(x interface{}) { p.Insert(len(p.a), x) }
// Pop deletes the last element of the vector.
func (p *Vector) Pop() interface{} {
- i := len(p.a) - 1;
- x := p.a[i];
- p.a[i] = nil; // support GC, nil out entry
- p.a = p.a[0:i];
- return x;
+ i := len(p.a) - 1
+ x := p.a[i]
+ p.a[i] = nil // support GC, nil out entry
+ p.a = p.a[0:i]
+ return x
}
// AppendVector appends the entire Vector x to the end of this vector.
-func (p *Vector) AppendVector(x *Vector) { p.InsertVector(len(p.a), x) }
+func (p *Vector) AppendVector(x *Vector) { p.InsertVector(len(p.a), x) }
// Partial sort.Interface support
// LessInterface provides partial support of the sort.Interface.
type LessInterface interface {
- Less(y interface{}) bool;
+ Less(y interface{}) bool
}
// Less returns a boolean denoting whether the i'th element is less than the j'th element.
-func (p *Vector) Less(i, j int) bool { return p.a[i].(LessInterface).Less(p.a[j]) }
+func (p *Vector) Less(i, j int) bool { return p.a[i].(LessInterface).Less(p.a[j]) }
// Swap exchanges the elements at indexes i and j.
func (p *Vector) Swap(i, j int) {
- a := p.a;
- a[i], a[j] = a[j], a[i];
+ a := p.a
+ a[i], a[j] = a[j], a[i]
}
@@ -217,13 +217,13 @@ func (p *Vector) iterate(c chan<- interface{}) {
for _, v := range p.a {
c <- v
}
- close(c);
+ close(c)
}
// Channel iterator for range.
func (p *Vector) Iter() <-chan interface{} {
- c := make(chan interface{});
- go p.iterate(c);
- return c;
+ c := make(chan interface{})
+ go p.iterate(c)
+ return c
}
diff --git a/src/pkg/container/vector/vector_test.go b/src/pkg/container/vector/vector_test.go
index f187f72188..755ba7cad0 100644
--- a/src/pkg/container/vector/vector_test.go
+++ b/src/pkg/container/vector/vector_test.go
@@ -10,7 +10,7 @@ import "fmt"
func TestZeroLen(t *testing.T) {
- a := new(Vector);
+ a := new(Vector)
if a.Len() != 0 {
t.Errorf("B) expected 0, got %d", a.Len())
}
@@ -18,8 +18,8 @@ func TestZeroLen(t *testing.T) {
type VectorInterface interface {
- Len() int;
- Cap() int;
+ Len() int
+ Cap() int
}
@@ -34,27 +34,27 @@ func checkSize(t *testing.T, v VectorInterface, len, cap int) {
func TestResize(t *testing.T) {
- var a Vector;
- checkSize(t, &a, 0, 0);
- checkSize(t, a.Resize(0, 5), 0, 5);
- checkSize(t, a.Resize(1, 0), 1, 5);
- checkSize(t, a.Resize(10, 0), 10, 10);
- checkSize(t, a.Resize(5, 0), 5, 10);
- checkSize(t, a.Resize(3, 8), 3, 10);
- checkSize(t, a.Resize(0, 100), 0, 100);
- checkSize(t, a.Resize(11, 100), 11, 100);
+ var a Vector
+ checkSize(t, &a, 0, 0)
+ checkSize(t, a.Resize(0, 5), 0, 5)
+ checkSize(t, a.Resize(1, 0), 1, 5)
+ checkSize(t, a.Resize(10, 0), 10, 10)
+ checkSize(t, a.Resize(5, 0), 5, 10)
+ checkSize(t, a.Resize(3, 8), 3, 10)
+ checkSize(t, a.Resize(0, 100), 0, 100)
+ checkSize(t, a.Resize(11, 100), 11, 100)
}
func TestIntResize(t *testing.T) {
- var a IntVector;
- checkSize(t, &a, 0, 0);
- a.Push(1);
- a.Push(2);
- a.Push(3);
- a.Push(4);
- checkSize(t, &a, 4, 4);
- checkSize(t, a.Resize(10, 0), 10, 10);
+ var a IntVector
+ checkSize(t, &a, 0, 0)
+ a.Push(1)
+ a.Push(2)
+ a.Push(3)
+ a.Push(4)
+ checkSize(t, &a, 4, 4)
+ checkSize(t, a.Resize(10, 0), 10, 10)
for i := 4; i < a.Len(); i++ {
if a.At(i) != 0 {
t.Errorf("expected a.At(%d) == 0; found %d", i, a.At(i))
@@ -64,14 +64,14 @@ func TestIntResize(t *testing.T) {
func TestStringResize(t *testing.T) {
- var a StringVector;
- checkSize(t, &a, 0, 0);
- a.Push("1");
- a.Push("2");
- a.Push("3");
- a.Push("4");
- checkSize(t, &a, 4, 4);
- checkSize(t, a.Resize(10, 0), 10, 10);
+ var a StringVector
+ checkSize(t, &a, 0, 0)
+ a.Push("1")
+ a.Push("2")
+ a.Push("3")
+ a.Push("4")
+ checkSize(t, &a, 4, 4)
+ checkSize(t, a.Resize(10, 0), 10, 10)
for i := 4; i < a.Len(); i++ {
if a.At(i) != "" {
t.Errorf("expected a.At(%d) == "+"; found %s", i, a.At(i))
@@ -95,25 +95,25 @@ func checkNil(t *testing.T, a *Vector, i int) {
func TestTrailingElements(t *testing.T) {
- var a Vector;
+ var a Vector
for i := 0; i < 10; i++ {
a.Push(i)
}
- checkNil(t, &a, 10);
- checkSize(t, &a, 10, 16);
- checkSize(t, a.Resize(5, 0), 5, 16);
- checkSize(t, a.Resize(10, 0), 10, 16);
- checkNil(t, &a, 5);
+ checkNil(t, &a, 10)
+ checkSize(t, &a, 10, 16)
+ checkSize(t, a.Resize(5, 0), 5, 16)
+ checkSize(t, a.Resize(10, 0), 10, 16)
+ checkNil(t, &a, 5)
}
-func val(i int) int { return i*991 - 1234 }
+func val(i int) int { return i*991 - 1234 }
func TestAccess(t *testing.T) {
- const n = 100;
- var a Vector;
- a.Resize(n, 0);
+ const n = 100
+ var a Vector
+ a.Resize(n, 0)
for i := 0; i < n; i++ {
a.Set(i, val(i))
}
@@ -126,14 +126,14 @@ func TestAccess(t *testing.T) {
func TestInsertDeleteClear(t *testing.T) {
- const n = 100;
- var a Vector;
+ const n = 100
+ var a Vector
for i := 0; i < n; i++ {
if a.Len() != i {
t.Errorf("A) wrong len %d (expected %d)", a.Len(), i)
}
- a.Insert(0, val(i));
+ a.Insert(0, val(i))
if a.Last().(int) != val(0) {
t.Error("B")
}
@@ -145,7 +145,7 @@ func TestInsertDeleteClear(t *testing.T) {
if a.At(0).(int) != val(i) {
t.Error("D")
}
- a.Delete(0);
+ a.Delete(0)
if a.Len() != i {
t.Errorf("E) wrong len %d (expected %d)", a.Len(), i)
}
@@ -155,7 +155,7 @@ func TestInsertDeleteClear(t *testing.T) {
t.Errorf("F) wrong len %d (expected 0)", a.Len())
}
for i := 0; i < n; i++ {
- a.Push(val(i));
+ a.Push(val(i))
if a.Len() != i+1 {
t.Errorf("G) wrong len %d (expected %d)", a.Len(), i+1)
}
@@ -163,17 +163,17 @@ func TestInsertDeleteClear(t *testing.T) {
t.Error("H")
}
}
- a.Resize(0, 0);
+ a.Resize(0, 0)
if a.Len() != 0 {
t.Errorf("I wrong len %d (expected 0)", a.Len())
}
- const m = 5;
+ const m = 5
for j := 0; j < m; j++ {
- a.Push(j);
+ a.Push(j)
for i := 0; i < n; i++ {
- x := val(i);
- a.Push(x);
+ x := val(i)
+ a.Push(x)
if a.Pop().(int) != x {
t.Error("J")
}
@@ -195,7 +195,7 @@ func verify_slice(t *testing.T, x *Vector, elt, i, j int) {
}
}
- s := x.Slice(i, j);
+ s := x.Slice(i, j)
for k, n := 0, j-i; k < n; k++ {
if s.At(k).(int) != elt {
t.Errorf("N) wrong [%d] element %d (expected %d)", k, x.At(k).(int), elt)
@@ -205,54 +205,54 @@ func verify_slice(t *testing.T, x *Vector, elt, i, j int) {
func verify_pattern(t *testing.T, x *Vector, a, b, c int) {
- n := a + b + c;
+ n := a + b + c
if x.Len() != n {
t.Errorf("O) wrong len %d (expected %d)", x.Len(), n)
}
- verify_slice(t, x, 0, 0, a);
- verify_slice(t, x, 1, a, a+b);
- verify_slice(t, x, 0, a+b, n);
+ verify_slice(t, x, 0, 0, a)
+ verify_slice(t, x, 1, a, a+b)
+ verify_slice(t, x, 0, a+b, n)
}
func make_vector(elt, len int) *Vector {
- x := new(Vector).Resize(len, 0);
+ x := new(Vector).Resize(len, 0)
for i := 0; i < len; i++ {
x.Set(i, elt)
}
- return x;
+ return x
}
func TestInsertVector(t *testing.T) {
// 1
- a := make_vector(0, 0);
- b := make_vector(1, 10);
- a.InsertVector(0, b);
- verify_pattern(t, a, 0, 10, 0);
+ a := make_vector(0, 0)
+ b := make_vector(1, 10)
+ a.InsertVector(0, b)
+ verify_pattern(t, a, 0, 10, 0)
// 2
- a = make_vector(0, 10);
- b = make_vector(1, 0);
- a.InsertVector(5, b);
- verify_pattern(t, a, 5, 0, 5);
+ a = make_vector(0, 10)
+ b = make_vector(1, 0)
+ a.InsertVector(5, b)
+ verify_pattern(t, a, 5, 0, 5)
// 3
- a = make_vector(0, 10);
- b = make_vector(1, 3);
- a.InsertVector(3, b);
- verify_pattern(t, a, 3, 3, 7);
+ a = make_vector(0, 10)
+ b = make_vector(1, 3)
+ a.InsertVector(3, b)
+ verify_pattern(t, a, 3, 3, 7)
// 4
- a = make_vector(0, 10);
- b = make_vector(1, 1000);
- a.InsertVector(8, b);
- verify_pattern(t, a, 8, 1000, 2);
+ a = make_vector(0, 10)
+ b = make_vector(1, 1000)
+ a.InsertVector(8, b)
+ verify_pattern(t, a, 8, 1000, 2)
}
// This also tests IntVector and StringVector
func TestSorting(t *testing.T) {
- const n = 100;
+ const n = 100
- a := new(IntVector).Resize(n, 0);
+ a := new(IntVector).Resize(n, 0)
for i := n - 1; i >= 0; i-- {
a.Set(i, n-1-i)
}
@@ -260,7 +260,7 @@ func TestSorting(t *testing.T) {
t.Error("int vector not sorted")
}
- b := new(StringVector).Resize(n, 0);
+ b := new(StringVector).Resize(n, 0)
for i := n - 1; i >= 0; i-- {
b.Set(i, fmt.Sprint(n-1-i))
}
@@ -271,20 +271,20 @@ func TestSorting(t *testing.T) {
func TestDo(t *testing.T) {
- const n = 25;
- const salt = 17;
- a := new(IntVector).Resize(n, 0);
+ const n = 25
+ const salt = 17
+ a := new(IntVector).Resize(n, 0)
for i := 0; i < n; i++ {
a.Set(i, salt*i)
}
- count := 0;
+ count := 0
a.Do(func(e interface{}) {
- i := e.(int);
+ i := e.(int)
if i != count*salt {
t.Error("value at", count, "should be", count*salt, "not", i)
}
- count++;
- });
+ count++
+ })
if count != n {
t.Error("should visit", n, "values; did visit", count)
}
@@ -292,17 +292,17 @@ func TestDo(t *testing.T) {
func TestIter(t *testing.T) {
- const Len = 100;
- x := new(Vector).Resize(Len, 0);
+ const Len = 100
+ x := new(Vector).Resize(Len, 0)
for i := 0; i < Len; i++ {
x.Set(i, i*i)
}
- i := 0;
+ i := 0
for v := range x.Iter() {
if v.(int) != i*i {
t.Error("Iter expected", i*i, "got", v.(int))
}
- i++;
+ i++
}
if i != Len {
t.Error("Iter stopped at", i, "not", Len)
diff --git a/src/pkg/crypto/aes/aes_test.go b/src/pkg/crypto/aes/aes_test.go
index 39933a8242..1629a33ed7 100644
--- a/src/pkg/crypto/aes/aes_test.go
+++ b/src/pkg/crypto/aes/aes_test.go
@@ -5,7 +5,7 @@
package aes
import (
- "testing";
+ "testing"
)
// See const.go for overview of math here.
@@ -13,12 +13,12 @@ import (
// Test that powx is initialized correctly.
// (Can adapt this code to generate it too.)
func TestPowx(t *testing.T) {
- p := 1;
+ p := 1
for i := 0; i < len(powx); i++ {
if powx[i] != byte(p) {
t.Errorf("powx[%d] = %#x, want %#x", i, powx[i], p)
}
- p <<= 1;
+ p <<= 1
if p&0x100 != 0 {
p ^= poly
}
@@ -27,25 +27,25 @@ func TestPowx(t *testing.T) {
// Multiply b and c as GF(2) polynomials modulo poly
func mul(b, c uint32) uint32 {
- i := b;
- j := c;
- s := uint32(0);
+ i := b
+ j := c
+ s := uint32(0)
for k := uint32(1); k < 0x100 && j != 0; k <<= 1 {
// Invariant: k == 1<<n, i == b * xⁿ
if j&k != 0 {
// s += i in GF(2); xor in binary
- s ^= i;
- j ^= k; // turn off bit to end loop early
+ s ^= i
+ j ^= k // turn off bit to end loop early
}
// i *= x in GF(2) modulo the polynomial
- i <<= 1;
+ i <<= 1
if i&0x100 != 0 {
i ^= poly
}
}
- return s;
+ return s
}
// Test all mul inputs against bit-by-bit n² algorithm.
@@ -53,7 +53,7 @@ func TestMul(t *testing.T) {
for i := uint32(0); i < 256; i++ {
for j := uint32(0); j < 256; j++ {
// Multiply i, j bit by bit.
- s := uint8(0);
+ s := uint8(0)
for k := uint(0); k < 8; k++ {
for l := uint(0); l < 8; l++ {
if i&(1<<k) != 0 && j&(1<<l) != 0 {
@@ -87,15 +87,15 @@ func TestSboxes(t *testing.T) {
// (Can adapt this code to generate them too.)
func TestTe(t *testing.T) {
for i := 0; i < 256; i++ {
- s := uint32(sbox0[i]);
- s2 := mul(s, 2);
- s3 := mul(s, 3);
- w := s2<<24 | s<<16 | s<<8 | s3;
+ s := uint32(sbox0[i])
+ s2 := mul(s, 2)
+ s3 := mul(s, 3)
+ w := s2<<24 | s<<16 | s<<8 | s3
for j := 0; j < 4; j++ {
if x := te[j][i]; x != w {
t.Fatalf("te[%d][%d] = %#x, want %#x", j, i, x, w)
}
- w = w<<24 | w>>8;
+ w = w<<24 | w>>8
}
}
}
@@ -104,17 +104,17 @@ func TestTe(t *testing.T) {
// (Can adapt this code to generate them too.)
func TestTd(t *testing.T) {
for i := 0; i < 256; i++ {
- s := uint32(sbox1[i]);
- s9 := mul(s, 0x9);
- sb := mul(s, 0xb);
- sd := mul(s, 0xd);
- se := mul(s, 0xe);
- w := se<<24 | s9<<16 | sd<<8 | sb;
+ s := uint32(sbox1[i])
+ s9 := mul(s, 0x9)
+ sb := mul(s, 0xb)
+ sd := mul(s, 0xd)
+ se := mul(s, 0xe)
+ w := se<<24 | s9<<16 | sd<<8 | sb
for j := 0; j < 4; j++ {
if x := td[j][i]; x != w {
t.Fatalf("td[%d][%d] = %#x, want %#x", j, i, x, w)
}
- w = w<<24 | w>>8;
+ w = w<<24 | w>>8
}
}
}
@@ -124,9 +124,9 @@ func TestTd(t *testing.T) {
// Appendix A of FIPS 197: Key expansion examples
type KeyTest struct {
- key []byte;
- enc []uint32;
- dec []uint32; // decryption expansion; not in FIPS 197, computed from C implementation.
+ key []byte
+ enc []uint32
+ dec []uint32 // decryption expansion; not in FIPS 197, computed from C implementation.
}
var keyTests = []KeyTest{
@@ -214,23 +214,23 @@ var keyTests = []KeyTest{
func TestExpandKey(t *testing.T) {
L:
for i, tt := range keyTests {
- enc := make([]uint32, len(tt.enc));
- var dec []uint32;
+ enc := make([]uint32, len(tt.enc))
+ var dec []uint32
if tt.dec != nil {
dec = make([]uint32, len(tt.dec))
}
- expandKey(tt.key, enc, dec);
+ expandKey(tt.key, enc, dec)
for j, v := range enc {
if v != tt.enc[j] {
- t.Errorf("key %d: enc[%d] = %#x, want %#x", i, j, v, tt.enc[j]);
- continue L;
+ t.Errorf("key %d: enc[%d] = %#x, want %#x", i, j, v, tt.enc[j])
+ continue L
}
}
if dec != nil {
for j, v := range dec {
if v != tt.dec[j] {
- t.Errorf("key %d: dec[%d] = %#x, want %#x", i, j, v, tt.dec[j]);
- continue L;
+ t.Errorf("key %d: dec[%d] = %#x, want %#x", i, j, v, tt.dec[j])
+ continue L
}
}
}
@@ -239,9 +239,9 @@ L:
// Appendix B, C of FIPS 197: Cipher examples, Example vectors.
type CryptTest struct {
- key []byte;
- in []byte;
- out []byte;
+ key []byte
+ in []byte
+ out []byte
}
var encryptTests = []CryptTest{
@@ -278,16 +278,16 @@ var encryptTests = []CryptTest{
// Test encryptBlock against FIPS 197 examples.
func TestEncryptBlock(t *testing.T) {
for i, tt := range encryptTests {
- n := len(tt.key) + 28;
- enc := make([]uint32, n);
- dec := make([]uint32, n);
- expandKey(tt.key, enc, dec);
- out := make([]byte, len(tt.in));
- encryptBlock(enc, tt.in, out);
+ n := len(tt.key) + 28
+ enc := make([]uint32, n)
+ dec := make([]uint32, n)
+ expandKey(tt.key, enc, dec)
+ out := make([]byte, len(tt.in))
+ encryptBlock(enc, tt.in, out)
for j, v := range out {
if v != tt.out[j] {
- t.Errorf("encryptBlock %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j]);
- break;
+ t.Errorf("encryptBlock %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j])
+ break
}
}
}
@@ -296,16 +296,16 @@ func TestEncryptBlock(t *testing.T) {
// Test decryptBlock against FIPS 197 examples.
func TestDecryptBlock(t *testing.T) {
for i, tt := range encryptTests {
- n := len(tt.key) + 28;
- enc := make([]uint32, n);
- dec := make([]uint32, n);
- expandKey(tt.key, enc, dec);
- plain := make([]byte, len(tt.in));
- decryptBlock(dec, tt.out, plain);
+ n := len(tt.key) + 28
+ enc := make([]uint32, n)
+ dec := make([]uint32, n)
+ expandKey(tt.key, enc, dec)
+ plain := make([]byte, len(tt.in))
+ decryptBlock(dec, tt.out, plain)
for j, v := range plain {
if v != tt.in[j] {
- t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j]);
- break;
+ t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j])
+ break
}
}
}
@@ -314,17 +314,17 @@ func TestDecryptBlock(t *testing.T) {
// Test Cipher Encrypt method against FIPS 197 examples.
func TestCipherEncrypt(t *testing.T) {
for i, tt := range encryptTests {
- c, err := NewCipher(tt.key);
+ c, err := NewCipher(tt.key)
if err != nil {
- t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err);
- continue;
+ t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err)
+ continue
}
- out := make([]byte, len(tt.in));
- c.Encrypt(tt.in, out);
+ out := make([]byte, len(tt.in))
+ c.Encrypt(tt.in, out)
for j, v := range out {
if v != tt.out[j] {
- t.Errorf("Cipher.Encrypt %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j]);
- break;
+ t.Errorf("Cipher.Encrypt %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j])
+ break
}
}
}
@@ -333,17 +333,17 @@ func TestCipherEncrypt(t *testing.T) {
// Test Cipher Decrypt against FIPS 197 examples.
func TestCipherDecrypt(t *testing.T) {
for i, tt := range encryptTests {
- c, err := NewCipher(tt.key);
+ c, err := NewCipher(tt.key)
if err != nil {
- t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err);
- continue;
+ t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err)
+ continue
}
- plain := make([]byte, len(tt.in));
- c.Decrypt(tt.out, plain);
+ plain := make([]byte, len(tt.in))
+ c.Decrypt(tt.out, plain)
for j, v := range plain {
if v != tt.in[j] {
- t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j]);
- break;
+ t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j])
+ break
}
}
}
diff --git a/src/pkg/crypto/aes/block.go b/src/pkg/crypto/aes/block.go
index dbd448f8bb..a502554bd5 100644
--- a/src/pkg/crypto/aes/block.go
+++ b/src/pkg/crypto/aes/block.go
@@ -38,92 +38,92 @@ package aes
// Encrypt one block from src into dst, using the expanded key xk.
func encryptBlock(xk []uint32, src, dst []byte) {
- var s0, s1, s2, s3, t0, t1, t2, t3 uint32;
+ var s0, s1, s2, s3, t0, t1, t2, t3 uint32
- s0 = uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]);
- s1 = uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]);
- s2 = uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11]);
- s3 = uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15]);
+ s0 = uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
+ s1 = uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
+ s2 = uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11])
+ s3 = uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15])
// First round just XORs input with key.
- s0 ^= xk[0];
- s1 ^= xk[1];
- s2 ^= xk[2];
- s3 ^= xk[3];
+ s0 ^= xk[0]
+ s1 ^= xk[1]
+ s2 ^= xk[2]
+ s3 ^= xk[3]
// Middle rounds shuffle using tables.
// Number of rounds is set by length of expanded key.
- nr := len(xk)/4 - 2; // - 2: one above, one more below
- k := 4;
+ nr := len(xk)/4 - 2 // - 2: one above, one more below
+ k := 4
for r := 0; r < nr; r++ {
- t0 = xk[k+0] ^ te[0][s0>>24] ^ te[1][s1>>16&0xff] ^ te[2][s2>>8&0xff] ^ te[3][s3&0xff];
- t1 = xk[k+1] ^ te[0][s1>>24] ^ te[1][s2>>16&0xff] ^ te[2][s3>>8&0xff] ^ te[3][s0&0xff];
- t2 = xk[k+2] ^ te[0][s2>>24] ^ te[1][s3>>16&0xff] ^ te[2][s0>>8&0xff] ^ te[3][s1&0xff];
- t3 = xk[k+3] ^ te[0][s3>>24] ^ te[1][s0>>16&0xff] ^ te[2][s1>>8&0xff] ^ te[3][s2&0xff];
- k += 4;
- s0, s1, s2, s3 = t0, t1, t2, t3;
+ t0 = xk[k+0] ^ te[0][s0>>24] ^ te[1][s1>>16&0xff] ^ te[2][s2>>8&0xff] ^ te[3][s3&0xff]
+ t1 = xk[k+1] ^ te[0][s1>>24] ^ te[1][s2>>16&0xff] ^ te[2][s3>>8&0xff] ^ te[3][s0&0xff]
+ t2 = xk[k+2] ^ te[0][s2>>24] ^ te[1][s3>>16&0xff] ^ te[2][s0>>8&0xff] ^ te[3][s1&0xff]
+ t3 = xk[k+3] ^ te[0][s3>>24] ^ te[1][s0>>16&0xff] ^ te[2][s1>>8&0xff] ^ te[3][s2&0xff]
+ k += 4
+ s0, s1, s2, s3 = t0, t1, t2, t3
}
// Last round uses s-box directly and XORs to produce output.
- s0 = uint32(sbox0[t0>>24])<<24 | uint32(sbox0[t1>>16&0xff])<<16 | uint32(sbox0[t2>>8&0xff])<<8 | uint32(sbox0[t3&0xff]);
- s1 = uint32(sbox0[t1>>24])<<24 | uint32(sbox0[t2>>16&0xff])<<16 | uint32(sbox0[t3>>8&0xff])<<8 | uint32(sbox0[t0&0xff]);
- s2 = uint32(sbox0[t2>>24])<<24 | uint32(sbox0[t3>>16&0xff])<<16 | uint32(sbox0[t0>>8&0xff])<<8 | uint32(sbox0[t1&0xff]);
- s3 = uint32(sbox0[t3>>24])<<24 | uint32(sbox0[t0>>16&0xff])<<16 | uint32(sbox0[t1>>8&0xff])<<8 | uint32(sbox0[t2&0xff]);
+ s0 = uint32(sbox0[t0>>24])<<24 | uint32(sbox0[t1>>16&0xff])<<16 | uint32(sbox0[t2>>8&0xff])<<8 | uint32(sbox0[t3&0xff])
+ s1 = uint32(sbox0[t1>>24])<<24 | uint32(sbox0[t2>>16&0xff])<<16 | uint32(sbox0[t3>>8&0xff])<<8 | uint32(sbox0[t0&0xff])
+ s2 = uint32(sbox0[t2>>24])<<24 | uint32(sbox0[t3>>16&0xff])<<16 | uint32(sbox0[t0>>8&0xff])<<8 | uint32(sbox0[t1&0xff])
+ s3 = uint32(sbox0[t3>>24])<<24 | uint32(sbox0[t0>>16&0xff])<<16 | uint32(sbox0[t1>>8&0xff])<<8 | uint32(sbox0[t2&0xff])
- s0 ^= xk[k+0];
- s1 ^= xk[k+1];
- s2 ^= xk[k+2];
- s3 ^= xk[k+3];
+ s0 ^= xk[k+0]
+ s1 ^= xk[k+1]
+ s2 ^= xk[k+2]
+ s3 ^= xk[k+3]
- dst[0], dst[1], dst[2], dst[3] = byte(s0>>24), byte(s0>>16), byte(s0>>8), byte(s0);
- dst[4], dst[5], dst[6], dst[7] = byte(s1>>24), byte(s1>>16), byte(s1>>8), byte(s1);
- dst[8], dst[9], dst[10], dst[11] = byte(s2>>24), byte(s2>>16), byte(s2>>8), byte(s2);
- dst[12], dst[13], dst[14], dst[15] = byte(s3>>24), byte(s3>>16), byte(s3>>8), byte(s3);
+ dst[0], dst[1], dst[2], dst[3] = byte(s0>>24), byte(s0>>16), byte(s0>>8), byte(s0)
+ dst[4], dst[5], dst[6], dst[7] = byte(s1>>24), byte(s1>>16), byte(s1>>8), byte(s1)
+ dst[8], dst[9], dst[10], dst[11] = byte(s2>>24), byte(s2>>16), byte(s2>>8), byte(s2)
+ dst[12], dst[13], dst[14], dst[15] = byte(s3>>24), byte(s3>>16), byte(s3>>8), byte(s3)
}
// Decrypt one block from src into dst, using the expanded key xk.
func decryptBlock(xk []uint32, src, dst []byte) {
- var s0, s1, s2, s3, t0, t1, t2, t3 uint32;
+ var s0, s1, s2, s3, t0, t1, t2, t3 uint32
- s0 = uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]);
- s1 = uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]);
- s2 = uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11]);
- s3 = uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15]);
+ s0 = uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
+ s1 = uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
+ s2 = uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11])
+ s3 = uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15])
// First round just XORs input with key.
- s0 ^= xk[0];
- s1 ^= xk[1];
- s2 ^= xk[2];
- s3 ^= xk[3];
+ s0 ^= xk[0]
+ s1 ^= xk[1]
+ s2 ^= xk[2]
+ s3 ^= xk[3]
// Middle rounds shuffle using tables.
// Number of rounds is set by length of expanded key.
- nr := len(xk)/4 - 2; // - 2: one above, one more below
- k := 4;
+ nr := len(xk)/4 - 2 // - 2: one above, one more below
+ k := 4
for r := 0; r < nr; r++ {
- t0 = xk[k+0] ^ td[0][s0>>24] ^ td[1][s3>>16&0xff] ^ td[2][s2>>8&0xff] ^ td[3][s1&0xff];
- t1 = xk[k+1] ^ td[0][s1>>24] ^ td[1][s0>>16&0xff] ^ td[2][s3>>8&0xff] ^ td[3][s2&0xff];
- t2 = xk[k+2] ^ td[0][s2>>24] ^ td[1][s1>>16&0xff] ^ td[2][s0>>8&0xff] ^ td[3][s3&0xff];
- t3 = xk[k+3] ^ td[0][s3>>24] ^ td[1][s2>>16&0xff] ^ td[2][s1>>8&0xff] ^ td[3][s0&0xff];
- k += 4;
- s0, s1, s2, s3 = t0, t1, t2, t3;
+ t0 = xk[k+0] ^ td[0][s0>>24] ^ td[1][s3>>16&0xff] ^ td[2][s2>>8&0xff] ^ td[3][s1&0xff]
+ t1 = xk[k+1] ^ td[0][s1>>24] ^ td[1][s0>>16&0xff] ^ td[2][s3>>8&0xff] ^ td[3][s2&0xff]
+ t2 = xk[k+2] ^ td[0][s2>>24] ^ td[1][s1>>16&0xff] ^ td[2][s0>>8&0xff] ^ td[3][s3&0xff]
+ t3 = xk[k+3] ^ td[0][s3>>24] ^ td[1][s2>>16&0xff] ^ td[2][s1>>8&0xff] ^ td[3][s0&0xff]
+ k += 4
+ s0, s1, s2, s3 = t0, t1, t2, t3
}
// Last round uses s-box directly and XORs to produce output.
- s0 = uint32(sbox1[t0>>24])<<24 | uint32(sbox1[t3>>16&0xff])<<16 | uint32(sbox1[t2>>8&0xff])<<8 | uint32(sbox1[t1&0xff]);
- s1 = uint32(sbox1[t1>>24])<<24 | uint32(sbox1[t0>>16&0xff])<<16 | uint32(sbox1[t3>>8&0xff])<<8 | uint32(sbox1[t2&0xff]);
- s2 = uint32(sbox1[t2>>24])<<24 | uint32(sbox1[t1>>16&0xff])<<16 | uint32(sbox1[t0>>8&0xff])<<8 | uint32(sbox1[t3&0xff]);
- s3 = uint32(sbox1[t3>>24])<<24 | uint32(sbox1[t2>>16&0xff])<<16 | uint32(sbox1[t1>>8&0xff])<<8 | uint32(sbox1[t0&0xff]);
+ s0 = uint32(sbox1[t0>>24])<<24 | uint32(sbox1[t3>>16&0xff])<<16 | uint32(sbox1[t2>>8&0xff])<<8 | uint32(sbox1[t1&0xff])
+ s1 = uint32(sbox1[t1>>24])<<24 | uint32(sbox1[t0>>16&0xff])<<16 | uint32(sbox1[t3>>8&0xff])<<8 | uint32(sbox1[t2&0xff])
+ s2 = uint32(sbox1[t2>>24])<<24 | uint32(sbox1[t1>>16&0xff])<<16 | uint32(sbox1[t0>>8&0xff])<<8 | uint32(sbox1[t3&0xff])
+ s3 = uint32(sbox1[t3>>24])<<24 | uint32(sbox1[t2>>16&0xff])<<16 | uint32(sbox1[t1>>8&0xff])<<8 | uint32(sbox1[t0&0xff])
- s0 ^= xk[k+0];
- s1 ^= xk[k+1];
- s2 ^= xk[k+2];
- s3 ^= xk[k+3];
+ s0 ^= xk[k+0]
+ s1 ^= xk[k+1]
+ s2 ^= xk[k+2]
+ s3 ^= xk[k+3]
- dst[0], dst[1], dst[2], dst[3] = byte(s0>>24), byte(s0>>16), byte(s0>>8), byte(s0);
- dst[4], dst[5], dst[6], dst[7] = byte(s1>>24), byte(s1>>16), byte(s1>>8), byte(s1);
- dst[8], dst[9], dst[10], dst[11] = byte(s2>>24), byte(s2>>16), byte(s2>>8), byte(s2);
- dst[12], dst[13], dst[14], dst[15] = byte(s3>>24), byte(s3>>16), byte(s3>>8), byte(s3);
+ dst[0], dst[1], dst[2], dst[3] = byte(s0>>24), byte(s0>>16), byte(s0>>8), byte(s0)
+ dst[4], dst[5], dst[6], dst[7] = byte(s1>>24), byte(s1>>16), byte(s1>>8), byte(s1)
+ dst[8], dst[9], dst[10], dst[11] = byte(s2>>24), byte(s2>>16), byte(s2>>8), byte(s2)
+ dst[12], dst[13], dst[14], dst[15] = byte(s3>>24), byte(s3>>16), byte(s3>>8), byte(s3)
}
// Apply sbox0 to each byte in w.
@@ -135,25 +135,25 @@ func subw(w uint32) uint32 {
}
// Rotate
-func rotw(w uint32) uint32 { return w<<8 | w>>24 }
+func rotw(w uint32) uint32 { return w<<8 | w>>24 }
// Key expansion algorithm. See FIPS-197, Figure 11.
// Their rcon[i] is our powx[i-1] << 24.
func expandKey(key []byte, enc, dec []uint32) {
// Encryption key setup.
- var i int;
- nk := len(key) / 4;
+ var i int
+ nk := len(key) / 4
for i = 0; i < nk; i++ {
enc[i] = uint32(key[4*i])<<24 | uint32(key[4*i+1])<<16 | uint32(key[4*i+2])<<8 | uint32(key[4*i+3])
}
for ; i < len(enc); i++ {
- t := enc[i-1];
+ t := enc[i-1]
if i%nk == 0 {
t = subw(rotw(t)) ^ (uint32(powx[i/nk-1]) << 24)
} else if nk > 6 && i%nk == 4 {
t = subw(t)
}
- enc[i] = enc[i-nk] ^ t;
+ enc[i] = enc[i-nk] ^ t
}
// Derive decryption key from encryption key.
@@ -162,15 +162,15 @@ func expandKey(key []byte, enc, dec []uint32) {
if dec == nil {
return
}
- n := len(enc);
+ n := len(enc)
for i := 0; i < n; i += 4 {
- ei := n - i - 4;
+ ei := n - i - 4
for j := 0; j < 4; j++ {
- x := enc[ei+j];
+ x := enc[ei+j]
if i > 0 && i+4 < n {
x = td[0][sbox0[x>>24]] ^ td[1][sbox0[x>>16&0xff]] ^ td[2][sbox0[x>>8&0xff]] ^ td[3][sbox0[x&0xff]]
}
- dec[i+j] = x;
+ dec[i+j] = x
}
}
}
diff --git a/src/pkg/crypto/aes/cipher.go b/src/pkg/crypto/aes/cipher.go
index 651c2651e0..a7caf55764 100644
--- a/src/pkg/crypto/aes/cipher.go
+++ b/src/pkg/crypto/aes/cipher.go
@@ -5,8 +5,8 @@
package aes
import (
- "os";
- "strconv";
+ "os"
+ "strconv"
)
// The AES block size in bytes.
@@ -14,8 +14,8 @@ const BlockSize = 16
// A Cipher is an instance of AES encryption using a particular key.
type Cipher struct {
- enc []uint32;
- dec []uint32;
+ enc []uint32
+ dec []uint32
}
type KeySizeError int
@@ -29,7 +29,7 @@ func (k KeySizeError) String() string {
// either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256.
func NewCipher(key []byte) (*Cipher, os.Error) {
- k := len(key);
+ k := len(key)
switch k {
default:
return nil, KeySizeError(k)
@@ -37,27 +37,27 @@ func NewCipher(key []byte) (*Cipher, os.Error) {
break
}
- n := k + 28;
- c := &Cipher{make([]uint32, n), make([]uint32, n)};
- expandKey(key, c.enc, c.dec);
- return c, nil;
+ n := k + 28
+ c := &Cipher{make([]uint32, n), make([]uint32, n)}
+ expandKey(key, c.enc, c.dec)
+ return c, nil
}
// BlockSize returns the AES block size, 16 bytes.
// It is necessary to satisfy the Key interface in the
// package "crypto/modes".
-func (c *Cipher) BlockSize() int { return BlockSize }
+func (c *Cipher) BlockSize() int { return BlockSize }
// Encrypt encrypts the 16-byte buffer src using the key k
// and stores the result in dst.
// Note that for amounts of data larger than a block,
// it is not safe to just call Encrypt on successive blocks;
// instead, use an encryption mode like AESCBC (see modes.go).
-func (c *Cipher) Encrypt(src, dst []byte) { encryptBlock(c.enc, src, dst) }
+func (c *Cipher) Encrypt(src, dst []byte) { encryptBlock(c.enc, src, dst) }
// Decrypt decrypts the 16-byte buffer src using the key k
// and stores the result in dst.
-func (c *Cipher) Decrypt(src, dst []byte) { decryptBlock(c.dec, src, dst) }
+func (c *Cipher) Decrypt(src, dst []byte) { decryptBlock(c.dec, src, dst) }
// Reset zeros the key data, so that it will no longer
// appear in the process's memory.
diff --git a/src/pkg/crypto/aes/const.go b/src/pkg/crypto/aes/const.go
index 862be087be..8ddcaff260 100644
--- a/src/pkg/crypto/aes/const.go
+++ b/src/pkg/crypto/aes/const.go
@@ -15,7 +15,7 @@ package aes
// Addition of these binary polynomials corresponds to binary xor.
// Reducing mod poly corresponds to binary xor with poly every
// time a 0x100 bit appears.
-const poly = 1<<8 | 1<<4 | 1<<3 | 1<<1 | 1<<0 // x⁸ + x⁴ + x² + x + 1
+const poly = 1<<8 | 1<<4 | 1<<3 | 1<<1 | 1<<0 // x⁸ + x⁴ + x² + x + 1
// Powers of x mod poly in GF(2).
var powx = [16]byte{
diff --git a/src/pkg/crypto/block/cbc.go b/src/pkg/crypto/block/cbc.go
index ac41ab1fbe..10235f5411 100644
--- a/src/pkg/crypto/block/cbc.go
+++ b/src/pkg/crypto/block/cbc.go
@@ -12,44 +12,44 @@
package block
import (
- "io";
+ "io"
)
type cbcCipher struct {
- c Cipher;
- blockSize int;
- iv []byte;
- tmp []byte;
+ c Cipher
+ blockSize int
+ iv []byte
+ tmp []byte
}
func newCBC(c Cipher, iv []byte) *cbcCipher {
- n := c.BlockSize();
- x := new(cbcCipher);
- x.c = c;
- x.blockSize = n;
- x.iv = copy(iv);
- x.tmp = make([]byte, n);
- return x;
+ n := c.BlockSize()
+ x := new(cbcCipher)
+ x.c = c
+ x.blockSize = n
+ x.iv = copy(iv)
+ x.tmp = make([]byte, n)
+ return x
}
-func (x *cbcCipher) BlockSize() int { return x.blockSize }
+func (x *cbcCipher) BlockSize() int { return x.blockSize }
func (x *cbcCipher) Encrypt(src, dst []byte) {
for i := 0; i < x.blockSize; i++ {
x.iv[i] ^= src[i]
}
- x.c.Encrypt(x.iv, x.iv);
+ x.c.Encrypt(x.iv, x.iv)
for i := 0; i < x.blockSize; i++ {
dst[i] = x.iv[i]
}
}
func (x *cbcCipher) Decrypt(src, dst []byte) {
- x.c.Decrypt(src, x.tmp);
+ x.c.Decrypt(src, x.tmp)
for i := 0; i < x.blockSize; i++ {
- x.tmp[i] ^= x.iv[i];
- x.iv[i] = src[i];
- dst[i] = x.tmp[i];
+ x.tmp[i] ^= x.iv[i]
+ x.iv[i] = src[i]
+ dst[i] = x.tmp[i]
}
}
diff --git a/src/pkg/crypto/block/cbc_aes_test.go b/src/pkg/crypto/block/cbc_aes_test.go
index 02c58fabdd..5531f3ab99 100644
--- a/src/pkg/crypto/block/cbc_aes_test.go
+++ b/src/pkg/crypto/block/cbc_aes_test.go
@@ -11,18 +11,18 @@
package block
import (
- "bytes";
- "crypto/aes";
- "io";
- "testing";
+ "bytes"
+ "crypto/aes"
+ "io"
+ "testing"
)
type cbcTest struct {
- name string;
- key []byte;
- iv []byte;
- in []byte;
- out []byte;
+ name string
+ key []byte
+ iv []byte
+ in []byte
+ out []byte
}
var cbcAESTests = []cbcTest{
@@ -67,28 +67,28 @@ var cbcAESTests = []cbcTest{
func TestCBC_AES(t *testing.T) {
for _, tt := range cbcAESTests {
- test := tt.name;
+ test := tt.name
- c, err := aes.NewCipher(tt.key);
+ c, err := aes.NewCipher(tt.key)
if err != nil {
- t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
- continue;
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
+ continue
}
- var crypt bytes.Buffer;
- w := NewCBCEncrypter(c, tt.iv, &crypt);
- var r io.Reader = bytes.NewBuffer(tt.in);
- n, err := io.Copy(w, r);
+ var crypt bytes.Buffer
+ w := NewCBCEncrypter(c, tt.iv, &crypt)
+ var r io.Reader = bytes.NewBuffer(tt.in)
+ n, err := io.Copy(w, r)
if n != int64(len(tt.in)) || err != nil {
t.Errorf("%s: CBCEncrypter io.Copy = %d, %v want %d, nil", test, n, err, len(tt.in))
} else if d := crypt.Bytes(); !same(tt.out, d) {
t.Errorf("%s: CBCEncrypter\nhave %x\nwant %x", test, d, tt.out)
}
- var plain bytes.Buffer;
- r = NewCBCDecrypter(c, tt.iv, bytes.NewBuffer(tt.out));
- w = &plain;
- n, err = io.Copy(w, r);
+ var plain bytes.Buffer
+ r = NewCBCDecrypter(c, tt.iv, bytes.NewBuffer(tt.out))
+ w = &plain
+ n, err = io.Copy(w, r)
if n != int64(len(tt.out)) || err != nil {
t.Errorf("%s: CBCDecrypter io.Copy = %d, %v want %d, nil", test, n, err, len(tt.out))
} else if d := plain.Bytes(); !same(tt.in, d) {
diff --git a/src/pkg/crypto/block/cfb.go b/src/pkg/crypto/block/cfb.go
index d3c8852d70..82b289ac4c 100644
--- a/src/pkg/crypto/block/cfb.go
+++ b/src/pkg/crypto/block/cfb.go
@@ -13,36 +13,36 @@
package block
import (
- "io";
+ "io"
)
type cfbCipher struct {
- c Cipher;
- blockSize int; // our block size (s/8)
- cipherSize int; // underlying cipher block size
- iv []byte;
- tmp []byte;
+ c Cipher
+ blockSize int // our block size (s/8)
+ cipherSize int // underlying cipher block size
+ iv []byte
+ tmp []byte
}
func newCFB(c Cipher, s int, iv []byte) *cfbCipher {
if s == 0 || s%8 != 0 {
panicln("crypto/block: invalid CFB mode", s)
}
- b := c.BlockSize();
- x := new(cfbCipher);
- x.c = c;
- x.blockSize = s / 8;
- x.cipherSize = b;
- x.iv = copy(iv);
- x.tmp = make([]byte, b);
- return x;
+ b := c.BlockSize()
+ x := new(cfbCipher)
+ x.c = c
+ x.blockSize = s / 8
+ x.cipherSize = b
+ x.iv = copy(iv)
+ x.tmp = make([]byte, b)
+ return x
}
-func (x *cfbCipher) BlockSize() int { return x.blockSize }
+func (x *cfbCipher) BlockSize() int { return x.blockSize }
func (x *cfbCipher) Encrypt(src, dst []byte) {
// Encrypt old IV and xor prefix with src to make dst.
- x.c.Encrypt(x.iv, x.tmp);
+ x.c.Encrypt(x.iv, x.tmp)
for i := 0; i < x.blockSize; i++ {
dst[i] = src[i] ^ x.tmp[i]
}
@@ -51,7 +51,7 @@ func (x *cfbCipher) Encrypt(src, dst []byte) {
for i := 0; i < x.cipherSize-x.blockSize; i++ {
x.iv[i] = x.iv[i+x.blockSize]
}
- off := x.cipherSize - x.blockSize;
+ off := x.cipherSize - x.blockSize
for i := off; i < x.cipherSize; i++ {
x.iv[i] = dst[i-off]
}
@@ -59,7 +59,7 @@ func (x *cfbCipher) Encrypt(src, dst []byte) {
func (x *cfbCipher) Decrypt(src, dst []byte) {
// Encrypt [sic] old IV and xor prefix with src to make dst.
- x.c.Encrypt(x.iv, x.tmp);
+ x.c.Encrypt(x.iv, x.tmp)
for i := 0; i < x.blockSize; i++ {
dst[i] = src[i] ^ x.tmp[i]
}
@@ -68,7 +68,7 @@ func (x *cfbCipher) Decrypt(src, dst []byte) {
for i := 0; i < x.cipherSize-x.blockSize; i++ {
x.iv[i] = x.iv[i+x.blockSize]
}
- off := x.cipherSize - x.blockSize;
+ off := x.cipherSize - x.blockSize
for i := off; i < x.cipherSize; i++ {
// Reconstruct src = dst ^ x.tmp
// in case we overwrote src (src == dst).
diff --git a/src/pkg/crypto/block/cfb_aes_test.go b/src/pkg/crypto/block/cfb_aes_test.go
index f1913691b9..8a245a2cbd 100644
--- a/src/pkg/crypto/block/cfb_aes_test.go
+++ b/src/pkg/crypto/block/cfb_aes_test.go
@@ -11,19 +11,19 @@
package block
import (
- "bytes";
- "crypto/aes";
- "io";
- "testing";
+ "bytes"
+ "crypto/aes"
+ "io"
+ "testing"
)
type cfbTest struct {
- name string;
- s int;
- key []byte;
- iv []byte;
- in []byte;
- out []byte;
+ name string
+ s int
+ key []byte
+ iv []byte
+ in []byte
+ out []byte
}
var cfbAESTests = []cfbTest{
@@ -271,33 +271,33 @@ var cfbAESTests = []cfbTest{
func TestCFB_AES(t *testing.T) {
for _, tt := range cfbAESTests {
- test := tt.name;
+ test := tt.name
if tt.s == 1 {
// 1-bit CFB not implemented
continue
}
- c, err := aes.NewCipher(tt.key);
+ c, err := aes.NewCipher(tt.key)
if err != nil {
- t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
- continue;
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
+ continue
}
- var crypt bytes.Buffer;
- w := NewCFBEncrypter(c, tt.s, tt.iv, &crypt);
- var r io.Reader = bytes.NewBuffer(tt.in);
- n, err := io.Copy(w, r);
+ var crypt bytes.Buffer
+ w := NewCFBEncrypter(c, tt.s, tt.iv, &crypt)
+ var r io.Reader = bytes.NewBuffer(tt.in)
+ n, err := io.Copy(w, r)
if n != int64(len(tt.in)) || err != nil {
t.Errorf("%s: CFBEncrypter io.Copy = %d, %v want %d, nil", test, n, err, len(tt.in))
} else if d := crypt.Bytes(); !same(tt.out, d) {
t.Errorf("%s: CFBEncrypter\nhave %x\nwant %x", test, d, tt.out)
}
- var plain bytes.Buffer;
- r = NewCFBDecrypter(c, tt.s, tt.iv, bytes.NewBuffer(tt.out));
- w = &plain;
- n, err = io.Copy(w, r);
+ var plain bytes.Buffer
+ r = NewCFBDecrypter(c, tt.s, tt.iv, bytes.NewBuffer(tt.out))
+ w = &plain
+ n, err = io.Copy(w, r)
if n != int64(len(tt.out)) || err != nil {
t.Errorf("%s: CFBDecrypter io.Copy = %d, %v want %d, nil", test, n, err, len(tt.out))
} else if d := plain.Bytes(); !same(tt.in, d) {
diff --git a/src/pkg/crypto/block/cipher.go b/src/pkg/crypto/block/cipher.go
index 2ca15c1296..1b786cca49 100644
--- a/src/pkg/crypto/block/cipher.go
+++ b/src/pkg/crypto/block/cipher.go
@@ -14,27 +14,27 @@ package block
// extend that capability to streams of blocks.
type Cipher interface {
// BlockSize returns the cipher's block size.
- BlockSize() int;
+ BlockSize() int
// Encrypt encrypts the first block in src into dst.
// Src and dst may point at the same memory.
- Encrypt(src, dst []byte);
+ Encrypt(src, dst []byte)
// Decrypt decrypts the first block in src into dst.
// Src and dst may point at the same memory.
- Decrypt(src, dst []byte);
+ Decrypt(src, dst []byte)
}
// Utility routines
func shift1(src, dst []byte) byte {
- var b byte;
+ var b byte
for i := len(src) - 1; i >= 0; i-- {
- bb := src[i] >> 7;
- dst[i] = src[i]<<1 | b;
- b = bb;
+ bb := src[i] >> 7
+ dst[i] = src[i]<<1 | b
+ b = bb
}
- return b;
+ return b
}
func same(p, q []byte) bool {
@@ -46,13 +46,13 @@ func same(p, q []byte) bool {
return false
}
}
- return true;
+ return true
}
func copy(p []byte) []byte {
- q := make([]byte, len(p));
+ q := make([]byte, len(p))
for i, b := range p {
q[i] = b
}
- return q;
+ return q
}
diff --git a/src/pkg/crypto/block/cmac.go b/src/pkg/crypto/block/cmac.go
index 5b00b37272..a2f80fe4b3 100644
--- a/src/pkg/crypto/block/cmac.go
+++ b/src/pkg/crypto/block/cmac.go
@@ -8,20 +8,20 @@
package block
import (
- "hash";
- "os";
+ "hash"
+ "os"
)
const (
// minimal irreducible polynomial of degree b
- r64 = 0x1b;
- r128 = 0x87;
+ r64 = 0x1b
+ r128 = 0x87
)
type cmac struct {
- k1, k2, ci, digest []byte;
- p int; // position in ci
- c Cipher;
+ k1, k2, ci, digest []byte
+ p int // position in ci
+ c Cipher
}
// TODO(rsc): Should this return an error instead of panic?
@@ -29,8 +29,8 @@ type cmac struct {
// NewCMAC returns a new instance of a CMAC message authentication code
// digest using the given Cipher.
func NewCMAC(c Cipher) hash.Hash {
- var r byte;
- n := c.BlockSize();
+ var r byte
+ n := c.BlockSize()
switch n {
case 64 / 8:
r = r64
@@ -40,15 +40,15 @@ func NewCMAC(c Cipher) hash.Hash {
panic("crypto/block: NewCMAC: invalid cipher block size", n)
}
- d := new(cmac);
- d.c = c;
- d.k1 = make([]byte, n);
- d.k2 = make([]byte, n);
- d.ci = make([]byte, n);
- d.digest = make([]byte, n);
+ d := new(cmac)
+ d.c = c
+ d.k1 = make([]byte, n)
+ d.k2 = make([]byte, n)
+ d.ci = make([]byte, n)
+ d.digest = make([]byte, n)
// Subkey generation, p. 7
- c.Encrypt(d.k1, d.k1);
+ c.Encrypt(d.k1, d.k1)
if shift1(d.k1, d.k1) != 0 {
d.k1[n-1] ^= r
}
@@ -56,7 +56,7 @@ func NewCMAC(c Cipher) hash.Hash {
d.k2[n-1] ^= r
}
- return d;
+ return d
}
// Reset clears the digest state, starting a new digest.
@@ -64,7 +64,7 @@ func (d *cmac) Reset() {
for i := range d.ci {
d.ci[i] = 0
}
- d.p = 0;
+ d.p = 0
}
// Write adds the given data to the digest state.
@@ -73,13 +73,13 @@ func (d *cmac) Write(p []byte) (n int, err os.Error) {
for _, c := range p {
// If ci is full, encrypt and start over.
if d.p >= len(d.ci) {
- d.c.Encrypt(d.ci, d.ci);
- d.p = 0;
+ d.c.Encrypt(d.ci, d.ci)
+ d.p = 0
}
- d.ci[d.p] ^= c;
- d.p++;
+ d.ci[d.p] ^= c
+ d.p++
}
- return len(p), nil;
+ return len(p), nil
}
// Sum returns the CMAC digest, one cipher block in length,
@@ -88,7 +88,7 @@ func (d *cmac) Sum() []byte {
// Finish last block, mix in key, encrypt.
// Don't edit ci, in case caller wants
// to keep digesting after call to Sum.
- k := d.k1;
+ k := d.k1
if d.p < len(d.digest) {
k = d.k2
}
@@ -98,8 +98,8 @@ func (d *cmac) Sum() []byte {
if d.p < len(d.digest) {
d.digest[d.p] ^= 0x80
}
- d.c.Encrypt(d.digest, d.digest);
- return d.digest;
+ d.c.Encrypt(d.digest, d.digest)
+ return d.digest
}
-func (d *cmac) Size() int { return len(d.digest) }
+func (d *cmac) Size() int { return len(d.digest) }
diff --git a/src/pkg/crypto/block/cmac_aes_test.go b/src/pkg/crypto/block/cmac_aes_test.go
index 8e727ed9cf..a9cbc71a6c 100644
--- a/src/pkg/crypto/block/cmac_aes_test.go
+++ b/src/pkg/crypto/block/cmac_aes_test.go
@@ -7,14 +7,14 @@
package block
import (
- "crypto/aes";
- "testing";
+ "crypto/aes"
+ "testing"
)
type cmacAESTest struct {
- key []byte;
- in []byte;
- digest []byte;
+ key []byte
+ in []byte
+ digest []byte
}
var cmacAESTests = []cmacAESTest{
@@ -109,22 +109,22 @@ var cmacAESTests = []cmacAESTest{
func TestCMAC_AES(t *testing.T) {
for i, tt := range cmacAESTests {
- c, err := aes.NewCipher(tt.key);
+ c, err := aes.NewCipher(tt.key)
if err != nil {
- t.Errorf("test %d: NewCipher: %s", i, err);
- continue;
+ t.Errorf("test %d: NewCipher: %s", i, err)
+ continue
}
- d := NewCMAC(c);
- n, err := d.Write(tt.in);
+ d := NewCMAC(c)
+ n, err := d.Write(tt.in)
if err != nil || n != len(tt.in) {
- t.Errorf("test %d: Write %d: %d, %s", i, len(tt.in), n, err);
- continue;
+ t.Errorf("test %d: Write %d: %d, %s", i, len(tt.in), n, err)
+ continue
}
- sum := d.Sum();
+ sum := d.Sum()
if !same(sum, tt.digest) {
- x := d.(*cmac);
- t.Errorf("test %d: digest mismatch\n\twant %x\n\thave %x\n\tk1 %x\n\tk2 %x", i, tt.digest, sum, x.k1, x.k2);
- continue;
+ x := d.(*cmac)
+ t.Errorf("test %d: digest mismatch\n\twant %x\n\thave %x\n\tk1 %x\n\tk2 %x", i, tt.digest, sum, x.k1, x.k2)
+ continue
}
}
}
diff --git a/src/pkg/crypto/block/ctr.go b/src/pkg/crypto/block/ctr.go
index bfb0fc23e7..085ae05b18 100644
--- a/src/pkg/crypto/block/ctr.go
+++ b/src/pkg/crypto/block/ctr.go
@@ -13,36 +13,36 @@
package block
import (
- "io";
+ "io"
)
type ctrStream struct {
- c Cipher;
- ctr []byte;
- out []byte;
+ c Cipher
+ ctr []byte
+ out []byte
}
func newCTRStream(c Cipher, ctr []byte) *ctrStream {
- x := new(ctrStream);
- x.c = c;
- x.ctr = copy(ctr);
- x.out = make([]byte, len(ctr));
- return x;
+ x := new(ctrStream)
+ x.c = c
+ x.ctr = copy(ctr)
+ x.out = make([]byte, len(ctr))
+ return x
}
func (x *ctrStream) Next() []byte {
// Next block is encryption of counter.
- x.c.Encrypt(x.ctr, x.out);
+ x.c.Encrypt(x.ctr, x.out)
// Increment counter
for i := len(x.ctr) - 1; i >= 0; i-- {
- x.ctr[i]++;
+ x.ctr[i]++
if x.ctr[i] != 0 {
break
}
}
- return x.out;
+ return x.out
}
// NewCTRReader returns a reader that reads data from r, decrypts (or encrypts)
diff --git a/src/pkg/crypto/block/ctr_aes_test.go b/src/pkg/crypto/block/ctr_aes_test.go
index 456c07131b..adb996c1dd 100644
--- a/src/pkg/crypto/block/ctr_aes_test.go
+++ b/src/pkg/crypto/block/ctr_aes_test.go
@@ -11,18 +11,18 @@
package block
import (
- "bytes";
- "crypto/aes";
- "io";
- "testing";
+ "bytes"
+ "crypto/aes"
+ "io"
+ "testing"
)
type ctrTest struct {
- name string;
- key []byte;
- iv []byte;
- in []byte;
- out []byte;
+ name string
+ key []byte
+ iv []byte
+ in []byte
+ out []byte
}
var commonCounter = []byte{0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}
@@ -69,20 +69,20 @@ var ctrAESTests = []ctrTest{
func TestCTR_AES(t *testing.T) {
for _, tt := range ctrAESTests {
- test := tt.name;
+ test := tt.name
- c, err := aes.NewCipher(tt.key);
+ c, err := aes.NewCipher(tt.key)
if err != nil {
- t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
- continue;
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
+ continue
}
for j := 0; j <= 5; j += 5 {
- var crypt bytes.Buffer;
- in := tt.in[0 : len(tt.in)-j];
- w := NewCTRWriter(c, tt.iv, &crypt);
- var r io.Reader = bytes.NewBuffer(in);
- n, err := io.Copy(w, r);
+ var crypt bytes.Buffer
+ in := tt.in[0 : len(tt.in)-j]
+ w := NewCTRWriter(c, tt.iv, &crypt)
+ var r io.Reader = bytes.NewBuffer(in)
+ n, err := io.Copy(w, r)
if n != int64(len(in)) || err != nil {
t.Errorf("%s/%d: CTRWriter io.Copy = %d, %v want %d, nil", test, len(in), n, err, len(in))
} else if d, out := crypt.Bytes(), tt.out[0:len(in)]; !same(out, d) {
@@ -91,11 +91,11 @@ func TestCTR_AES(t *testing.T) {
}
for j := 0; j <= 7; j += 7 {
- var plain bytes.Buffer;
- out := tt.out[0 : len(tt.out)-j];
- r := NewCTRReader(c, tt.iv, bytes.NewBuffer(out));
- w := &plain;
- n, err := io.Copy(w, r);
+ var plain bytes.Buffer
+ out := tt.out[0 : len(tt.out)-j]
+ r := NewCTRReader(c, tt.iv, bytes.NewBuffer(out))
+ w := &plain
+ n, err := io.Copy(w, r)
if n != int64(len(out)) || err != nil {
t.Errorf("%s/%d: CTRReader io.Copy = %d, %v want %d, nil", test, len(out), n, err, len(out))
} else if d, in := plain.Bytes(), tt.in[0:len(out)]; !same(in, d) {
diff --git a/src/pkg/crypto/block/eax.go b/src/pkg/crypto/block/eax.go
index 07919e4ae7..fcd5fe20f7 100644
--- a/src/pkg/crypto/block/eax.go
+++ b/src/pkg/crypto/block/eax.go
@@ -15,18 +15,18 @@
package block
import (
- "fmt";
- "hash";
- "io";
- "os";
+ "fmt"
+ "hash"
+ "io"
+ "os"
)
// An EAXTagError is returned when the message has failed to authenticate,
// because the tag at the end of the message stream (Read) does not match
// the tag computed from the message itself (Computed).
type EAXTagError struct {
- Read []byte;
- Computed []byte;
+ Read []byte
+ Computed []byte
}
func (e *EAXTagError) String() string {
@@ -34,39 +34,39 @@ func (e *EAXTagError) String() string {
}
func setupEAX(c Cipher, iv, hdr []byte, tagBytes int) (ctrIV, tag []byte, cmac hash.Hash) {
- n := len(iv);
+ n := len(iv)
if n != c.BlockSize() {
panicln("crypto/block: EAX: iv length", n, "!=", c.BlockSize())
}
- buf := make([]byte, n); // zeroed
+ buf := make([]byte, n) // zeroed
// tag = CMAC(0 + iv) ^ CMAC(1 + hdr) ^ CMAC(2 + data)
- cmac = NewCMAC(c);
- cmac.Write(buf); // 0
- cmac.Write(iv);
- sum := cmac.Sum();
- ctrIV = copy(sum);
- tag = copy(sum[0:tagBytes]);
+ cmac = NewCMAC(c)
+ cmac.Write(buf) // 0
+ cmac.Write(iv)
+ sum := cmac.Sum()
+ ctrIV = copy(sum)
+ tag = copy(sum[0:tagBytes])
- cmac.Reset();
- buf[n-1] = 1;
- cmac.Write(buf); // 1
- cmac.Write(hdr);
- sum = cmac.Sum();
+ cmac.Reset()
+ buf[n-1] = 1
+ cmac.Write(buf) // 1
+ cmac.Write(hdr)
+ sum = cmac.Sum()
for i := 0; i < tagBytes; i++ {
tag[i] ^= sum[i]
}
- cmac.Reset();
- buf[n-1] = 2; // 2
- cmac.Write(buf);
+ cmac.Reset()
+ buf[n-1] = 2 // 2
+ cmac.Write(buf)
- return;
+ return
}
func finishEAX(tag []byte, cmac hash.Hash) {
// Finish CMAC #2 and xor into tag.
- sum := cmac.Sum();
+ sum := cmac.Sum()
for i := range tag {
tag[i] ^= sum[i]
}
@@ -75,21 +75,21 @@ func finishEAX(tag []byte, cmac hash.Hash) {
// Writer adapter. Tees writes into both w and cmac.
// Knows that cmac never returns write errors.
type cmacWriter struct {
- w io.Writer;
- cmac hash.Hash;
+ w io.Writer
+ cmac hash.Hash
}
func (cw *cmacWriter) Write(p []byte) (n int, err os.Error) {
- n, err = cw.w.Write(p);
- cw.cmac.Write(p[0:n]);
- return;
+ n, err = cw.w.Write(p)
+ cw.cmac.Write(p[0:n])
+ return
}
// An eaxEncrypter implements the EAX encryption mode.
type eaxEncrypter struct {
- ctr io.Writer; // CTR encrypter
- cw cmacWriter; // CTR's output stream
- tag []byte;
+ ctr io.Writer // CTR encrypter
+ cw cmacWriter // CTR's output stream
+ tag []byte
}
// NewEAXEncrypter creates and returns a new EAX encrypter
@@ -98,15 +98,15 @@ type eaxEncrypter struct {
// the data it receives and writes that data to w.
// The encrypter's Close method writes a final authenticating tag to w.
func NewEAXEncrypter(c Cipher, iv []byte, hdr []byte, tagBytes int, w io.Writer) io.WriteCloser {
- x := new(eaxEncrypter);
+ x := new(eaxEncrypter)
// Create new CTR instance writing to both
// w for encrypted output and cmac for digesting.
- x.cw.w = w;
- var ctrIV []byte;
- ctrIV, x.tag, x.cw.cmac = setupEAX(c, iv, hdr, tagBytes);
- x.ctr = NewCTRWriter(c, ctrIV, &x.cw);
- return x;
+ x.cw.w = w
+ var ctrIV []byte
+ ctrIV, x.tag, x.cw.cmac = setupEAX(c, iv, hdr, tagBytes)
+ x.ctr = NewCTRWriter(c, ctrIV, &x.cw)
+ return x
}
func (x *eaxEncrypter) Write(p []byte) (n int, err os.Error) {
@@ -114,16 +114,16 @@ func (x *eaxEncrypter) Write(p []byte) (n int, err os.Error) {
}
func (x *eaxEncrypter) Close() os.Error {
- x.ctr = nil; // crash if Write is called again
+ x.ctr = nil // crash if Write is called again
// Write tag.
- finishEAX(x.tag, x.cw.cmac);
- n, err := x.cw.w.Write(x.tag);
+ finishEAX(x.tag, x.cw.cmac)
+ n, err := x.cw.w.Write(x.tag)
if n != len(x.tag) && err == nil {
err = io.ErrShortWrite
}
- return err;
+ return err
}
// Reader adapter. Returns data read from r but hangs
@@ -133,10 +133,10 @@ func (x *eaxEncrypter) Close() os.Error {
// and the "tee into digest" functionality could be separated,
// but the latter half is trivial.
type cmacReader struct {
- r io.Reader;
- cmac hash.Hash;
- tag []byte;
- tmp []byte;
+ r io.Reader
+ cmac hash.Hash
+ tag []byte
+ tmp []byte
}
func (cr *cmacReader) Read(p []byte) (n int, err os.Error) {
@@ -147,21 +147,21 @@ func (cr *cmacReader) Read(p []byte) (n int, err os.Error) {
// First, read a tag-sized chunk.
// It's probably not the tag (unless there's no data).
- tag := cr.tag;
+ tag := cr.tag
if len(tag) < cap(tag) {
- nt := len(tag);
- nn, err1 := io.ReadFull(cr.r, tag[nt:cap(tag)]);
- tag = tag[0 : nt+nn];
- cr.tag = tag;
+ nt := len(tag)
+ nn, err1 := io.ReadFull(cr.r, tag[nt:cap(tag)])
+ tag = tag[0 : nt+nn]
+ cr.tag = tag
if err1 != nil {
return 0, err1
}
}
- tagBytes := len(tag);
+ tagBytes := len(tag)
if len(p) > 4*tagBytes {
// If p is big, try to read directly into p to avoid a copy.
- n, err = cr.r.Read(p[tagBytes:]);
+ n, err = cr.r.Read(p[tagBytes:])
if n == 0 {
goto out
}
@@ -173,19 +173,19 @@ func (cr *cmacReader) Read(p []byte) (n int, err os.Error) {
for i := 0; i < tagBytes; i++ {
tag[i] = p[n+i]
}
- goto out;
+ goto out
}
// Otherwise, read into p and then slide data
- n, err = cr.r.Read(p);
+ n, err = cr.r.Read(p)
if n == 0 {
goto out
}
// copy tag+p into p+tmp and then swap tmp, tag
- tmp := cr.tmp;
+ tmp := cr.tmp
for i := n + tagBytes - 1; i >= 0; i-- {
- var c byte;
+ var c byte
if i < tagBytes {
c = tag[i]
} else {
@@ -197,17 +197,17 @@ func (cr *cmacReader) Read(p []byte) (n int, err os.Error) {
tmp[i] = c
}
}
- cr.tmp, cr.tag = tag, tmp;
+ cr.tmp, cr.tag = tag, tmp
out:
- cr.cmac.Write(p[0:n]);
- return;
+ cr.cmac.Write(p[0:n])
+ return
}
type eaxDecrypter struct {
- ctr io.Reader;
- cr cmacReader;
- tag []byte;
+ ctr io.Reader
+ cr cmacReader
+ tag []byte
}
// NewEAXDecrypter creates and returns a new EAX decrypter
@@ -220,34 +220,34 @@ type eaxDecrypter struct {
// assumed to be valid, authenticated data until Read returns
// 0, nil to signal the end of the data.
func NewEAXDecrypter(c Cipher, iv []byte, hdr []byte, tagBytes int, r io.Reader) io.Reader {
- x := new(eaxDecrypter);
+ x := new(eaxDecrypter)
- x.cr.r = r;
- x.cr.tag = make([]byte, 0, tagBytes);
- x.cr.tmp = make([]byte, 0, tagBytes);
- var ctrIV []byte;
- ctrIV, x.tag, x.cr.cmac = setupEAX(c, iv, hdr, tagBytes);
- x.ctr = NewCTRReader(c, ctrIV, &x.cr);
- return x;
+ x.cr.r = r
+ x.cr.tag = make([]byte, 0, tagBytes)
+ x.cr.tmp = make([]byte, 0, tagBytes)
+ var ctrIV []byte
+ ctrIV, x.tag, x.cr.cmac = setupEAX(c, iv, hdr, tagBytes)
+ x.ctr = NewCTRReader(c, ctrIV, &x.cr)
+ return x
}
func (x *eaxDecrypter) checkTag() os.Error {
- x.ctr = nil; // crash if Read is called again
+ x.ctr = nil // crash if Read is called again
- finishEAX(x.tag, x.cr.cmac);
+ finishEAX(x.tag, x.cr.cmac)
if !same(x.tag, x.cr.tag) {
- e := new(EAXTagError);
- e.Computed = copy(x.tag);
- e.Read = copy(x.cr.tag);
- return e;
+ e := new(EAXTagError)
+ e.Computed = copy(x.tag)
+ e.Read = copy(x.cr.tag)
+ return e
}
- return nil;
+ return nil
}
func (x *eaxDecrypter) Read(p []byte) (n int, err os.Error) {
- n, err = x.ctr.Read(p);
+ n, err = x.ctr.Read(p)
if n == 0 && err == nil {
err = x.checkTag()
}
- return n, err;
+ return n, err
}
diff --git a/src/pkg/crypto/block/eax_aes_test.go b/src/pkg/crypto/block/eax_aes_test.go
index 43f126d216..a1a0994293 100644
--- a/src/pkg/crypto/block/eax_aes_test.go
+++ b/src/pkg/crypto/block/eax_aes_test.go
@@ -5,21 +5,21 @@
package block
import (
- "bytes";
- "crypto/aes";
- "fmt";
- "io";
- "testing";
+ "bytes"
+ "crypto/aes"
+ "fmt"
+ "io"
+ "testing"
)
// Test vectors from http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
type eaxAESTest struct {
- msg []byte;
- key []byte;
- nonce []byte;
- header []byte;
- cipher []byte;
+ msg []byte
+ key []byte
+ nonce []byte
+ header []byte
+ cipher []byte
}
var eaxAESTests = []eaxAESTest{
@@ -96,20 +96,20 @@ var eaxAESTests = []eaxAESTest{
}
func TestEAXEncrypt_AES(t *testing.T) {
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for i, tt := range eaxAESTests {
- test := fmt.Sprintf("test %d", i);
- c, err := aes.NewCipher(tt.key);
+ test := fmt.Sprintf("test %d", i)
+ c, err := aes.NewCipher(tt.key)
if err != nil {
t.Fatalf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
}
- b.Reset();
- enc := NewEAXEncrypter(c, tt.nonce, tt.header, 16, b);
- n, err := io.Copy(enc, bytes.NewBuffer(tt.msg));
+ b.Reset()
+ enc := NewEAXEncrypter(c, tt.nonce, tt.header, 16, b)
+ n, err := io.Copy(enc, bytes.NewBuffer(tt.msg))
if n != int64(len(tt.msg)) || err != nil {
t.Fatalf("%s: io.Copy into encrypter: %d, %s", test, n, err)
}
- err = enc.Close();
+ err = enc.Close()
if err != nil {
t.Fatalf("%s: enc.Close: %s", test, err)
}
@@ -120,16 +120,16 @@ func TestEAXEncrypt_AES(t *testing.T) {
}
func TestEAXDecrypt_AES(t *testing.T) {
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for i, tt := range eaxAESTests {
- test := fmt.Sprintf("test %d", i);
- c, err := aes.NewCipher(tt.key);
+ test := fmt.Sprintf("test %d", i)
+ c, err := aes.NewCipher(tt.key)
if err != nil {
t.Fatalf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
}
- b.Reset();
- dec := NewEAXDecrypter(c, tt.nonce, tt.header, 16, bytes.NewBuffer(tt.cipher));
- n, err := io.Copy(b, dec);
+ b.Reset()
+ dec := NewEAXDecrypter(c, tt.nonce, tt.header, 16, bytes.NewBuffer(tt.cipher))
+ n, err := io.Copy(b, dec)
if n != int64(len(tt.msg)) || err != nil {
t.Fatalf("%s: io.Copy into decrypter: %d, %s", test, n, err)
}
diff --git a/src/pkg/crypto/block/ecb.go b/src/pkg/crypto/block/ecb.go
index c7491eb9cb..73d1d63f71 100644
--- a/src/pkg/crypto/block/ecb.go
+++ b/src/pkg/crypto/block/ecb.go
@@ -14,32 +14,32 @@
package block
import (
- "io";
- "os";
- "strconv";
+ "io"
+ "os"
+ "strconv"
)
type ecbDecrypter struct {
- c Cipher;
- r io.Reader;
- blockSize int; // block size
+ c Cipher
+ r io.Reader
+ blockSize int // block size
// Buffered data.
// The buffer buf is used as storage for both
// plain or crypt; at least one of those is nil at any given time.
- buf []byte;
- plain []byte; // plain text waiting to be read
- crypt []byte; // ciphertext waiting to be decrypted
+ buf []byte
+ plain []byte // plain text waiting to be read
+ crypt []byte // ciphertext waiting to be decrypted
}
// Read into x.crypt until it has a full block or EOF or an error happens.
func (x *ecbDecrypter) fillCrypt() os.Error {
- var err os.Error;
+ var err os.Error
for len(x.crypt) < x.blockSize {
- off := len(x.crypt);
- var m int;
- m, err = x.r.Read(x.crypt[off:x.blockSize]);
- x.crypt = x.crypt[0 : off+m];
+ off := len(x.crypt)
+ var m int
+ m, err = x.r.Read(x.crypt[off:x.blockSize])
+ x.crypt = x.crypt[0 : off+m]
if m == 0 {
break
}
@@ -53,12 +53,12 @@ func (x *ecbDecrypter) fillCrypt() os.Error {
break
}
}
- return err;
+ return err
}
// Read from plain text buffer into p.
func (x *ecbDecrypter) readPlain(p []byte) int {
- n := len(x.plain);
+ n := len(x.plain)
if n > len(p) {
n = len(p)
}
@@ -70,7 +70,7 @@ func (x *ecbDecrypter) readPlain(p []byte) int {
} else {
x.plain = nil
}
- return n;
+ return n
}
type ecbFragmentError int
@@ -95,46 +95,46 @@ func (x *ecbDecrypter) Read(p []byte) (n int, err os.Error) {
// If there is a leftover cipher text buffer,
// try to accumulate a full block.
if x.crypt != nil {
- err = x.fillCrypt();
+ err = x.fillCrypt()
if err != nil || len(x.crypt) == 0 {
return
}
- x.c.Decrypt(x.crypt, x.crypt);
- x.plain = x.crypt;
- x.crypt = nil;
+ x.c.Decrypt(x.crypt, x.crypt)
+ x.plain = x.crypt
+ x.crypt = nil
}
// If there is a leftover plain text buffer, read from it.
if x.plain != nil {
- n = x.readPlain(p);
- return;
+ n = x.readPlain(p)
+ return
}
// Read and decrypt directly in caller's buffer.
- n, err = io.ReadAtLeast(x.r, p, x.blockSize);
+ n, err = io.ReadAtLeast(x.r, p, x.blockSize)
if err == os.EOF && n > 0 {
// EOF is only okay on block boundary
- err = os.ErrorString("block fragment at EOF during decryption");
- return;
+ err = os.ErrorString("block fragment at EOF during decryption")
+ return
}
- var i int;
+ var i int
for i = 0; i+x.blockSize <= n; i += x.blockSize {
- a := p[i : i+x.blockSize];
- x.c.Decrypt(a, a);
+ a := p[i : i+x.blockSize]
+ x.c.Decrypt(a, a)
}
// There might be an encrypted fringe remaining.
// Save it for next time.
if i < n {
- p = p[i:n];
+ p = p[i:n]
for j, v := range p {
x.buf[j] = v
}
- x.crypt = x.buf[0:len(p)];
- n = i;
+ x.crypt = x.buf[0:len(p)]
+ n = i
}
- return;
+ return
}
// NewECBDecrypter returns a reader that reads data from r and decrypts it using c.
@@ -143,26 +143,26 @@ func (x *ecbDecrypter) Read(p []byte) (n int, err os.Error) {
// The returned Reader does not buffer or read ahead except
// as required by the cipher's block size.
func NewECBDecrypter(c Cipher, r io.Reader) io.Reader {
- x := new(ecbDecrypter);
- x.c = c;
- x.r = r;
- x.blockSize = c.BlockSize();
- x.buf = make([]byte, x.blockSize);
- return x;
+ x := new(ecbDecrypter)
+ x.c = c
+ x.r = r
+ x.blockSize = c.BlockSize()
+ x.buf = make([]byte, x.blockSize)
+ return x
}
type ecbEncrypter struct {
- c Cipher;
- w io.Writer;
- blockSize int;
+ c Cipher
+ w io.Writer
+ blockSize int
// Buffered data.
// The buffer buf is used as storage for both
// plain or crypt. If both are non-nil, plain
// follows crypt in buf.
- buf []byte;
- plain []byte; // plain text waiting to be encrypted
- crypt []byte; // encrypted text waiting to be written
+ buf []byte
+ plain []byte // plain text waiting to be encrypted
+ crypt []byte // encrypted text waiting to be written
}
// Flush the x.crypt buffer to x.w.
@@ -170,9 +170,9 @@ func (x *ecbEncrypter) flushCrypt() os.Error {
if len(x.crypt) == 0 {
return nil
}
- n, err := x.w.Write(x.crypt);
+ n, err := x.w.Write(x.crypt)
if n < len(x.crypt) {
- x.crypt = x.crypt[n:];
+ x.crypt = x.crypt[n:]
if err == nil {
err = io.ErrShortWrite
}
@@ -180,8 +180,8 @@ func (x *ecbEncrypter) flushCrypt() os.Error {
if err != nil {
return err
}
- x.crypt = nil;
- return nil;
+ x.crypt = nil
+ return nil
}
// Slide x.plain down to the beginning of x.buf.
@@ -196,35 +196,35 @@ func (x *ecbEncrypter) slidePlain() {
for i := 0; i < len(x.plain); i++ {
x.buf[i] = x.plain[i]
}
- x.plain = x.buf[0:len(x.plain)];
+ x.plain = x.buf[0:len(x.plain)]
}
}
// Fill x.plain from the data in p.
// Return the number of bytes copied.
func (x *ecbEncrypter) fillPlain(p []byte) int {
- off := len(x.plain);
- n := len(p);
+ off := len(x.plain)
+ n := len(p)
if max := cap(x.plain) - off; n > max {
n = max
}
- x.plain = x.plain[0 : off+n];
+ x.plain = x.plain[0 : off+n]
for i := 0; i < n; i++ {
x.plain[off+i] = p[i]
}
- return n;
+ return n
}
// Encrypt x.plain; record encrypted range as x.crypt.
func (x *ecbEncrypter) encrypt() {
- var i int;
- n := len(x.plain);
+ var i int
+ n := len(x.plain)
for i = 0; i+x.blockSize <= n; i += x.blockSize {
- a := x.plain[i : i+x.blockSize];
- x.c.Encrypt(a, a);
+ a := x.plain[i : i+x.blockSize]
+ x.c.Encrypt(a, a)
}
- x.crypt = x.plain[0:i];
- x.plain = x.plain[i:n];
+ x.crypt = x.plain[0:i]
+ x.plain = x.plain[i:n]
}
func (x *ecbEncrypter) Write(p []byte) (n int, err os.Error) {
@@ -238,25 +238,25 @@ func (x *ecbEncrypter) Write(p []byte) (n int, err os.Error) {
// Now that encrypted data is gone (flush ran),
// perhaps we need to slide the plaintext down.
- x.slidePlain();
+ x.slidePlain()
// Fill plaintext buffer from p.
- m := x.fillPlain(p);
+ m := x.fillPlain(p)
if m == 0 {
break
}
- n += m;
- p = p[m:];
+ n += m
+ p = p[m:]
// Encrypt, adjusting crypt and plain.
- x.encrypt();
+ x.encrypt()
// Write x.crypt.
if err = x.flushCrypt(); err != nil {
break
}
}
- return;
+ return
}
// NewECBEncrypter returns a writer that encrypts data using c and writes it to w.
@@ -265,12 +265,12 @@ func (x *ecbEncrypter) Write(p []byte) (n int, err os.Error) {
// The returned Writer does no buffering except as required
// by the cipher's block size, so there is no need for a Flush method.
func NewECBEncrypter(c Cipher, w io.Writer) io.Writer {
- x := new(ecbEncrypter);
- x.c = c;
- x.w = w;
- x.blockSize = c.BlockSize();
+ x := new(ecbEncrypter)
+ x.c = c
+ x.w = w
+ x.blockSize = c.BlockSize()
// Create a buffer that is an integral number of blocks.
- x.buf = make([]byte, 8192/x.blockSize*x.blockSize);
- return x;
+ x.buf = make([]byte, 8192/x.blockSize*x.blockSize)
+ return x
}
diff --git a/src/pkg/crypto/block/ecb_aes_test.go b/src/pkg/crypto/block/ecb_aes_test.go
index 315ec213de..db0e085fa2 100644
--- a/src/pkg/crypto/block/ecb_aes_test.go
+++ b/src/pkg/crypto/block/ecb_aes_test.go
@@ -11,17 +11,17 @@
package block
import (
- "bytes";
- "crypto/aes";
- "io";
- "testing";
+ "bytes"
+ "crypto/aes"
+ "io"
+ "testing"
)
type ecbTest struct {
- name string;
- key []byte;
- in []byte;
- out []byte;
+ name string
+ key []byte
+ in []byte
+ out []byte
}
var commonInput = []byte{
@@ -92,28 +92,28 @@ var ecbAESTests = []ecbTest{
func TestECB_AES(t *testing.T) {
for _, tt := range ecbAESTests {
- test := tt.name;
+ test := tt.name
- c, err := aes.NewCipher(tt.key);
+ c, err := aes.NewCipher(tt.key)
if err != nil {
- t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
- continue;
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
+ continue
}
- var crypt bytes.Buffer;
- w := NewECBEncrypter(c, &crypt);
- var r io.Reader = bytes.NewBuffer(tt.in);
- n, err := io.Copy(w, r);
+ var crypt bytes.Buffer
+ w := NewECBEncrypter(c, &crypt)
+ var r io.Reader = bytes.NewBuffer(tt.in)
+ n, err := io.Copy(w, r)
if n != int64(len(tt.in)) || err != nil {
t.Errorf("%s: ECBReader io.Copy = %d, %v want %d, nil", test, n, err, len(tt.in))
} else if d := crypt.Bytes(); !same(tt.out, d) {
t.Errorf("%s: ECBReader\nhave %x\nwant %x", test, d, tt.out)
}
- var plain bytes.Buffer;
- r = NewECBDecrypter(c, bytes.NewBuffer(tt.out));
- w = &plain;
- n, err = io.Copy(w, r);
+ var plain bytes.Buffer
+ r = NewECBDecrypter(c, bytes.NewBuffer(tt.out))
+ w = &plain
+ n, err = io.Copy(w, r)
if n != int64(len(tt.out)) || err != nil {
t.Errorf("%s: ECBWriter io.Copy = %d, %v want %d, nil", test, n, err, len(tt.out))
} else if d := plain.Bytes(); !same(tt.in, d) {
diff --git a/src/pkg/crypto/block/ecb_test.go b/src/pkg/crypto/block/ecb_test.go
index d07afbe941..0d7c4035fb 100644
--- a/src/pkg/crypto/block/ecb_test.go
+++ b/src/pkg/crypto/block/ecb_test.go
@@ -5,22 +5,22 @@
package block
import (
- "bytes";
- "fmt";
- "io";
- "testing";
- "testing/iotest";
+ "bytes"
+ "fmt"
+ "io"
+ "testing"
+ "testing/iotest"
)
// Simple Cipher for testing: adds an incrementing amount
// to each byte in each
type IncCipher struct {
- blockSize int;
- delta byte;
- encrypting bool;
+ blockSize int
+ delta byte
+ encrypting bool
}
-func (c *IncCipher) BlockSize() int { return c.blockSize }
+func (c *IncCipher) BlockSize() int { return c.blockSize }
func (c *IncCipher) Encrypt(src, dst []byte) {
if !c.encrypting {
@@ -29,7 +29,7 @@ func (c *IncCipher) Encrypt(src, dst []byte) {
if len(src) != c.blockSize || len(dst) != c.blockSize {
panicln("encrypt: wrong block size", c.blockSize, len(src), len(dst))
}
- c.delta++;
+ c.delta++
for i, b := range src {
dst[i] = b + c.delta
}
@@ -42,62 +42,62 @@ func (c *IncCipher) Decrypt(src, dst []byte) {
if len(src) != c.blockSize || len(dst) != c.blockSize {
panicln("decrypt: wrong block size", c.blockSize, len(src), len(dst))
}
- c.delta--;
+ c.delta--
for i, b := range src {
dst[i] = b + c.delta
}
}
func TestECBEncrypter(t *testing.T) {
- var plain, crypt [256]byte;
+ var plain, crypt [256]byte
for i := 0; i < len(plain); i++ {
plain[i] = byte(i)
}
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for block := 1; block <= 64; block *= 2 {
// compute encrypted version
- delta := byte(0);
+ delta := byte(0)
for i := 0; i < len(crypt); i++ {
if i%block == 0 {
delta++
}
- crypt[i] = plain[i] + delta;
+ crypt[i] = plain[i] + delta
}
for frag := 0; frag < 2; frag++ {
- c := &IncCipher{block, 0, true};
- b.Reset();
- r := bytes.NewBuffer(&plain);
- w := NewECBEncrypter(c, b);
+ c := &IncCipher{block, 0, true}
+ b.Reset()
+ r := bytes.NewBuffer(&plain)
+ w := NewECBEncrypter(c, b)
// copy plain into w in increasingly large chunks: 1, 1, 2, 4, 8, ...
// if frag != 0, move the 1 to the end to cause fragmentation.
if frag == 0 {
- _, err := io.Copyn(w, r, 1);
+ _, err := io.Copyn(w, r, 1)
if err != nil {
- t.Errorf("block=%d frag=0: first Copyn: %s", block, err);
- continue;
+ t.Errorf("block=%d frag=0: first Copyn: %s", block, err)
+ continue
}
}
for n := 1; n <= len(plain)/2; n *= 2 {
- _, err := io.Copyn(w, r, int64(n));
+ _, err := io.Copyn(w, r, int64(n))
if err != nil {
t.Errorf("block=%d frag=%d: Copyn %d: %s", block, frag, n, err)
}
}
if frag != 0 {
- _, err := io.Copyn(w, r, 1);
+ _, err := io.Copyn(w, r, 1)
if err != nil {
- t.Errorf("block=%d frag=1: last Copyn: %s", block, err);
- continue;
+ t.Errorf("block=%d frag=1: last Copyn: %s", block, err)
+ continue
}
}
// check output
- data := b.Bytes();
+ data := b.Bytes()
if len(data) != len(crypt) {
- t.Errorf("block=%d frag=%d: want %d bytes, got %d", block, frag, len(crypt), len(data));
- continue;
+ t.Errorf("block=%d frag=%d: want %d bytes, got %d", block, frag, len(crypt), len(data))
+ continue
}
if string(data) != string(&crypt) {
@@ -112,57 +112,57 @@ func testECBDecrypter(t *testing.T, maxio int) {
func(r io.Reader) io.Reader { return r },
iotest.OneByteReader,
iotest.HalfReader,
- };
- var plain, crypt [256]byte;
+ }
+ var plain, crypt [256]byte
for i := 0; i < len(plain); i++ {
plain[i] = byte(255 - i)
}
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for block := 1; block <= 64 && block <= maxio; block *= 2 {
// compute encrypted version
- delta := byte(0);
+ delta := byte(0)
for i := 0; i < len(crypt); i++ {
if i%block == 0 {
delta++
}
- crypt[i] = plain[i] + delta;
+ crypt[i] = plain[i] + delta
}
for mode := 0; mode < len(readers); mode++ {
for frag := 0; frag < 2; frag++ {
- test := fmt.Sprintf("block=%d mode=%d frag=%d maxio=%d", block, mode, frag, maxio);
- c := &IncCipher{block, 0, false};
- b.Reset();
- r := NewECBDecrypter(c, readers[mode](bytes.NewBuffer(crypt[0:maxio])));
+ test := fmt.Sprintf("block=%d mode=%d frag=%d maxio=%d", block, mode, frag, maxio)
+ c := &IncCipher{block, 0, false}
+ b.Reset()
+ r := NewECBDecrypter(c, readers[mode](bytes.NewBuffer(crypt[0:maxio])))
// read from crypt in increasingly large chunks: 1, 1, 2, 4, 8, ...
// if frag == 1, move the 1 to the end to cause fragmentation.
if frag == 0 {
- _, err := io.Copyn(b, r, 1);
+ _, err := io.Copyn(b, r, 1)
if err != nil {
- t.Errorf("%s: first Copyn: %s", test, err);
- continue;
+ t.Errorf("%s: first Copyn: %s", test, err)
+ continue
}
}
for n := 1; n <= maxio/2; n *= 2 {
- _, err := io.Copyn(b, r, int64(n));
+ _, err := io.Copyn(b, r, int64(n))
if err != nil {
t.Errorf("%s: Copyn %d: %s", test, n, err)
}
}
if frag != 0 {
- _, err := io.Copyn(b, r, 1);
+ _, err := io.Copyn(b, r, 1)
if err != nil {
- t.Errorf("%s: last Copyn: %s", test, err);
- continue;
+ t.Errorf("%s: last Copyn: %s", test, err)
+ continue
}
}
// check output
- data := b.Bytes();
+ data := b.Bytes()
if len(data) != maxio {
- t.Errorf("%s: want %d bytes, got %d", test, maxio, len(data));
- continue;
+ t.Errorf("%s: want %d bytes, got %d", test, maxio, len(data))
+ continue
}
if string(data) != string(plain[0:maxio]) {
diff --git a/src/pkg/crypto/block/ofb.go b/src/pkg/crypto/block/ofb.go
index c297541e33..bffdc53db1 100644
--- a/src/pkg/crypto/block/ofb.go
+++ b/src/pkg/crypto/block/ofb.go
@@ -13,28 +13,28 @@
package block
import (
- "io";
+ "io"
)
type ofbStream struct {
- c Cipher;
- iv []byte;
+ c Cipher
+ iv []byte
}
func newOFBStream(c Cipher, iv []byte) *ofbStream {
- x := new(ofbStream);
- x.c = c;
- n := len(iv);
+ x := new(ofbStream)
+ x.c = c
+ n := len(iv)
if n != c.BlockSize() {
panicln("crypto/block: newOFBStream: invalid iv size", n, "!=", c.BlockSize())
}
- x.iv = copy(iv);
- return x;
+ x.iv = copy(iv)
+ return x
}
func (x *ofbStream) Next() []byte {
- x.c.Encrypt(x.iv, x.iv);
- return x.iv;
+ x.c.Encrypt(x.iv, x.iv)
+ return x.iv
}
// NewOFBReader returns a reader that reads data from r, decrypts (or encrypts)
diff --git a/src/pkg/crypto/block/ofb_aes_test.go b/src/pkg/crypto/block/ofb_aes_test.go
index 80af78fe40..f2faa44325 100644
--- a/src/pkg/crypto/block/ofb_aes_test.go
+++ b/src/pkg/crypto/block/ofb_aes_test.go
@@ -11,18 +11,18 @@
package block
import (
- "bytes";
- "crypto/aes";
- "io";
- "testing";
+ "bytes"
+ "crypto/aes"
+ "io"
+ "testing"
)
type ofbTest struct {
- name string;
- key []byte;
- iv []byte;
- in []byte;
- out []byte;
+ name string
+ key []byte
+ iv []byte
+ in []byte
+ out []byte
}
var ofbAESTests = []ofbTest{
@@ -67,20 +67,20 @@ var ofbAESTests = []ofbTest{
func TestOFB_AES(t *testing.T) {
for _, tt := range ofbAESTests {
- test := tt.name;
+ test := tt.name
- c, err := aes.NewCipher(tt.key);
+ c, err := aes.NewCipher(tt.key)
if err != nil {
- t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err);
- continue;
+ t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err)
+ continue
}
for j := 0; j <= 5; j += 5 {
- var crypt bytes.Buffer;
- in := tt.in[0 : len(tt.in)-j];
- w := NewOFBWriter(c, tt.iv, &crypt);
- var r io.Reader = bytes.NewBuffer(in);
- n, err := io.Copy(w, r);
+ var crypt bytes.Buffer
+ in := tt.in[0 : len(tt.in)-j]
+ w := NewOFBWriter(c, tt.iv, &crypt)
+ var r io.Reader = bytes.NewBuffer(in)
+ n, err := io.Copy(w, r)
if n != int64(len(in)) || err != nil {
t.Errorf("%s/%d: OFBWriter io.Copy = %d, %v want %d, nil", test, len(in), n, err, len(in))
} else if d, out := crypt.Bytes(), tt.out[0:len(in)]; !same(out, d) {
@@ -89,11 +89,11 @@ func TestOFB_AES(t *testing.T) {
}
for j := 0; j <= 7; j += 7 {
- var plain bytes.Buffer;
- out := tt.out[0 : len(tt.out)-j];
- r := NewOFBReader(c, tt.iv, bytes.NewBuffer(out));
- w := &plain;
- n, err := io.Copy(w, r);
+ var plain bytes.Buffer
+ out := tt.out[0 : len(tt.out)-j]
+ r := NewOFBReader(c, tt.iv, bytes.NewBuffer(out))
+ w := &plain
+ n, err := io.Copy(w, r)
if n != int64(len(out)) || err != nil {
t.Errorf("%s/%d: OFBReader io.Copy = %d, %v want %d, nil", test, len(out), n, err, len(out))
} else if d, in := plain.Bytes(), tt.in[0:len(out)]; !same(in, d) {
diff --git a/src/pkg/crypto/block/xor.go b/src/pkg/crypto/block/xor.go
index ffb76c5c4a..9d8b172240 100644
--- a/src/pkg/crypto/block/xor.go
+++ b/src/pkg/crypto/block/xor.go
@@ -7,8 +7,8 @@
package block
import (
- "io";
- "os";
+ "io"
+ "os"
)
// A dataStream is an interface to an unending stream of data,
@@ -16,62 +16,62 @@ import (
// Calls to Next() return sequential blocks of data from the stream.
// Each call must return at least one byte: there is no EOF.
type dataStream interface {
- Next() []byte;
+ Next() []byte
}
type xorReader struct {
- r io.Reader;
- rand dataStream; // pseudo-random
- buf []byte; // data available from last call to rand
+ r io.Reader
+ rand dataStream // pseudo-random
+ buf []byte // data available from last call to rand
}
func newXorReader(rand dataStream, r io.Reader) io.Reader {
- x := new(xorReader);
- x.r = r;
- x.rand = rand;
- return x;
+ x := new(xorReader)
+ x.r = r
+ x.rand = rand
+ return x
}
func (x *xorReader) Read(p []byte) (n int, err os.Error) {
- n, err = x.r.Read(p);
+ n, err = x.r.Read(p)
// xor input with stream.
- bp := 0;
- buf := x.buf;
+ bp := 0
+ buf := x.buf
for i := 0; i < n; i++ {
if bp >= len(buf) {
- buf = x.rand.Next();
- bp = 0;
+ buf = x.rand.Next()
+ bp = 0
}
- p[i] ^= buf[bp];
- bp++;
+ p[i] ^= buf[bp]
+ bp++
}
- x.buf = buf[bp:];
- return n, err;
+ x.buf = buf[bp:]
+ return n, err
}
type xorWriter struct {
- w io.Writer;
- rand dataStream; // pseudo-random
- buf []byte; // last buffer returned by rand
- extra []byte; // extra random data (use before buf)
- work []byte; // work space
+ w io.Writer
+ rand dataStream // pseudo-random
+ buf []byte // last buffer returned by rand
+ extra []byte // extra random data (use before buf)
+ work []byte // work space
}
func newXorWriter(rand dataStream, w io.Writer) io.Writer {
- x := new(xorWriter);
- x.w = w;
- x.rand = rand;
- x.work = make([]byte, 4096);
- return x;
+ x := new(xorWriter)
+ x.w = w
+ x.rand = rand
+ x.work = make([]byte, 4096)
+ return x
}
func (x *xorWriter) Write(p []byte) (n int, err os.Error) {
for len(p) > 0 {
// Determine next chunk of random data
// and xor with p into x.work.
- var chunk []byte;
- m := len(p);
+ var chunk []byte
+ m := len(p)
if nn := len(x.extra); nn > 0 {
// extra points into work, so edit directly
if m > nn {
@@ -80,29 +80,29 @@ func (x *xorWriter) Write(p []byte) (n int, err os.Error) {
for i := 0; i < m; i++ {
x.extra[i] ^= p[i]
}
- chunk = x.extra[0:m];
+ chunk = x.extra[0:m]
} else {
// xor p ^ buf into work, refreshing buf as needed
if nn := len(x.work); m > nn {
m = nn
}
- bp := 0;
- buf := x.buf;
+ bp := 0
+ buf := x.buf
for i := 0; i < m; i++ {
if bp >= len(buf) {
- buf = x.rand.Next();
- bp = 0;
+ buf = x.rand.Next()
+ bp = 0
}
- x.work[i] = buf[bp] ^ p[i];
- bp++;
+ x.work[i] = buf[bp] ^ p[i]
+ bp++
}
- x.buf = buf[bp:];
- chunk = x.work[0:m];
+ x.buf = buf[bp:]
+ chunk = x.work[0:m]
}
// Write chunk.
- var nn int;
- nn, err = x.w.Write(chunk);
+ var nn int
+ nn, err = x.w.Write(chunk)
if nn != len(chunk) && err == nil {
err = io.ErrShortWrite
}
@@ -112,13 +112,13 @@ func (x *xorWriter) Write(p []byte) (n int, err os.Error) {
for i := nn; i < m; i++ {
chunk[i] ^= p[i]
}
- x.extra = chunk[nn:];
+ x.extra = chunk[nn:]
}
- n += nn;
+ n += nn
if err != nil {
return
}
- p = p[m:];
+ p = p[m:]
}
- return;
+ return
}
diff --git a/src/pkg/crypto/block/xor_test.go b/src/pkg/crypto/block/xor_test.go
index 1815be3fcb..87b493a405 100644
--- a/src/pkg/crypto/block/xor_test.go
+++ b/src/pkg/crypto/block/xor_test.go
@@ -5,80 +5,80 @@
package block
import (
- "bytes";
- "fmt";
- "io";
- "testing";
- "testing/iotest";
+ "bytes"
+ "fmt"
+ "io"
+ "testing"
+ "testing/iotest"
)
// Simple "pseudo-random" stream for testing.
type incStream struct {
- buf []byte;
- n byte;
+ buf []byte
+ n byte
}
func newIncStream(blockSize int) *incStream {
- x := new(incStream);
- x.buf = make([]byte, blockSize);
- return x;
+ x := new(incStream)
+ x.buf = make([]byte, blockSize)
+ return x
}
func (x *incStream) Next() []byte {
- x.n++;
+ x.n++
for i := range x.buf {
- x.buf[i] = x.n;
- x.n++;
+ x.buf[i] = x.n
+ x.n++
}
- return x.buf;
+ return x.buf
}
func testXorWriter(t *testing.T, maxio int) {
- var plain, crypt [256]byte;
+ var plain, crypt [256]byte
for i := 0; i < len(plain); i++ {
plain[i] = byte(i)
}
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for block := 1; block <= 64 && block <= maxio; block *= 2 {
// compute encrypted version
- n := byte(0);
+ n := byte(0)
for i := 0; i < len(crypt); i++ {
if i%block == 0 {
n++
}
- crypt[i] = plain[i] ^ n;
- n++;
+ crypt[i] = plain[i] ^ n
+ n++
}
for frag := 0; frag < 2; frag++ {
- test := fmt.Sprintf("block=%d frag=%d maxio=%d", block, frag, maxio);
- b.Reset();
- r := bytes.NewBuffer(&plain);
- s := newIncStream(block);
- w := newXorWriter(s, b);
+ test := fmt.Sprintf("block=%d frag=%d maxio=%d", block, frag, maxio)
+ b.Reset()
+ r := bytes.NewBuffer(&plain)
+ s := newIncStream(block)
+ w := newXorWriter(s, b)
// copy plain into w in increasingly large chunks: 1, 1, 2, 4, 8, ...
// if frag != 0, move the 1 to the end to cause fragmentation.
if frag == 0 {
- _, err := io.Copyn(w, r, 1);
+ _, err := io.Copyn(w, r, 1)
if err != nil {
- t.Errorf("%s: first Copyn: %s", test, err);
- continue;
+ t.Errorf("%s: first Copyn: %s", test, err)
+ continue
}
}
for n := 1; n <= len(plain)/2; n *= 2 {
- _, err := io.Copyn(w, r, int64(n));
+ _, err := io.Copyn(w, r, int64(n))
if err != nil {
t.Errorf("%s: Copyn %d: %s", test, n, err)
}
}
// check output
- crypt := crypt[0 : len(crypt)-frag];
- data := b.Bytes();
+ crypt := crypt[0 : len(crypt)-frag]
+ data := b.Bytes()
if len(data) != len(crypt) {
- t.Errorf("%s: want %d bytes, got %d", test, len(crypt), len(data));
- continue;
+ t.Errorf("%s: want %d bytes, got %d", test, len(crypt), len(data))
+ continue
}
if string(data) != string(crypt) {
@@ -101,53 +101,53 @@ func testXorReader(t *testing.T, maxio int) {
func(r io.Reader) io.Reader { return r },
iotest.OneByteReader,
iotest.HalfReader,
- };
- var plain, crypt [256]byte;
+ }
+ var plain, crypt [256]byte
for i := 0; i < len(plain); i++ {
plain[i] = byte(255 - i)
}
- b := new(bytes.Buffer);
+ b := new(bytes.Buffer)
for block := 1; block <= 64 && block <= maxio; block *= 2 {
// compute encrypted version
- n := byte(0);
+ n := byte(0)
for i := 0; i < len(crypt); i++ {
if i%block == 0 {
n++
}
- crypt[i] = plain[i] ^ n;
- n++;
+ crypt[i] = plain[i] ^ n
+ n++
}
for mode := 0; mode < len(readers); mode++ {
for frag := 0; frag < 2; frag++ {
- test := fmt.Sprintf("block=%d mode=%d frag=%d maxio=%d", block, mode, frag, maxio);
- s := newIncStream(block);
- b.Reset();
- r := newXorReader(s, readers[mode](bytes.NewBuffer(crypt[0:maxio])));
+ test := fmt.Sprintf("block=%d mode=%d frag=%d maxio=%d", block, mode, frag, maxio)
+ s := newIncStream(block)
+ b.Reset()
+ r := newXorReader(s, readers[mode](bytes.NewBuffer(crypt[0:maxio])))
// read from crypt in increasingly large chunks: 1, 1, 2, 4, 8, ...
// if frag == 1, move the 1 to the end to cause fragmentation.
if frag == 0 {
- _, err := io.Copyn(b, r, 1);
+ _, err := io.Copyn(b, r, 1)
if err != nil {
- t.Errorf("%s: first Copyn: %s", test, err);
- continue;
+ t.Errorf("%s: first Copyn: %s", test, err)
+ continue
}
}
for n := 1; n <= maxio/2; n *= 2 {
- _, err := io.Copyn(b, r, int64(n));
+ _, err := io.Copyn(b, r, int64(n))
if err != nil {
t.Errorf("%s: Copyn %d: %s", test, n, err)
}
}
// check output
- data := b.Bytes();
- crypt := crypt[0 : maxio-frag];
- plain := plain[0 : maxio-frag];
+ data := b.Bytes()
+ crypt := crypt[0 : maxio-frag]
+ plain := plain[0 : maxio-frag]
if len(data) != len(plain) {
- t.Errorf("%s: want %d bytes, got %d", test, len(plain), len(data));
- continue;
+ t.Errorf("%s: want %d bytes, got %d", test, len(plain), len(data))
+ continue
}
if string(data) != string(plain) {
diff --git a/src/pkg/crypto/hmac/hmac.go b/src/pkg/crypto/hmac/hmac.go
index 8a9a4cbb5f..38d13738de 100644
--- a/src/pkg/crypto/hmac/hmac.go
+++ b/src/pkg/crypto/hmac/hmac.go
@@ -9,10 +9,10 @@
package hmac
import (
- "crypto/md5";
- "crypto/sha1";
- "hash";
- "os";
+ "crypto/md5"
+ "crypto/sha1"
+ "hash"
+ "os"
)
// FIPS 198:
@@ -30,14 +30,14 @@ const (
// MD5 and SHA1, and both use 64-byte blocks.
// The hash.Hash interface doesn't provide a
// way to find out the block size.
- padSize = 64;
+ padSize = 64
)
type hmac struct {
- size int;
- key []byte;
- tmp []byte;
- inner hash.Hash;
+ size int
+ key []byte
+ tmp []byte
+ inner hash.Hash
}
func (h *hmac) tmpPad(xor byte) {
@@ -50,49 +50,49 @@ func (h *hmac) tmpPad(xor byte) {
}
func (h *hmac) Sum() []byte {
- h.tmpPad(0x5c);
- sum := h.inner.Sum();
+ h.tmpPad(0x5c)
+ sum := h.inner.Sum()
for i, b := range sum {
h.tmp[padSize+i] = b
}
- h.inner.Reset();
- h.inner.Write(h.tmp);
- return h.inner.Sum();
+ h.inner.Reset()
+ h.inner.Write(h.tmp)
+ return h.inner.Sum()
}
func (h *hmac) Write(p []byte) (n int, err os.Error) {
return h.inner.Write(p)
}
-func (h *hmac) Size() int { return h.size }
+func (h *hmac) Size() int { return h.size }
func (h *hmac) Reset() {
- h.inner.Reset();
- h.tmpPad(0x36);
- h.inner.Write(h.tmp[0:padSize]);
+ h.inner.Reset()
+ h.tmpPad(0x36)
+ h.inner.Write(h.tmp[0:padSize])
}
// New returns a new HMAC hash using the given hash and key.
func New(h hash.Hash, key []byte) hash.Hash {
if len(key) > padSize {
// If key is too big, hash it.
- h.Write(key);
- key = h.Sum();
+ h.Write(key)
+ key = h.Sum()
}
- hm := new(hmac);
- hm.inner = h;
- hm.size = h.Size();
- hm.key = make([]byte, len(key));
+ hm := new(hmac)
+ hm.inner = h
+ hm.size = h.Size()
+ hm.key = make([]byte, len(key))
for i, k := range key {
hm.key[i] = k
}
- hm.tmp = make([]byte, padSize+hm.size);
- hm.Reset();
- return hm;
+ hm.tmp = make([]byte, padSize+hm.size)
+ hm.Reset()
+ return hm
}
// NewMD5 returns a new HMAC-MD5 hash using the given key.
-func NewMD5(key []byte) hash.Hash { return New(md5.New(), key) }
+func NewMD5(key []byte) hash.Hash { return New(md5.New(), key) }
// NewSHA1 returns a new HMAC-SHA1 hash using the given key.
-func NewSHA1(key []byte) hash.Hash { return New(sha1.New(), key) }
+func NewSHA1(key []byte) hash.Hash { return New(sha1.New(), key) }
diff --git a/src/pkg/crypto/hmac/hmac_test.go b/src/pkg/crypto/hmac/hmac_test.go
index 1c81fd9906..98e32df016 100644
--- a/src/pkg/crypto/hmac/hmac_test.go
+++ b/src/pkg/crypto/hmac/hmac_test.go
@@ -5,17 +5,17 @@
package hmac
import (
- "hash";
- "fmt";
- "strings";
- "testing";
+ "hash"
+ "fmt"
+ "strings"
+ "testing"
)
type hmacTest struct {
- hash func([]byte) hash.Hash;
- key []byte;
- in []byte;
- out string;
+ hash func([]byte) hash.Hash
+ key []byte
+ in []byte
+ out string
}
// Tests from US FIPS 198
@@ -78,20 +78,20 @@ var hmacTests = []hmacTest{
func TestHMAC(t *testing.T) {
for i, tt := range hmacTests {
- h := tt.hash(tt.key);
+ h := tt.hash(tt.key)
for j := 0; j < 2; j++ {
- n, err := h.Write(tt.in);
+ n, err := h.Write(tt.in)
if n != len(tt.in) || err != nil {
- t.Errorf("test %d.%d: Write(%d) = %d, %v", i, j, len(tt.in), n, err);
- continue;
+ t.Errorf("test %d.%d: Write(%d) = %d, %v", i, j, len(tt.in), n, err)
+ continue
}
- sum := fmt.Sprintf("%x", h.Sum());
+ sum := fmt.Sprintf("%x", h.Sum())
if sum != tt.out {
t.Errorf("test %d.%d: have %s want %s\n", i, j, sum, tt.out)
}
// Second iteration: make sure reset works.
- h.Reset();
+ h.Reset()
}
}
}
diff --git a/src/pkg/crypto/md4/md4.go b/src/pkg/crypto/md4/md4.go
index 8efb74e475..650fce313f 100644
--- a/src/pkg/crypto/md4/md4.go
+++ b/src/pkg/crypto/md4/md4.go
@@ -6,81 +6,81 @@
package md4
import (
- "hash";
- "os";
+ "hash"
+ "os"
)
// The size of an MD4 checksum in bytes.
const Size = 16
const (
- _Chunk = 64;
- _Init0 = 0x67452301;
- _Init1 = 0xEFCDAB89;
- _Init2 = 0x98BADCFE;
- _Init3 = 0x10325476;
+ _Chunk = 64
+ _Init0 = 0x67452301
+ _Init1 = 0xEFCDAB89
+ _Init2 = 0x98BADCFE
+ _Init3 = 0x10325476
)
// digest represents the partial evaluation of a checksum.
type digest struct {
- s [4]uint32;
- x [_Chunk]byte;
- nx int;
- len uint64;
+ s [4]uint32
+ x [_Chunk]byte
+ nx int
+ len uint64
}
func (d *digest) Reset() {
- d.s[0] = _Init0;
- d.s[1] = _Init1;
- d.s[2] = _Init2;
- d.s[3] = _Init3;
- d.nx = 0;
- d.len = 0;
+ d.s[0] = _Init0
+ d.s[1] = _Init1
+ d.s[2] = _Init2
+ d.s[3] = _Init3
+ d.nx = 0
+ d.len = 0
}
// New returns a new hash.Hash computing the MD4 checksum.
func New() hash.Hash {
- d := new(digest);
- d.Reset();
- return d;
+ d := new(digest)
+ d.Reset()
+ return d
}
-func (d *digest) Size() int { return Size }
+func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) {
- nn = len(p);
- d.len += uint64(nn);
+ nn = len(p)
+ d.len += uint64(nn)
if d.nx > 0 {
- n := len(p);
+ n := len(p)
if n > _Chunk-d.nx {
n = _Chunk - d.nx
}
for i := 0; i < n; i++ {
d.x[d.nx+i] = p[i]
}
- d.nx += n;
+ d.nx += n
if d.nx == _Chunk {
- _Block(d, &d.x);
- d.nx = 0;
+ _Block(d, &d.x)
+ d.nx = 0
}
- p = p[n:];
+ p = p[n:]
}
- n := _Block(d, p);
- p = p[n:];
+ n := _Block(d, p)
+ p = p[n:]
if len(p) > 0 {
for i := 0; i < len(p); i++ {
d.x[i] = p[i]
}
- d.nx = len(p);
+ d.nx = len(p)
}
- return;
+ return
}
func (d *digest) Sum() []byte {
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
- len := d.len;
- var tmp [64]byte;
- tmp[0] = 0x80;
+ len := d.len
+ var tmp [64]byte
+ tmp[0] = 0x80
if len%64 < 56 {
d.Write(tmp[0 : 56-len%64])
} else {
@@ -88,28 +88,28 @@ func (d *digest) Sum() []byte {
}
// Length in bits.
- len <<= 3;
+ len <<= 3
for i := uint(0); i < 8; i++ {
tmp[i] = byte(len >> (8 * i))
}
- d.Write(tmp[0:8]);
+ d.Write(tmp[0:8])
if d.nx != 0 {
panicln("oops")
}
- p := make([]byte, 16);
- j := 0;
+ p := make([]byte, 16)
+ j := 0
for i := 0; i < 4; i++ {
- s := d.s[i];
- p[j] = byte(s);
- j++;
- p[j] = byte(s >> 8);
- j++;
- p[j] = byte(s >> 16);
- j++;
- p[j] = byte(s >> 24);
- j++;
+ s := d.s[i]
+ p[j] = byte(s)
+ j++
+ p[j] = byte(s >> 8)
+ j++
+ p[j] = byte(s >> 16)
+ j++
+ p[j] = byte(s >> 24)
+ j++
}
- return p;
+ return p
}
diff --git a/src/pkg/crypto/md4/md4_test.go b/src/pkg/crypto/md4/md4_test.go
index 31aa67527f..9cab80c63e 100644
--- a/src/pkg/crypto/md4/md4_test.go
+++ b/src/pkg/crypto/md4/md4_test.go
@@ -5,14 +5,14 @@
package md4
import (
- "fmt";
- "io";
- "testing";
+ "fmt"
+ "io"
+ "testing"
)
type md4Test struct {
- out string;
- in string;
+ out string
+ in string
}
var golden = []md4Test{
@@ -51,16 +51,16 @@ var golden = []md4Test{
func TestGolden(t *testing.T) {
for i := 0; i < len(golden); i++ {
- g := golden[i];
- c := New();
+ g := golden[i]
+ c := New()
for j := 0; j < 2; j++ {
- io.WriteString(c, g.in);
- s := fmt.Sprintf("%x", c.Sum());
+ io.WriteString(c, g.in)
+ s := fmt.Sprintf("%x", c.Sum())
if s != g.out {
- t.Errorf("md4[%d](%s) = %s want %s", j, g.in, s, g.out);
- t.FailNow();
+ t.Errorf("md4[%d](%s) = %s want %s", j, g.in, s, g.out)
+ t.FailNow()
}
- c.Reset();
+ c.Reset()
}
}
}
diff --git a/src/pkg/crypto/md4/md4block.go b/src/pkg/crypto/md4/md4block.go
index 6f2c2d5a2e..492e960cae 100644
--- a/src/pkg/crypto/md4/md4block.go
+++ b/src/pkg/crypto/md4/md4block.go
@@ -16,18 +16,18 @@ var xIndex2 = []uint{0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15}
var xIndex3 = []uint{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}
func _Block(dig *digest, p []byte) int {
- a := dig.s[0];
- b := dig.s[1];
- c := dig.s[2];
- d := dig.s[3];
- n := 0;
- var X [16]uint32;
+ a := dig.s[0]
+ b := dig.s[1]
+ c := dig.s[2]
+ d := dig.s[3]
+ n := 0
+ var X [16]uint32
for len(p) >= _Chunk {
- aa, bb, cc, dd := a, b, c, d;
+ aa, bb, cc, dd := a, b, c, d
for i := 0; i < 16; i++ {
- j := i * 4;
- X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24;
+ j := i * 4
+ X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24
}
// If this needs to be made faster in the future,
@@ -40,46 +40,46 @@ func _Block(dig *digest, p []byte) int {
// Round 1.
for i := 0; i < 16; i++ {
- x := i;
- s := shift1[i%4];
- f := ((c ^ d) & b) ^ d;
- a += f + X[x];
- a = a<<s | a>>(32-s);
- a, b, c, d = d, a, b, c;
+ x := i
+ s := shift1[i%4]
+ f := ((c ^ d) & b) ^ d
+ a += f + X[x]
+ a = a<<s | a>>(32-s)
+ a, b, c, d = d, a, b, c
}
// Round 2.
for i := 0; i < 16; i++ {
- x := xIndex2[i];
- s := shift2[i%4];
- g := (b & c) | (b & d) | (c & d);
- a += g + X[x] + 0x5a827999;
- a = a<<s | a>>(32-s);
- a, b, c, d = d, a, b, c;
+ x := xIndex2[i]
+ s := shift2[i%4]
+ g := (b & c) | (b & d) | (c & d)
+ a += g + X[x] + 0x5a827999
+ a = a<<s | a>>(32-s)
+ a, b, c, d = d, a, b, c
}
// Round 3.
for i := 0; i < 16; i++ {
- x := xIndex3[i];
- s := shift3[i%4];
- h := b ^ c ^ d;
- a += h + X[x] + 0x6ed9eba1;
- a = a<<s | a>>(32-s);
- a, b, c, d = d, a, b, c;
+ x := xIndex3[i]
+ s := shift3[i%4]
+ h := b ^ c ^ d
+ a += h + X[x] + 0x6ed9eba1
+ a = a<<s | a>>(32-s)
+ a, b, c, d = d, a, b, c
}
- a += aa;
- b += bb;
- c += cc;
- d += dd;
+ a += aa
+ b += bb
+ c += cc
+ d += dd
- p = p[_Chunk:];
- n += _Chunk;
+ p = p[_Chunk:]
+ n += _Chunk
}
- dig.s[0] = a;
- dig.s[1] = b;
- dig.s[2] = c;
- dig.s[3] = d;
- return n;
+ dig.s[0] = a
+ dig.s[1] = b
+ dig.s[2] = c
+ dig.s[3] = d
+ return n
}
diff --git a/src/pkg/crypto/md5/md5.go b/src/pkg/crypto/md5/md5.go
index 3752886915..2ee57f4214 100644
--- a/src/pkg/crypto/md5/md5.go
+++ b/src/pkg/crypto/md5/md5.go
@@ -6,81 +6,81 @@
package md5
import (
- "hash";
- "os";
+ "hash"
+ "os"
)
// The size of an MD5 checksum in bytes.
const Size = 16
const (
- _Chunk = 64;
- _Init0 = 0x67452301;
- _Init1 = 0xEFCDAB89;
- _Init2 = 0x98BADCFE;
- _Init3 = 0x10325476;
+ _Chunk = 64
+ _Init0 = 0x67452301
+ _Init1 = 0xEFCDAB89
+ _Init2 = 0x98BADCFE
+ _Init3 = 0x10325476
)
// digest represents the partial evaluation of a checksum.
type digest struct {
- s [4]uint32;
- x [_Chunk]byte;
- nx int;
- len uint64;
+ s [4]uint32
+ x [_Chunk]byte
+ nx int
+ len uint64
}
func (d *digest) Reset() {
- d.s[0] = _Init0;
- d.s[1] = _Init1;
- d.s[2] = _Init2;
- d.s[3] = _Init3;
- d.nx = 0;
- d.len = 0;
+ d.s[0] = _Init0
+ d.s[1] = _Init1
+ d.s[2] = _Init2
+ d.s[3] = _Init3
+ d.nx = 0
+ d.len = 0
}
// New returns a new hash.Hash computing the MD5 checksum.
func New() hash.Hash {
- d := new(digest);
- d.Reset();
- return d;
+ d := new(digest)
+ d.Reset()
+ return d
}
-func (d *digest) Size() int { return Size }
+func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) {
- nn = len(p);
- d.len += uint64(nn);
+ nn = len(p)
+ d.len += uint64(nn)
if d.nx > 0 {
- n := len(p);
+ n := len(p)
if n > _Chunk-d.nx {
n = _Chunk - d.nx
}
for i := 0; i < n; i++ {
d.x[d.nx+i] = p[i]
}
- d.nx += n;
+ d.nx += n
if d.nx == _Chunk {
- _Block(d, &d.x);
- d.nx = 0;
+ _Block(d, &d.x)
+ d.nx = 0
}
- p = p[n:];
+ p = p[n:]
}
- n := _Block(d, p);
- p = p[n:];
+ n := _Block(d, p)
+ p = p[n:]
if len(p) > 0 {
for i := 0; i < len(p); i++ {
d.x[i] = p[i]
}
- d.nx = len(p);
+ d.nx = len(p)
}
- return;
+ return
}
func (d *digest) Sum() []byte {
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
- len := d.len;
- var tmp [64]byte;
- tmp[0] = 0x80;
+ len := d.len
+ var tmp [64]byte
+ tmp[0] = 0x80
if len%64 < 56 {
d.Write(tmp[0 : 56-len%64])
} else {
@@ -88,28 +88,28 @@ func (d *digest) Sum() []byte {
}
// Length in bits.
- len <<= 3;
+ len <<= 3
for i := uint(0); i < 8; i++ {
tmp[i] = byte(len >> (8 * i))
}
- d.Write(tmp[0:8]);
+ d.Write(tmp[0:8])
if d.nx != 0 {
panicln("oops")
}
- p := make([]byte, 16);
- j := 0;
+ p := make([]byte, 16)
+ j := 0
for i := 0; i < 4; i++ {
- s := d.s[i];
- p[j] = byte(s);
- j++;
- p[j] = byte(s >> 8);
- j++;
- p[j] = byte(s >> 16);
- j++;
- p[j] = byte(s >> 24);
- j++;
+ s := d.s[i]
+ p[j] = byte(s)
+ j++
+ p[j] = byte(s >> 8)
+ j++
+ p[j] = byte(s >> 16)
+ j++
+ p[j] = byte(s >> 24)
+ j++
}
- return p;
+ return p
}
diff --git a/src/pkg/crypto/md5/md5_test.go b/src/pkg/crypto/md5/md5_test.go
index 51fd5a53af..7d5737b267 100644
--- a/src/pkg/crypto/md5/md5_test.go
+++ b/src/pkg/crypto/md5/md5_test.go
@@ -5,14 +5,14 @@
package md5
import (
- "fmt";
- "io";
- "testing";
+ "fmt"
+ "io"
+ "testing"
)
type md5Test struct {
- out string;
- in string;
+ out string
+ in string
}
var golden = []md5Test{
@@ -51,16 +51,16 @@ var golden = []md5Test{
func TestGolden(t *testing.T) {
for i := 0; i < len(golden); i++ {
- g := golden[i];
- c := New();
+ g := golden[i]
+ c := New()
for j := 0; j < 2; j++ {
- io.WriteString(c, g.in);
- s := fmt.Sprintf("%x", c.Sum());
+ io.WriteString(c, g.in)
+ s := fmt.Sprintf("%x", c.Sum())
if s != g.out {
- t.Errorf("md5[%d](%s) = %s want %s", j, g.in, s, g.out);
- t.FailNow();
+ t.Errorf("md5[%d](%s) = %s want %s", j, g.in, s, g.out)
+ t.FailNow()
}
- c.Reset();
+ c.Reset()
}
}
}
diff --git a/src/pkg/crypto/md5/md5block.go b/src/pkg/crypto/md5/md5block.go
index 4421acf8ec..f35096d50c 100644
--- a/src/pkg/crypto/md5/md5block.go
+++ b/src/pkg/crypto/md5/md5block.go
@@ -89,18 +89,18 @@ var shift3 = []uint{4, 11, 16, 23}
var shift4 = []uint{6, 10, 15, 21}
func _Block(dig *digest, p []byte) int {
- a := dig.s[0];
- b := dig.s[1];
- c := dig.s[2];
- d := dig.s[3];
- n := 0;
- var X [16]uint32;
+ a := dig.s[0]
+ b := dig.s[1]
+ c := dig.s[2]
+ d := dig.s[3]
+ n := 0
+ var X [16]uint32
for len(p) >= _Chunk {
- aa, bb, cc, dd := a, b, c, d;
+ aa, bb, cc, dd := a, b, c, d
for i := 0; i < 16; i++ {
- j := i * 4;
- X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24;
+ j := i * 4
+ X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24
}
// If this needs to be made faster in the future,
@@ -113,64 +113,64 @@ func _Block(dig *digest, p []byte) int {
// Round 1.
for i := 0; i < 16; i++ {
- x := i;
- t := i;
- s := shift1[i%4];
- f := ((c ^ d) & b) ^ d;
- a += f + X[x] + table[t];
- a = a<<s | a>>(32-s);
- a += b;
- a, b, c, d = d, a, b, c;
+ x := i
+ t := i
+ s := shift1[i%4]
+ f := ((c ^ d) & b) ^ d
+ a += f + X[x] + table[t]
+ a = a<<s | a>>(32-s)
+ a += b
+ a, b, c, d = d, a, b, c
}
// Round 2.
for i := 0; i < 16; i++ {
- x := (1 + 5*i) % 16;
- t := 16 + i;
- s := shift2[i%4];
- g := ((b ^ c) & d) ^ c;
- a += g + X[x] + table[t];
- a = a<<s | a>>(32-s);
- a += b;
- a, b, c, d = d, a, b, c;
+ x := (1 + 5*i) % 16
+ t := 16 + i
+ s := shift2[i%4]
+ g := ((b ^ c) & d) ^ c
+ a += g + X[x] + table[t]
+ a = a<<s | a>>(32-s)
+ a += b
+ a, b, c, d = d, a, b, c
}
// Round 3.
for i := 0; i < 16; i++ {
- x := (5 + 3*i) % 16;
- t := 32 + i;
- s := shift3[i%4];
- h := b ^ c ^ d;
- a += h + X[x] + table[t];
- a = a<<s | a>>(32-s);
- a += b;
- a, b, c, d = d, a, b, c;
+ x := (5 + 3*i) % 16
+ t := 32 + i
+ s := shift3[i%4]
+ h := b ^ c ^ d
+ a += h + X[x] + table[t]
+ a = a<<s | a>>(32-s)
+ a += b
+ a, b, c, d = d, a, b, c
}
// Round 4.
for i := 0; i < 16; i++ {
- x := (7 * i) % 16;
- s := shift4[i%4];
- t := 48 + i;
- ii := c ^ (b | ^d);
- a += ii + X[x] + table[t];
- a = a<<s | a>>(32-s);
- a += b;
- a, b, c, d = d, a, b, c;
+ x := (7 * i) % 16
+ s := shift4[i%4]
+ t := 48 + i
+ ii := c ^ (b | ^d)
+ a += ii + X[x] + table[t]
+ a = a<<s | a>>(32-s)
+ a += b
+ a, b, c, d = d, a, b, c
}
- a += aa;
- b += bb;
- c += cc;
- d += dd;
+ a += aa
+ b += bb
+ c += cc
+ d += dd
- p = p[_Chunk:];
- n += _Chunk;
+ p = p[_Chunk:]
+ n += _Chunk
}
- dig.s[0] = a;
- dig.s[1] = b;
- dig.s[2] = c;
- dig.s[3] = d;
- return n;
+ dig.s[0] = a
+ dig.s[1] = b
+ dig.s[2] = c
+ dig.s[3] = d
+ return n
}
diff --git a/src/pkg/crypto/rc4/rc4.go b/src/pkg/crypto/rc4/rc4.go
index d965f827bd..e47a015138 100644
--- a/src/pkg/crypto/rc4/rc4.go
+++ b/src/pkg/crypto/rc4/rc4.go
@@ -10,14 +10,14 @@ package rc4
// it a poor choice for new protocols.
import (
- "os";
- "strconv";
+ "os"
+ "strconv"
)
// A Cipher is an instance of RC4 using a particular key.
type Cipher struct {
- s [256]byte;
- i, j uint8;
+ s [256]byte
+ i, j uint8
}
type KeySizeError int
@@ -29,30 +29,30 @@ func (k KeySizeError) String() string {
// NewCipher creates and returns a new Cipher. The key argument should be the
// RC4 key, at least 1 byte and at most 256 bytes.
func NewCipher(key []byte) (*Cipher, os.Error) {
- k := len(key);
+ k := len(key)
if k < 1 || k > 256 {
return nil, KeySizeError(k)
}
- var c Cipher;
+ var c Cipher
for i := 0; i < 256; i++ {
c.s[i] = uint8(i)
}
- var j uint8 = 0;
+ var j uint8 = 0
for i := 0; i < 256; i++ {
- j += c.s[i] + key[i%k];
- c.s[i], c.s[j] = c.s[j], c.s[i];
+ j += c.s[i] + key[i%k]
+ c.s[i], c.s[j] = c.s[j], c.s[i]
}
- return &c, nil;
+ return &c, nil
}
// XORKeyStream will XOR each byte of the given buffer with a byte of the
// generated keystream.
func (c *Cipher) XORKeyStream(buf []byte) {
for i := range buf {
- c.i += 1;
- c.j += c.s[c.i];
- c.s[c.i], c.s[c.j] = c.s[c.j], c.s[c.i];
- buf[i] ^= c.s[c.s[c.i]+c.s[c.j]];
+ c.i += 1
+ c.j += c.s[c.i]
+ c.s[c.i], c.s[c.j] = c.s[c.j], c.s[c.i]
+ buf[i] ^= c.s[c.s[c.i]+c.s[c.j]]
}
}
@@ -62,5 +62,5 @@ func (c *Cipher) Reset() {
for i := range c.s {
c.s[i] = 0
}
- c.i, c.j = 0, 0;
+ c.i, c.j = 0, 0
}
diff --git a/src/pkg/crypto/rc4/rc4_test.go b/src/pkg/crypto/rc4/rc4_test.go
index e0ca4a4ae6..1d39b2f177 100644
--- a/src/pkg/crypto/rc4/rc4_test.go
+++ b/src/pkg/crypto/rc4/rc4_test.go
@@ -5,11 +5,11 @@
package rc4
import (
- "testing";
+ "testing"
)
type rc4Test struct {
- key, keystream []byte;
+ key, keystream []byte
}
var golden = []rc4Test{
@@ -41,18 +41,18 @@ var golden = []rc4Test{
func TestGolden(t *testing.T) {
for i := 0; i < len(golden); i++ {
- g := golden[i];
- c, err := NewCipher(g.key);
+ g := golden[i]
+ c, err := NewCipher(g.key)
if err != nil {
- t.Errorf("Failed to create cipher at golden index %d", i);
- return;
+ t.Errorf("Failed to create cipher at golden index %d", i)
+ return
}
- keystream := make([]byte, len(g.keystream));
- c.XORKeyStream(keystream);
+ keystream := make([]byte, len(g.keystream))
+ c.XORKeyStream(keystream)
for j, v := range keystream {
if g.keystream[j] != v {
- t.Errorf("Failed at golden index %d", i);
- break;
+ t.Errorf("Failed at golden index %d", i)
+ break
}
}
}
diff --git a/src/pkg/crypto/rsa/pkcs1v15.go b/src/pkg/crypto/rsa/pkcs1v15.go
index 9dbc20f296..cfad954544 100644
--- a/src/pkg/crypto/rsa/pkcs1v15.go
+++ b/src/pkg/crypto/rsa/pkcs1v15.go
@@ -5,10 +5,10 @@
package rsa
import (
- "big";
- "crypto/subtle";
- "io";
- "os";
+ "big"
+ "crypto/subtle"
+ "io"
+ "os"
)
// This file implements encryption and decryption using PKCS#1 v1.5 padding.
@@ -18,38 +18,38 @@ import (
// WARNING: use of this function to encrypt plaintexts other than session keys
// is dangerous. Use RSA OAEP in new protocols.
func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err os.Error) {
- k := (pub.N.Len() + 7) / 8;
+ k := (pub.N.Len() + 7) / 8
if len(msg) > k-11 {
- err = MessageTooLongError{};
- return;
+ err = MessageTooLongError{}
+ return
}
// EM = 0x02 || PS || 0x00 || M
- em := make([]byte, k-1);
- em[0] = 2;
- ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):];
- err = nonZeroRandomBytes(ps, rand);
+ em := make([]byte, k-1)
+ em[0] = 2
+ ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):]
+ err = nonZeroRandomBytes(ps, rand)
if err != nil {
return
}
- em[len(em)-len(msg)-1] = 0;
- copy(mm, msg);
+ em[len(em)-len(msg)-1] = 0
+ copy(mm, msg)
- m := new(big.Int).SetBytes(em);
- c := encrypt(new(big.Int), pub, m);
- out = c.Bytes();
- return;
+ m := new(big.Int).SetBytes(em)
+ c := encrypt(new(big.Int), pub, m)
+ out = c.Bytes()
+ return
}
// DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err os.Error) {
- valid, out, err := decryptPKCS1v15(rand, priv, ciphertext);
+ valid, out, err := decryptPKCS1v15(rand, priv, ciphertext)
if err == nil && valid == 0 {
err = DecryptionError{}
}
- return;
+ return
}
// DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5.
@@ -66,74 +66,74 @@ func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out [
// Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
// (Crypto '98),
func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err os.Error) {
- k := (priv.N.Len() + 7) / 8;
+ k := (priv.N.Len() + 7) / 8
if k-(len(key)+3+8) < 0 {
- err = DecryptionError{};
- return;
+ err = DecryptionError{}
+ return
}
- valid, msg, err := decryptPKCS1v15(rand, priv, ciphertext);
+ valid, msg, err := decryptPKCS1v15(rand, priv, ciphertext)
if err != nil {
return
}
- valid &= subtle.ConstantTimeEq(int32(len(msg)), int32(len(key)));
- subtle.ConstantTimeCopy(valid, key, msg);
- return;
+ valid &= subtle.ConstantTimeEq(int32(len(msg)), int32(len(key)))
+ subtle.ConstantTimeCopy(valid, key, msg)
+ return
}
func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, msg []byte, err os.Error) {
- k := (priv.N.Len() + 7) / 8;
+ k := (priv.N.Len() + 7) / 8
if k < 11 {
- err = DecryptionError{};
- return;
+ err = DecryptionError{}
+ return
}
- c := new(big.Int).SetBytes(ciphertext);
- m, err := decrypt(rand, priv, c);
+ c := new(big.Int).SetBytes(ciphertext)
+ m, err := decrypt(rand, priv, c)
if err != nil {
return
}
- em := leftPad(m.Bytes(), k);
- firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0);
- secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2);
+ em := leftPad(m.Bytes(), k)
+ firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
+ secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2)
// The remainder of the plaintext must be a string of non-zero random
// octets, followed by a 0, followed by the message.
// lookingForIndex: 1 iff we are still looking for the zero.
// index: the offset of the first zero byte.
- var lookingForIndex, index int;
- lookingForIndex = 1;
+ var lookingForIndex, index int
+ lookingForIndex = 1
for i := 2; i < len(em); i++ {
- equals0 := subtle.ConstantTimeByteEq(em[i], 0);
- index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index);
- lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex);
+ equals0 := subtle.ConstantTimeByteEq(em[i], 0)
+ index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index)
+ lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex)
}
- valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1);
- msg = em[index+1:];
- return;
+ valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1)
+ msg = em[index+1:]
+ return
}
// nonZeroRandomBytes fills the given slice with non-zero random octets.
func nonZeroRandomBytes(s []byte, rand io.Reader) (err os.Error) {
- _, err = io.ReadFull(rand, s);
+ _, err = io.ReadFull(rand, s)
if err != nil {
return
}
for i := 0; i < len(s); i++ {
for s[i] == 0 {
- _, err = rand.Read(s[i : i+1]);
+ _, err = rand.Read(s[i : i+1])
if err != nil {
return
}
}
}
- return;
+ return
}
// Due to the design of PKCS#1 v1.5, we need to know the exact hash function in
@@ -141,11 +141,11 @@ func nonZeroRandomBytes(s []byte, rand io.Reader) (err os.Error) {
type PKCS1v15Hash int
const (
- HashMD5 PKCS1v15Hash = iota;
- HashSHA1;
- HashSHA256;
- HashSHA384;
- HashSHA512;
+ HashMD5 PKCS1v15Hash = iota
+ HashSHA1
+ HashSHA256
+ HashSHA384
+ HashSHA512
)
// These are ASN1 DER structures:
@@ -173,32 +173,32 @@ var hashPrefixes = [][]byte{
// Note that hashed must be the result of hashing the input message using the
// given hash function.
func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash PKCS1v15Hash, hashed []byte) (s []byte, err os.Error) {
- hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed));
+ hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
if err != nil {
return
}
- tLen := len(prefix) + hashLen;
- k := (priv.N.Len() + 7) / 8;
+ tLen := len(prefix) + hashLen
+ k := (priv.N.Len() + 7) / 8
if k < tLen+11 {
return nil, MessageTooLongError{}
}
// EM = 0x00 || 0x01 || PS || 0x00 || T
- em := make([]byte, k);
- em[1] = 1;
+ em := make([]byte, k)
+ em[1] = 1
for i := 2; i < k-tLen-1; i++ {
em[i] = 0xff
}
- copy(em[k-tLen:k-hashLen], prefix);
- copy(em[k-hashLen:k], hashed);
+ copy(em[k-tLen:k-hashLen], prefix)
+ copy(em[k-hashLen:k], hashed)
- m := new(big.Int).SetBytes(em);
- c, err := decrypt(rand, priv, m);
+ m := new(big.Int).SetBytes(em)
+ c, err := decrypt(rand, priv, m)
if err == nil {
s = c.Bytes()
}
- return;
+ return
}
// VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature.
@@ -206,28 +206,28 @@ func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash PKCS1v15Hash, hashed []
// function and sig is the signature. A valid signature is indicated by
// returning a nil error.
func VerifyPKCS1v15(pub *PublicKey, hash PKCS1v15Hash, hashed []byte, sig []byte) (err os.Error) {
- hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed));
+ hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
if err != nil {
return
}
- tLen := len(prefix) + hashLen;
- k := (pub.N.Len() + 7) / 8;
+ tLen := len(prefix) + hashLen
+ k := (pub.N.Len() + 7) / 8
if k < tLen+11 {
- err = VerificationError{};
- return;
+ err = VerificationError{}
+ return
}
- c := new(big.Int).SetBytes(sig);
- m := encrypt(new(big.Int), pub, c);
- em := leftPad(m.Bytes(), k);
+ c := new(big.Int).SetBytes(sig)
+ m := encrypt(new(big.Int), pub, c)
+ em := leftPad(m.Bytes(), k)
// EM = 0x00 || 0x01 || PS || 0x00 || T
- ok := subtle.ConstantTimeByteEq(em[0], 0);
- ok &= subtle.ConstantTimeByteEq(em[1], 1);
- ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed);
- ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix);
- ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0);
+ ok := subtle.ConstantTimeByteEq(em[0], 0)
+ ok &= subtle.ConstantTimeByteEq(em[1], 1)
+ ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed)
+ ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix)
+ ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0)
for i := 2; i < k-tLen-1; i++ {
ok &= subtle.ConstantTimeByteEq(em[i], 0xff)
@@ -237,7 +237,7 @@ func VerifyPKCS1v15(pub *PublicKey, hash PKCS1v15Hash, hashed []byte, sig []byte
return VerificationError{}
}
- return nil;
+ return nil
}
func pkcs1v15HashInfo(hash PKCS1v15Hash, inLen int) (hashLen int, prefix []byte, err os.Error) {
@@ -260,6 +260,6 @@ func pkcs1v15HashInfo(hash PKCS1v15Hash, inLen int) (hashLen int, prefix []byte,
return 0, nil, os.ErrorString("input must be hashed message")
}
- prefix = hashPrefixes[int(hash)];
- return;
+ prefix = hashPrefixes[int(hash)]
+ return
}
diff --git a/src/pkg/crypto/rsa/pkcs1v15_test.go b/src/pkg/crypto/rsa/pkcs1v15_test.go
index 4d62deac14..6bdd648765 100644
--- a/src/pkg/crypto/rsa/pkcs1v15_test.go
+++ b/src/pkg/crypto/rsa/pkcs1v15_test.go
@@ -5,29 +5,29 @@
package rsa
import (
- "big";
- "bytes";
- "crypto/sha1";
- "encoding/base64";
- "encoding/hex";
- "os";
- "io";
- "strings";
- "testing";
- "testing/quick";
+ "big"
+ "bytes"
+ "crypto/sha1"
+ "encoding/base64"
+ "encoding/hex"
+ "os"
+ "io"
+ "strings"
+ "testing"
+ "testing/quick"
)
func decodeBase64(in string) []byte {
- out := make([]byte, base64.StdEncoding.DecodedLen(len(in)));
- n, err := base64.StdEncoding.Decode(out, strings.Bytes(in));
+ out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
+ n, err := base64.StdEncoding.Decode(out, strings.Bytes(in))
if err != nil {
return nil
}
- return out[0:n];
+ return out[0:n]
}
type DecryptPKCS1v15Test struct {
- in, out string;
+ in, out string
}
// These test vectors were generated with `openssl rsautl -pkcs -encrypt`
@@ -52,11 +52,11 @@ var decryptPKCS1v15Tests = []DecryptPKCS1v15Test{
func TestDecryptPKCS1v15(t *testing.T) {
for i, test := range decryptPKCS1v15Tests {
- out, err := DecryptPKCS1v15(nil, rsaPrivateKey, decodeBase64(test.in));
+ out, err := DecryptPKCS1v15(nil, rsaPrivateKey, decodeBase64(test.in))
if err != nil {
t.Errorf("#%d error decrypting", i)
}
- want := strings.Bytes(test.out);
+ want := strings.Bytes(test.out)
if bytes.Compare(out, want) != 0 {
t.Errorf("#%d got:%#v want:%#v", i, out, want)
}
@@ -64,43 +64,43 @@ func TestDecryptPKCS1v15(t *testing.T) {
}
func TestEncryptPKCS1v15(t *testing.T) {
- urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0);
+ urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
if err != nil {
t.Errorf("Failed to open /dev/urandom")
}
- k := (rsaPrivateKey.N.Len() + 7) / 8;
+ k := (rsaPrivateKey.N.Len() + 7) / 8
tryEncryptDecrypt := func(in []byte, blind bool) bool {
if len(in) > k-11 {
in = in[0 : k-11]
}
- ciphertext, err := EncryptPKCS1v15(urandom, &rsaPrivateKey.PublicKey, in);
+ ciphertext, err := EncryptPKCS1v15(urandom, &rsaPrivateKey.PublicKey, in)
if err != nil {
- t.Errorf("error encrypting: %s", err);
- return false;
+ t.Errorf("error encrypting: %s", err)
+ return false
}
- var rand io.Reader;
+ var rand io.Reader
if !blind {
rand = nil
} else {
rand = urandom
}
- plaintext, err := DecryptPKCS1v15(rand, rsaPrivateKey, ciphertext);
+ plaintext, err := DecryptPKCS1v15(rand, rsaPrivateKey, ciphertext)
if err != nil {
- t.Errorf("error decrypting: %s", err);
- return false;
+ t.Errorf("error decrypting: %s", err)
+ return false
}
if bytes.Compare(plaintext, in) != 0 {
- t.Errorf("output mismatch: %#v %#v", plaintext, in);
- return false;
+ t.Errorf("output mismatch: %#v %#v", plaintext, in)
+ return false
}
- return true;
- };
+ return true
+ }
- quick.Check(tryEncryptDecrypt, nil);
+ quick.Check(tryEncryptDecrypt, nil)
}
// These test vectors were generated with `openssl rsautl -pkcs -encrypt`
@@ -125,12 +125,12 @@ var decryptPKCS1v15SessionKeyTests = []DecryptPKCS1v15Test{
func TestEncryptPKCS1v15SessionKey(t *testing.T) {
for i, test := range decryptPKCS1v15SessionKeyTests {
- key := strings.Bytes("FAIL");
- err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, decodeBase64(test.in), key);
+ key := strings.Bytes("FAIL")
+ err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, decodeBase64(test.in), key)
if err != nil {
t.Errorf("#%d error decrypting", i)
}
- want := strings.Bytes(test.out);
+ want := strings.Bytes(test.out)
if bytes.Compare(key, want) != 0 {
t.Errorf("#%d got:%#v want:%#v", i, key, want)
}
@@ -138,26 +138,26 @@ func TestEncryptPKCS1v15SessionKey(t *testing.T) {
}
func TestNonZeroRandomBytes(t *testing.T) {
- urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0);
+ urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
if err != nil {
t.Errorf("Failed to open /dev/urandom")
}
- b := make([]byte, 512);
- err = nonZeroRandomBytes(b, urandom);
+ b := make([]byte, 512)
+ err = nonZeroRandomBytes(b, urandom)
if err != nil {
t.Errorf("returned error: %s", err)
}
for _, b := range b {
if b == 0 {
- t.Errorf("Zero octet found");
- return;
+ t.Errorf("Zero octet found")
+ return
}
}
}
type signPKCS1v15Test struct {
- in, out string;
+ in, out string
}
// These vectors have been tested with
@@ -168,16 +168,16 @@ var signPKCS1v15Tests = []signPKCS1v15Test{
func TestSignPKCS1v15(t *testing.T) {
for i, test := range signPKCS1v15Tests {
- h := sha1.New();
- h.Write(strings.Bytes(test.in));
- digest := h.Sum();
+ h := sha1.New()
+ h.Write(strings.Bytes(test.in))
+ digest := h.Sum()
- s, err := SignPKCS1v15(nil, rsaPrivateKey, HashSHA1, digest);
+ s, err := SignPKCS1v15(nil, rsaPrivateKey, HashSHA1, digest)
if err != nil {
t.Errorf("#%d %s", i, err)
}
- expected, _ := hex.DecodeString(test.out);
+ expected, _ := hex.DecodeString(test.out)
if bytes.Compare(s, expected) != 0 {
t.Errorf("#%d got: %x want: %x", i, s, expected)
}
@@ -186,13 +186,13 @@ func TestSignPKCS1v15(t *testing.T) {
func TestVerifyPKCS1v15(t *testing.T) {
for i, test := range signPKCS1v15Tests {
- h := sha1.New();
- h.Write(strings.Bytes(test.in));
- digest := h.Sum();
+ h := sha1.New()
+ h.Write(strings.Bytes(test.in))
+ digest := h.Sum()
- sig, _ := hex.DecodeString(test.out);
+ sig, _ := hex.DecodeString(test.out)
- err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, HashSHA1, digest, sig);
+ err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, HashSHA1, digest, sig)
if err != nil {
t.Errorf("#%d %s", i, err)
}
@@ -200,9 +200,9 @@ func TestVerifyPKCS1v15(t *testing.T) {
}
func bigFromString(s string) *big.Int {
- ret := new(big.Int);
- ret.SetString(s, 10);
- return ret;
+ ret := new(big.Int)
+ ret.SetString(s, 10)
+ return ret
}
// In order to generate new test vectors you'll need the PEM form of this key:
diff --git a/src/pkg/crypto/rsa/rsa.go b/src/pkg/crypto/rsa/rsa.go
index e47b02060f..a4a3cfd38f 100644
--- a/src/pkg/crypto/rsa/rsa.go
+++ b/src/pkg/crypto/rsa/rsa.go
@@ -8,11 +8,11 @@ package rsa
// TODO(agl): Add support for PSS padding.
import (
- "big";
- "crypto/subtle";
- "hash";
- "io";
- "os";
+ "big"
+ "crypto/subtle"
+ "hash"
+ "io"
+ "os"
)
var bigZero = big.NewInt(0)
@@ -25,77 +25,77 @@ func randomSafePrime(rand io.Reader, bits int) (p *big.Int, err os.Error) {
err = os.EINVAL
}
- bytes := make([]byte, (bits+7)/8);
- p = new(big.Int);
- p2 := new(big.Int);
+ bytes := make([]byte, (bits+7)/8)
+ p = new(big.Int)
+ p2 := new(big.Int)
for {
- _, err = io.ReadFull(rand, bytes);
+ _, err = io.ReadFull(rand, bytes)
if err != nil {
return
}
// Don't let the value be too small.
- bytes[0] |= 0x80;
+ bytes[0] |= 0x80
// Make the value odd since an even number this large certainly isn't prime.
- bytes[len(bytes)-1] |= 1;
+ bytes[len(bytes)-1] |= 1
- p.SetBytes(bytes);
+ p.SetBytes(bytes)
if big.ProbablyPrime(p, 20) {
- p2.Rsh(p, 1); // p2 = (p - 1)/2
+ p2.Rsh(p, 1) // p2 = (p - 1)/2
if big.ProbablyPrime(p2, 20) {
return
}
}
}
- return;
+ return
}
// randomNumber returns a uniform random value in [0, max).
func randomNumber(rand io.Reader, max *big.Int) (n *big.Int, err os.Error) {
- k := (max.Len() + 7) / 8;
+ k := (max.Len() + 7) / 8
// r is the number of bits in the used in the most significant byte of
// max.
- r := uint(max.Len() % 8);
+ r := uint(max.Len() % 8)
if r == 0 {
r = 8
}
- bytes := make([]byte, k);
- n = new(big.Int);
+ bytes := make([]byte, k)
+ n = new(big.Int)
for {
- _, err = io.ReadFull(rand, bytes);
+ _, err = io.ReadFull(rand, bytes)
if err != nil {
return
}
// Clear bits in the first byte to increase the probability
// that the candidate is < max.
- bytes[0] &= uint8(int(1<<r) - 1);
+ bytes[0] &= uint8(int(1<<r) - 1)
- n.SetBytes(bytes);
+ n.SetBytes(bytes)
if n.Cmp(max) < 0 {
return
}
}
- return;
+ return
}
// A PublicKey represents the public part of an RSA key.
type PublicKey struct {
- N *big.Int; // modulus
- E int; // public exponent
+ N *big.Int // modulus
+ E int // public exponent
}
// A PrivateKey represents an RSA key
type PrivateKey struct {
- PublicKey; // public part.
- D *big.Int; // private exponent
- P, Q *big.Int; // prime factors of N
+ PublicKey // public part.
+ D *big.Int // private exponent
+ P, Q *big.Int // prime factors of N
}
// Validate performs basic sanity checks on the key.
@@ -114,34 +114,34 @@ func (priv PrivateKey) Validate() os.Error {
}
// Check that p*q == n.
- modulus := new(big.Int).Mul(priv.P, priv.Q);
+ modulus := new(big.Int).Mul(priv.P, priv.Q)
if modulus.Cmp(priv.N) != 0 {
return os.ErrorString("invalid modulus")
}
// Check that e and totient(p, q) are coprime.
- pminus1 := new(big.Int).Sub(priv.P, bigOne);
- qminus1 := new(big.Int).Sub(priv.Q, bigOne);
- totient := new(big.Int).Mul(pminus1, qminus1);
- e := big.NewInt(int64(priv.E));
- gcd := new(big.Int);
- x := new(big.Int);
- y := new(big.Int);
- big.GcdInt(gcd, x, y, totient, e);
+ pminus1 := new(big.Int).Sub(priv.P, bigOne)
+ qminus1 := new(big.Int).Sub(priv.Q, bigOne)
+ totient := new(big.Int).Mul(pminus1, qminus1)
+ e := big.NewInt(int64(priv.E))
+ gcd := new(big.Int)
+ x := new(big.Int)
+ y := new(big.Int)
+ big.GcdInt(gcd, x, y, totient, e)
if gcd.Cmp(bigOne) != 0 {
return os.ErrorString("invalid public exponent E")
}
// Check that de ≡ 1 (mod totient(p, q))
- de := new(big.Int).Mul(priv.D, e);
- de.Mod(de, totient);
+ de := new(big.Int).Mul(priv.D, e)
+ de.Mod(de, totient)
if de.Cmp(bigOne) != 0 {
return os.ErrorString("invalid private exponent D")
}
- return nil;
+ return nil
}
// GenerateKeyPair generates an RSA keypair of the given bit size.
func GenerateKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) {
- priv = new(PrivateKey);
+ priv = new(PrivateKey)
// Smaller public exponents lead to faster public key
// operations. Since the exponent must be coprime to
// (p-1)(q-1), the smallest possible value is 3. Some have
@@ -150,19 +150,19 @@ func GenerateKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) {
// was the case. However, there are no current reasons not to use
// small exponents.
// [1] http://marc.info/?l=cryptography&m=115694833312008&w=2
- priv.E = 3;
+ priv.E = 3
- pminus1 := new(big.Int);
- qminus1 := new(big.Int);
- totient := new(big.Int);
+ pminus1 := new(big.Int)
+ qminus1 := new(big.Int)
+ totient := new(big.Int)
for {
- p, err := randomSafePrime(rand, bits/2);
+ p, err := randomSafePrime(rand, bits/2)
if err != nil {
return nil, err
}
- q, err := randomSafePrime(rand, bits/2);
+ q, err := randomSafePrime(rand, bits/2)
if err != nil {
return nil, err
}
@@ -171,28 +171,28 @@ func GenerateKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) {
continue
}
- n := new(big.Int).Mul(p, q);
- pminus1.Sub(p, bigOne);
- qminus1.Sub(q, bigOne);
- totient.Mul(pminus1, qminus1);
+ n := new(big.Int).Mul(p, q)
+ pminus1.Sub(p, bigOne)
+ qminus1.Sub(q, bigOne)
+ totient.Mul(pminus1, qminus1)
- g := new(big.Int);
- priv.D = new(big.Int);
- y := new(big.Int);
- e := big.NewInt(int64(priv.E));
- big.GcdInt(g, priv.D, y, e, totient);
+ g := new(big.Int)
+ priv.D = new(big.Int)
+ y := new(big.Int)
+ e := big.NewInt(int64(priv.E))
+ big.GcdInt(g, priv.D, y, e, totient)
if g.Cmp(bigOne) == 0 {
- priv.D.Add(priv.D, totient);
- priv.P = p;
- priv.Q = q;
- priv.N = n;
+ priv.D.Add(priv.D, totient)
+ priv.P = p
+ priv.Q = q
+ priv.N = n
- break;
+ break
}
}
- return;
+ return
}
// incCounter increments a four byte, big-endian counter.
@@ -206,26 +206,26 @@ func incCounter(c *[4]byte) {
if c[1]++; c[1] != 0 {
return
}
- c[0]++;
+ c[0]++
}
// mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function
// specified in PKCS#1 v2.1.
func mgf1XOR(out []byte, hash hash.Hash, seed []byte) {
- var counter [4]byte;
+ var counter [4]byte
- done := 0;
+ done := 0
for done < len(out) {
- hash.Write(seed);
- hash.Write(counter[0:4]);
- digest := hash.Sum();
- hash.Reset();
+ hash.Write(seed)
+ hash.Write(counter[0:4])
+ digest := hash.Sum()
+ hash.Reset()
for i := 0; i < len(digest) && done < len(out); i++ {
- out[done] ^= digest[i];
- done++;
+ out[done] ^= digest[i]
+ done++
}
- incCounter(&counter);
+ incCounter(&counter)
}
}
@@ -238,68 +238,68 @@ func (MessageTooLongError) String() string {
}
func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int {
- e := big.NewInt(int64(pub.E));
- c.Exp(m, e, pub.N);
- return c;
+ e := big.NewInt(int64(pub.E))
+ c.Exp(m, e, pub.N)
+ return c
}
// EncryptOAEP encrypts the given message with RSA-OAEP.
// The message must be no longer than the length of the public modulus less
// twice the hash length plus 2.
func EncryptOAEP(hash hash.Hash, rand io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err os.Error) {
- hash.Reset();
- k := (pub.N.Len() + 7) / 8;
+ hash.Reset()
+ k := (pub.N.Len() + 7) / 8
if len(msg) > k-2*hash.Size()-2 {
- err = MessageTooLongError{};
- return;
+ err = MessageTooLongError{}
+ return
}
- hash.Write(label);
- lHash := hash.Sum();
- hash.Reset();
+ hash.Write(label)
+ lHash := hash.Sum()
+ hash.Reset()
- em := make([]byte, k);
- seed := em[1 : 1+hash.Size()];
- db := em[1+hash.Size():];
+ em := make([]byte, k)
+ seed := em[1 : 1+hash.Size()]
+ db := em[1+hash.Size():]
- copy(db[0:hash.Size()], lHash);
- db[len(db)-len(msg)-1] = 1;
- copy(db[len(db)-len(msg):], msg);
+ copy(db[0:hash.Size()], lHash)
+ db[len(db)-len(msg)-1] = 1
+ copy(db[len(db)-len(msg):], msg)
- _, err = io.ReadFull(rand, seed);
+ _, err = io.ReadFull(rand, seed)
if err != nil {
return
}
- mgf1XOR(db, hash, seed);
- mgf1XOR(seed, hash, db);
+ mgf1XOR(db, hash, seed)
+ mgf1XOR(seed, hash, db)
- m := new(big.Int);
- m.SetBytes(em);
- c := encrypt(new(big.Int), pub, m);
- out = c.Bytes();
- return;
+ m := new(big.Int)
+ m.SetBytes(em)
+ c := encrypt(new(big.Int), pub, m)
+ out = c.Bytes()
+ return
}
// A DecryptionError represents a failure to decrypt a message.
// It is deliberately vague to avoid adaptive attacks.
type DecryptionError struct{}
-func (DecryptionError) String() string { return "RSA decryption error" }
+func (DecryptionError) String() string { return "RSA decryption error" }
// A VerificationError represents a failure to verify a signature.
// It is deliberately vague to avoid adaptive attacks.
type VerificationError struct{}
-func (VerificationError) String() string { return "RSA verification error" }
+func (VerificationError) String() string { return "RSA verification error" }
// modInverse returns ia, the inverse of a in the multiplicative group of prime
// order n. It requires that a be a member of the group (i.e. less than n).
func modInverse(a, n *big.Int) (ia *big.Int, ok bool) {
- g := new(big.Int);
- x := new(big.Int);
- y := new(big.Int);
- big.GcdInt(g, x, y, a, n);
+ g := new(big.Int)
+ x := new(big.Int)
+ y := new(big.Int)
+ big.GcdInt(g, x, y, a, n)
if g.Cmp(bigOne) != 0 {
// In this case, a and n aren't coprime and we cannot calculate
// the inverse. This happens because the values of n are nearly
@@ -314,7 +314,7 @@ func modInverse(a, n *big.Int) (ia *big.Int, ok bool) {
x.Add(x, n)
}
- return x, true;
+ return x, true
}
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a
@@ -322,128 +322,128 @@ func modInverse(a, n *big.Int) (ia *big.Int, ok bool) {
func decrypt(rand io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) {
// TODO(agl): can we get away with reusing blinds?
if c.Cmp(priv.N) > 0 {
- err = DecryptionError{};
- return;
+ err = DecryptionError{}
+ return
}
- var ir *big.Int;
+ var ir *big.Int
if rand != nil {
// Blinding enabled. Blinding involves multiplying c by r^e.
// Then the decryption operation performs (m^e * r^e)^d mod n
// which equals mr mod n. The factor of r can then be removed
// by multipling by the multiplicative inverse of r.
- var r *big.Int;
+ var r *big.Int
for {
- r, err = randomNumber(rand, priv.N);
+ r, err = randomNumber(rand, priv.N)
if err != nil {
return
}
if r.Cmp(bigZero) == 0 {
r = bigOne
}
- var ok bool;
- ir, ok = modInverse(r, priv.N);
+ var ok bool
+ ir, ok = modInverse(r, priv.N)
if ok {
break
}
}
- bigE := big.NewInt(int64(priv.E));
- rpowe := new(big.Int).Exp(r, bigE, priv.N);
- c.Mul(c, rpowe);
- c.Mod(c, priv.N);
+ bigE := big.NewInt(int64(priv.E))
+ rpowe := new(big.Int).Exp(r, bigE, priv.N)
+ c.Mul(c, rpowe)
+ c.Mod(c, priv.N)
}
- m = new(big.Int).Exp(c, priv.D, priv.N);
+ m = new(big.Int).Exp(c, priv.D, priv.N)
if ir != nil {
// Unblind.
- m.Mul(m, ir);
- m.Mod(m, priv.N);
+ m.Mul(m, ir)
+ m.Mod(m, priv.N)
}
- return;
+ return
}
// DecryptOAEP decrypts ciphertext using RSA-OAEP.
// If rand != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks.
func DecryptOAEP(hash hash.Hash, rand io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err os.Error) {
- k := (priv.N.Len() + 7) / 8;
+ k := (priv.N.Len() + 7) / 8
if len(ciphertext) > k ||
k < hash.Size()*2+2 {
- err = DecryptionError{};
- return;
+ err = DecryptionError{}
+ return
}
- c := new(big.Int).SetBytes(ciphertext);
+ c := new(big.Int).SetBytes(ciphertext)
- m, err := decrypt(rand, priv, c);
+ m, err := decrypt(rand, priv, c)
if err != nil {
return
}
- hash.Write(label);
- lHash := hash.Sum();
- hash.Reset();
+ hash.Write(label)
+ lHash := hash.Sum()
+ hash.Reset()
// Converting the plaintext number to bytes will strip any
// leading zeros so we may have to left pad. We do this unconditionally
// to avoid leaking timing information. (Although we still probably
// leak the number of leading zeros. It's not clear that we can do
// anything about this.)
- em := leftPad(m.Bytes(), k);
+ em := leftPad(m.Bytes(), k)
- firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0);
+ firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0)
- seed := em[1 : hash.Size()+1];
- db := em[hash.Size()+1:];
+ seed := em[1 : hash.Size()+1]
+ db := em[hash.Size()+1:]
- mgf1XOR(seed, hash, db);
- mgf1XOR(db, hash, seed);
+ mgf1XOR(seed, hash, db)
+ mgf1XOR(db, hash, seed)
- lHash2 := db[0:hash.Size()];
+ lHash2 := db[0:hash.Size()]
// We have to validate the plaintext in contanst time in order to avoid
// attacks like: J. Manger. A Chosen Ciphertext Attack on RSA Optimal
// Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1
// v2.0. In J. Kilian, editor, Advances in Cryptology.
- lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2);
+ lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2)
// The remainder of the plaintext must be zero or more 0x00, followed
// by 0x01, followed by the message.
// lookingForIndex: 1 iff we are still looking for the 0x01
// index: the offset of the first 0x01 byte
// invalid: 1 iff we saw a non-zero byte before the 0x01.
- var lookingForIndex, index, invalid int;
- lookingForIndex = 1;
- rest := db[hash.Size():];
+ var lookingForIndex, index, invalid int
+ lookingForIndex = 1
+ rest := db[hash.Size():]
for i := 0; i < len(rest); i++ {
- equals0 := subtle.ConstantTimeByteEq(rest[i], 0);
- equals1 := subtle.ConstantTimeByteEq(rest[i], 1);
- index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index);
- lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex);
- invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid);
+ equals0 := subtle.ConstantTimeByteEq(rest[i], 0)
+ equals1 := subtle.ConstantTimeByteEq(rest[i], 1)
+ index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index)
+ lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex)
+ invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid)
}
if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 {
- err = DecryptionError{};
- return;
+ err = DecryptionError{}
+ return
}
- msg = rest[index+1:];
- return;
+ msg = rest[index+1:]
+ return
}
// leftPad returns a new slice of length size. The contents of input are right
// aligned in the new slice.
func leftPad(input []byte, size int) (out []byte) {
- n := len(input);
+ n := len(input)
if n > size {
n = size
}
- out = make([]byte, size);
- copy(out[len(out)-n:], input);
- return;
+ out = make([]byte, size)
+ copy(out[len(out)-n:], input)
+ return
}
diff --git a/src/pkg/crypto/rsa/rsa_test.go b/src/pkg/crypto/rsa/rsa_test.go
index cc15b86744..21acf6ed67 100644
--- a/src/pkg/crypto/rsa/rsa_test.go
+++ b/src/pkg/crypto/rsa/rsa_test.go
@@ -5,27 +5,27 @@
package rsa
import (
- "big";
- "bytes";
- "crypto/sha1";
- "os";
- "testing";
+ "big"
+ "bytes"
+ "crypto/sha1"
+ "os"
+ "testing"
)
func TestKeyGeneration(t *testing.T) {
- urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0);
+ urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
if err != nil {
t.Errorf("failed to open /dev/urandom")
}
- priv, err := GenerateKey(urandom, 32);
+ priv, err := GenerateKey(urandom, 32)
if err != nil {
t.Errorf("failed to generate key")
}
- pub := &priv.PublicKey;
- m := big.NewInt(42);
- c := encrypt(new(big.Int), pub, m);
- m2, err := decrypt(nil, priv, c);
+ pub := &priv.PublicKey
+ m := big.NewInt(42)
+ c := encrypt(new(big.Int), pub, m)
+ m2, err := decrypt(nil, priv, c)
if err != nil {
t.Errorf("error while decrypting: %s", err)
}
@@ -33,7 +33,7 @@ func TestKeyGeneration(t *testing.T) {
t.Errorf("got:%v, want:%v (%s)", m2, m, priv)
}
- m3, err := decrypt(urandom, priv, c);
+ m3, err := decrypt(urandom, priv, c)
if err != nil {
t.Errorf("error while decrypting (blind): %s", err)
}
@@ -43,28 +43,28 @@ func TestKeyGeneration(t *testing.T) {
}
type testEncryptOAEPMessage struct {
- in []byte;
- seed []byte;
- out []byte;
+ in []byte
+ seed []byte
+ out []byte
}
type testEncryptOAEPStruct struct {
- modulus string;
- e int;
- d string;
- msgs []testEncryptOAEPMessage;
+ modulus string
+ e int
+ d string
+ msgs []testEncryptOAEPMessage
}
func TestEncryptOAEP(t *testing.T) {
- sha1 := sha1.New();
- n := new(big.Int);
+ sha1 := sha1.New()
+ n := new(big.Int)
for i, test := range testEncryptOAEPData {
- n.SetString(test.modulus, 16);
- public := PublicKey{n, test.e};
+ n.SetString(test.modulus, 16)
+ public := PublicKey{n, test.e}
for j, message := range test.msgs {
- randomSource := bytes.NewBuffer(message.seed);
- out, err := EncryptOAEP(sha1, randomSource, &public, message.in, nil);
+ randomSource := bytes.NewBuffer(message.seed)
+ out, err := EncryptOAEP(sha1, randomSource, &public, message.in, nil)
if err != nil {
t.Errorf("#%d,%d error: %s", i, j, err)
}
@@ -76,21 +76,21 @@ func TestEncryptOAEP(t *testing.T) {
}
func TestDecryptOAEP(t *testing.T) {
- urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0);
+ urandom, err := os.Open("/dev/urandom", os.O_RDONLY, 0)
if err != nil {
t.Errorf("Failed to open /dev/urandom")
}
- sha1 := sha1.New();
- n := new(big.Int);
- d := new(big.Int);
+ sha1 := sha1.New()
+ n := new(big.Int)
+ d := new(big.Int)
for i, test := range testEncryptOAEPData {
- n.SetString(test.modulus, 16);
- d.SetString(test.d, 16);
- private := PrivateKey{PublicKey{n, test.e}, d, nil, nil};
+ n.SetString(test.modulus, 16)
+ d.SetString(test.d, 16)
+ private := PrivateKey{PublicKey{n, test.e}, d, nil, nil}
for j, message := range test.msgs {
- out, err := DecryptOAEP(sha1, nil, &private, message.out, nil);
+ out, err := DecryptOAEP(sha1, nil, &private, message.out, nil)
if err != nil {
t.Errorf("#%d,%d error: %s", i, j, err)
} else if bytes.Compare(out, message.in) != 0 {
@@ -98,7 +98,7 @@ func TestDecryptOAEP(t *testing.T) {
}
// Decrypt with blinding.
- out, err = DecryptOAEP(sha1, urandom, &private, message.out, nil);
+ out, err = DecryptOAEP(sha1, urandom, &private, message.out, nil)
if err != nil {
t.Errorf("#%d,%d (blind) error: %s", i, j, err)
} else if bytes.Compare(out, message.in) != 0 {
diff --git a/src/pkg/crypto/sha1/sha1.go b/src/pkg/crypto/sha1/sha1.go
index ad648d15dc..da70b7314a 100644
--- a/src/pkg/crypto/sha1/sha1.go
+++ b/src/pkg/crypto/sha1/sha1.go
@@ -6,83 +6,83 @@
package sha1
import (
- "hash";
- "os";
+ "hash"
+ "os"
)
// The size of a SHA1 checksum in bytes.
const Size = 20
const (
- _Chunk = 64;
- _Init0 = 0x67452301;
- _Init1 = 0xEFCDAB89;
- _Init2 = 0x98BADCFE;
- _Init3 = 0x10325476;
- _Init4 = 0xC3D2E1F0;
+ _Chunk = 64
+ _Init0 = 0x67452301
+ _Init1 = 0xEFCDAB89
+ _Init2 = 0x98BADCFE
+ _Init3 = 0x10325476
+ _Init4 = 0xC3D2E1F0
)
// digest represents the partial evaluation of a checksum.
type digest struct {
- h [5]uint32;
- x [_Chunk]byte;
- nx int;
- len uint64;
+ h [5]uint32
+ x [_Chunk]byte
+ nx int
+ len uint64
}
func (d *digest) Reset() {
- d.h[0] = _Init0;
- d.h[1] = _Init1;
- d.h[2] = _Init2;
- d.h[3] = _Init3;
- d.h[4] = _Init4;
- d.nx = 0;
- d.len = 0;
+ d.h[0] = _Init0
+ d.h[1] = _Init1
+ d.h[2] = _Init2
+ d.h[3] = _Init3
+ d.h[4] = _Init4
+ d.nx = 0
+ d.len = 0
}
// New returns a new hash.Hash computing the SHA1 checksum.
func New() hash.Hash {
- d := new(digest);
- d.Reset();
- return d;
+ d := new(digest)
+ d.Reset()
+ return d
}
-func (d *digest) Size() int { return Size }
+func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) {
- nn = len(p);
- d.len += uint64(nn);
+ nn = len(p)
+ d.len += uint64(nn)
if d.nx > 0 {
- n := len(p);
+ n := len(p)
if n > _Chunk-d.nx {
n = _Chunk - d.nx
}
for i := 0; i < n; i++ {
d.x[d.nx+i] = p[i]
}
- d.nx += n;
+ d.nx += n
if d.nx == _Chunk {
- _Block(d, &d.x);
- d.nx = 0;
+ _Block(d, &d.x)
+ d.nx = 0
}
- p = p[n:];
+ p = p[n:]
}
- n := _Block(d, p);
- p = p[n:];
+ n := _Block(d, p)
+ p = p[n:]
if len(p) > 0 {
for i := 0; i < len(p); i++ {
d.x[i] = p[i]
}
- d.nx = len(p);
+ d.nx = len(p)
}
- return;
+ return
}
func (d *digest) Sum() []byte {
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
- len := d.len;
- var tmp [64]byte;
- tmp[0] = 0x80;
+ len := d.len
+ var tmp [64]byte
+ tmp[0] = 0x80
if len%64 < 56 {
d.Write(tmp[0 : 56-len%64])
} else {
@@ -90,28 +90,28 @@ func (d *digest) Sum() []byte {
}
// Length in bits.
- len <<= 3;
+ len <<= 3
for i := uint(0); i < 8; i++ {
tmp[i] = byte(len >> (56 - 8*i))
}
- d.Write(tmp[0:8]);
+ d.Write(tmp[0:8])
if d.nx != 0 {
panicln("oops")
}
- p := make([]byte, 20);
- j := 0;
+ p := make([]byte, 20)
+ j := 0
for i := 0; i < 5; i++ {
- s := d.h[i];
- p[j] = byte(s >> 24);
- j++;
- p[j] = byte(s >> 16);
- j++;
- p[j] = byte(s >> 8);
- j++;
- p[j] = byte(s);
- j++;
+ s := d.h[i]
+ p[j] = byte(s >> 24)
+ j++
+ p[j] = byte(s >> 16)
+ j++
+ p[j] = byte(s >> 8)
+ j++
+ p[j] = byte(s)
+ j++
}
- return p;
+ return p
}
diff --git a/src/pkg/crypto/sha1/sha1_test.go b/src/pkg/crypto/sha1/sha1_test.go
index 7536300c29..8d4485282f 100644
--- a/src/pkg/crypto/sha1/sha1_test.go
+++ b/src/pkg/crypto/sha1/sha1_test.go
@@ -7,14 +7,14 @@
package sha1
import (
- "fmt";
- "io";
- "testing";
+ "fmt"
+ "io"
+ "testing"
)
type sha1Test struct {
- out string;
- in string;
+ out string
+ in string
}
var golden = []sha1Test{
@@ -53,16 +53,16 @@ var golden = []sha1Test{
func TestGolden(t *testing.T) {
for i := 0; i < len(golden); i++ {
- g := golden[i];
- c := New();
+ g := golden[i]
+ c := New()
for j := 0; j < 2; j++ {
- io.WriteString(c, g.in);
- s := fmt.Sprintf("%x", c.Sum());
+ io.WriteString(c, g.in)
+ s := fmt.Sprintf("%x", c.Sum())
if s != g.out {
- t.Errorf("sha1[%d](%s) = %s want %s", j, g.in, s, g.out);
- t.FailNow();
+ t.Errorf("sha1[%d](%s) = %s want %s", j, g.in, s, g.out)
+ t.FailNow()
}
- c.Reset();
+ c.Reset()
}
}
}
diff --git a/src/pkg/crypto/sha1/sha1block.go b/src/pkg/crypto/sha1/sha1block.go
index ff11520c0d..b5d32af709 100644
--- a/src/pkg/crypto/sha1/sha1block.go
+++ b/src/pkg/crypto/sha1/sha1block.go
@@ -9,73 +9,73 @@
package sha1
const (
- _K0 = 0x5A827999;
- _K1 = 0x6ED9EBA1;
- _K2 = 0x8F1BBCDC;
- _K3 = 0xCA62C1D6;
+ _K0 = 0x5A827999
+ _K1 = 0x6ED9EBA1
+ _K2 = 0x8F1BBCDC
+ _K3 = 0xCA62C1D6
)
func _Block(dig *digest, p []byte) int {
- var w [80]uint32;
+ var w [80]uint32
- n := 0;
- h0, h1, h2, h3, h4 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4];
+ n := 0
+ h0, h1, h2, h3, h4 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4]
for len(p) >= _Chunk {
// Can interlace the computation of w with the
// rounds below if needed for speed.
for i := 0; i < 16; i++ {
- j := i * 4;
- w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3]);
+ j := i * 4
+ w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3])
}
for i := 16; i < 80; i++ {
- tmp := w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];
- w[i] = tmp<<1 | tmp>>(32-1);
+ tmp := w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]
+ w[i] = tmp<<1 | tmp>>(32-1)
}
- a, b, c, d, e := h0, h1, h2, h3, h4;
+ a, b, c, d, e := h0, h1, h2, h3, h4
// Each of the four 20-iteration rounds
// differs only in the computation of f and
// the choice of K (_K0, _K1, etc).
for i := 0; i < 20; i++ {
- f := b&c | (^b)&d;
- a5 := a<<5 | a>>(32-5);
- b30 := b<<30 | b>>(32-30);
- t := a5 + f + e + w[i] + _K0;
- a, b, c, d, e = t, a, b30, c, d;
+ f := b&c | (^b)&d
+ a5 := a<<5 | a>>(32-5)
+ b30 := b<<30 | b>>(32-30)
+ t := a5 + f + e + w[i] + _K0
+ a, b, c, d, e = t, a, b30, c, d
}
for i := 20; i < 40; i++ {
- f := b ^ c ^ d;
- a5 := a<<5 | a>>(32-5);
- b30 := b<<30 | b>>(32-30);
- t := a5 + f + e + w[i] + _K1;
- a, b, c, d, e = t, a, b30, c, d;
+ f := b ^ c ^ d
+ a5 := a<<5 | a>>(32-5)
+ b30 := b<<30 | b>>(32-30)
+ t := a5 + f + e + w[i] + _K1
+ a, b, c, d, e = t, a, b30, c, d
}
for i := 40; i < 60; i++ {
- f := b&c | b&d | c&d;
- a5 := a<<5 | a>>(32-5);
- b30 := b<<30 | b>>(32-30);
- t := a5 + f + e + w[i] + _K2;
- a, b, c, d, e = t, a, b30, c, d;
+ f := b&c | b&d | c&d
+ a5 := a<<5 | a>>(32-5)
+ b30 := b<<30 | b>>(32-30)
+ t := a5 + f + e + w[i] + _K2
+ a, b, c, d, e = t, a, b30, c, d
}
for i := 60; i < 80; i++ {
- f := b ^ c ^ d;
- a5 := a<<5 | a>>(32-5);
- b30 := b<<30 | b>>(32-30);
- t := a5 + f + e + w[i] + _K3;
- a, b, c, d, e = t, a, b30, c, d;
+ f := b ^ c ^ d
+ a5 := a<<5 | a>>(32-5)
+ b30 := b<<30 | b>>(32-30)
+ t := a5 + f + e + w[i] + _K3
+ a, b, c, d, e = t, a, b30, c, d
}
- h0 += a;
- h1 += b;
- h2 += c;
- h3 += d;
- h4 += e;
+ h0 += a
+ h1 += b
+ h2 += c
+ h3 += d
+ h4 += e
- p = p[_Chunk:];
- n += _Chunk;
+ p = p[_Chunk:]
+ n += _Chunk
}
- dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4] = h0, h1, h2, h3, h4;
- return n;
+ dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4] = h0, h1, h2, h3, h4
+ return n
}
diff --git a/src/pkg/crypto/sha256/sha256.go b/src/pkg/crypto/sha256/sha256.go
index a4dbcf9127..050dd22118 100644
--- a/src/pkg/crypto/sha256/sha256.go
+++ b/src/pkg/crypto/sha256/sha256.go
@@ -6,89 +6,89 @@
package sha256
import (
- "hash";
- "os";
+ "hash"
+ "os"
)
// The size of a SHA256 checksum in bytes.
const Size = 32
const (
- _Chunk = 64;
- _Init0 = 0x6A09E667;
- _Init1 = 0xBB67AE85;
- _Init2 = 0x3C6EF372;
- _Init3 = 0xA54FF53A;
- _Init4 = 0x510E527F;
- _Init5 = 0x9B05688C;
- _Init6 = 0x1F83D9AB;
- _Init7 = 0x5BE0CD19;
+ _Chunk = 64
+ _Init0 = 0x6A09E667
+ _Init1 = 0xBB67AE85
+ _Init2 = 0x3C6EF372
+ _Init3 = 0xA54FF53A
+ _Init4 = 0x510E527F
+ _Init5 = 0x9B05688C
+ _Init6 = 0x1F83D9AB
+ _Init7 = 0x5BE0CD19
)
// digest represents the partial evaluation of a checksum.
type digest struct {
- h [8]uint32;
- x [_Chunk]byte;
- nx int;
- len uint64;
+ h [8]uint32
+ x [_Chunk]byte
+ nx int
+ len uint64
}
func (d *digest) Reset() {
- d.h[0] = _Init0;
- d.h[1] = _Init1;
- d.h[2] = _Init2;
- d.h[3] = _Init3;
- d.h[4] = _Init4;
- d.h[5] = _Init5;
- d.h[6] = _Init6;
- d.h[7] = _Init7;
- d.nx = 0;
- d.len = 0;
+ d.h[0] = _Init0
+ d.h[1] = _Init1
+ d.h[2] = _Init2
+ d.h[3] = _Init3
+ d.h[4] = _Init4
+ d.h[5] = _Init5
+ d.h[6] = _Init6
+ d.h[7] = _Init7
+ d.nx = 0
+ d.len = 0
}
// New returns a new hash.Hash computing the SHA256 checksum.
func New() hash.Hash {
- d := new(digest);
- d.Reset();
- return d;
+ d := new(digest)
+ d.Reset()
+ return d
}
-func (d *digest) Size() int { return Size }
+func (d *digest) Size() int { return Size }
func (d *digest) Write(p []byte) (nn int, err os.Error) {
- nn = len(p);
- d.len += uint64(nn);
+ nn = len(p)
+ d.len += uint64(nn)
if d.nx > 0 {
- n := len(p);
+ n := len(p)
if n > _Chunk-d.nx {
n = _Chunk - d.nx
}
for i := 0; i < n; i++ {
d.x[d.nx+i] = p[i]
}
- d.nx += n;
+ d.nx += n
if d.nx == _Chunk {
- _Block(d, &d.x);
- d.nx = 0;
+ _Block(d, &d.x)
+ d.nx = 0
}
- p = p[n:];
+ p = p[n:]
}
- n := _Block(d, p);
- p = p[n:];
+ n := _Block(d, p)
+ p = p[n:]
if len(p) > 0 {
for i := 0; i < len(p); i++ {
d.x[i] = p[i]
}
- d.nx = len(p);
+ d.nx = len(p)
}
- return;
+ return
}
func (d *digest) Sum() []byte {
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
- len := d.len;
- var tmp [64]byte;
- tmp[0] = 0x80;
+ len := d.len
+ var tmp [64]byte
+ tmp[0] = 0x80
if len%64 < 56 {
d.Write(tmp[0 : 56-len%64])
} else {
@@ -96,28 +96,28 @@ func (d *digest) Sum() []byte {
}
// Length in bits.
- len <<= 3;
+ len <<= 3
for i := uint(0); i < 8; i++ {
tmp[i] = byte(len >> (56 - 8*i))
}
- d.Write(tmp[0:8]);
+ d.Write(tmp[0:8])
if d.nx != 0 {
panicln("oops")
}
- p := make([]byte, 32);
- j := 0;
+ p := make([]byte, 32)
+ j := 0
for i := 0; i < 8; i++ {
- s := d.h[i];
- p[j] = byte(s >> 24);
- j++;
- p[j] = byte(s >> 16);
- j++;
- p[j] = byte(s >> 8);
- j++;
- p[j] = byte(s);
- j++;
+ s := d.h[i]
+ p[j] = byte(s >> 24)
+ j++
+ p[j] = byte(s >> 16)
+ j++
+ p[j] = byte(s >> 8)
+ j++
+ p[j] = byte(s)
+ j++
}
- return p;
+ return p
}
diff --git a/src/pkg/crypto/sha256/sha256_test.go b/src/pkg/crypto/sha256/sha256_test.go
index 5f1c969246..29c0bce601 100644
--- a/src/pkg/crypto/sha256/sha256_test.go
+++ b/src/pkg/crypto/sha256/sha256_test.go
@@ -7,14 +7,14 @@
package sha256
import (
- "fmt";
- "io";
- "testing";
+ "fmt"
+ "io"
+ "testing"
)
type sha256Test struct {
- out string;
- in string;
+ out string
+ in string
}
var golden = []sha256Test{
@@ -53,16 +53,16 @@ var golden = []sha256Test{
func TestGolden(t *testing.T) {
for i := 0; i < len(golden); i++ {
- g := golden[i];
- c := New();
+ g := golden[i]
+ c := New()
for j := 0; j < 2; j++ {
- io.WriteString(c, g.in);
- s := fmt.Sprintf("%x", c.Sum());
+ io.WriteString(c, g.in)
+ s := fmt.Sprintf("%x", c.Sum())
if s != g.out {
- t.Errorf("sha256[%d](%s) = %s want %s", j, g.in, s, g.out);
- t.FailNow();
+ t.Errorf("sha256[%d](%s) = %s want %s", j, g.in, s, g.out)
+ t.FailNow()
}
- c.Reset();
+ c.Reset()
}
}
}
diff --git a/src/pkg/crypto/sha256/sha256block.go b/src/pkg/crypto/sha256/sha256block.go
index a001708595..7b0f554445 100644
--- a/src/pkg/crypto/sha256/sha256block.go
+++ b/src/pkg/crypto/sha256/sha256block.go
@@ -76,54 +76,54 @@ var _K = []uint32{
}
func _Block(dig *digest, p []byte) int {
- var w [64]uint32;
- n := 0;
- h0, h1, h2, h3, h4, h5, h6, h7 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7];
+ var w [64]uint32
+ n := 0
+ h0, h1, h2, h3, h4, h5, h6, h7 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7]
for len(p) >= _Chunk {
// Can interlace the computation of w with the
// rounds below if needed for speed.
for i := 0; i < 16; i++ {
- j := i * 4;
- w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3]);
+ j := i * 4
+ w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3])
}
for i := 16; i < 64; i++ {
- t1 := (w[i-2]>>17 | w[i-2]<<(32-17)) ^ (w[i-2]>>19 | w[i-2]<<(32-19)) ^ (w[i-2] >> 10);
+ t1 := (w[i-2]>>17 | w[i-2]<<(32-17)) ^ (w[i-2]>>19 | w[i-2]<<(32-19)) ^ (w[i-2] >> 10)
- t2 := (w[i-15]>>7 | w[i-15]<<(32-7)) ^ (w[i-15]>>18 | w[i-15]<<(32-18)) ^ (w[i-15] >> 3);
+ t2 := (w[i-15]>>7 | w[i-15]<<(32-7)) ^ (w[i-15]>>18 | w[i-15]<<(32-18)) ^ (w[i-15] >> 3)
- w[i] = t1 + w[i-7] + t2 + w[i-16];
+ w[i] = t1 + w[i-7] + t2 + w[i-16]
}
- a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7;
+ a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7
for i := 0; i < 64; i++ {
- t1 := h + ((e>>6 | e<<(32-6)) ^ (e>>11 | e<<(32-11)) ^ (e>>25 | e<<(32-25))) + ((e & f) ^ (^e & g)) + _K[i] + w[i];
+ t1 := h + ((e>>6 | e<<(32-6)) ^ (e>>11 | e<<(32-11)) ^ (e>>25 | e<<(32-25))) + ((e & f) ^ (^e & g)) + _K[i] + w[i]
- t2 := ((a>>2 | a<<(32-2)) ^ (a>>13 | a<<(32-13)) ^ (a>>22 | a<<(32-22))) + ((a & b) ^ (a & c) ^ (b & c));
+ t2 := ((a>>2 | a<<(32-2)) ^ (a>>13 | a<<(32-13)) ^ (a>>22 | a<<(32-22))) + ((a & b) ^ (a & c) ^ (b & c))
- h = g;
- g = f;
- f = e;
- e = d + t1;
- d = c;
- c = b;
- b = a;
- a = t1 + t2;
+ h = g
+ g = f
+ f = e
+ e = d + t1
+ d = c
+ c = b
+ b = a
+ a = t1 + t2
}
- h0 += a;
- h1 += b;
- h2 += c;
- h3 += d;
- h4 += e;
- h5 += f;
- h6 += g;
- h7 += h;
+ h0 += a
+ h1 += b
+ h2 += c
+ h3 += d
+ h4 += e
+ h5 += f
+ h6 += g
+ h7 += h
- p = p[_Chunk:];
- n += _Chunk;
+ p = p[_Chunk:]
+ n += _Chunk
}
- dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] = h0, h1, h2, h3, h4, h5, h6, h7;
- return n;
+ dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] = h0, h1, h2, h3, h4, h5, h6, h7
+ return n
}
diff --git a/src/pkg/crypto/subtle/constant_time.go b/src/pkg/crypto/subtle/constant_time.go
index 79a96ec963..a3d70b9c96 100644
--- a/src/pkg/crypto/subtle/constant_time.go
+++ b/src/pkg/crypto/subtle/constant_time.go
@@ -10,48 +10,48 @@ package subtle
// and y, have equal contents. The time taken is a function of the length of
// the slices and is independent of the contents.
func ConstantTimeCompare(x, y []byte) int {
- var v byte;
+ var v byte
for i := 0; i < len(x); i++ {
v |= x[i] ^ y[i]
}
- return ConstantTimeByteEq(v, 0);
+ return ConstantTimeByteEq(v, 0)
}
// ConstantTimeSelect returns x if v is 1 and y if v is 0.
// Its behavior is undefined if v takes any other value.
-func ConstantTimeSelect(v, x, y int) int { return ^(v-1)&x | (v-1)&y }
+func ConstantTimeSelect(v, x, y int) int { return ^(v-1)&x | (v-1)&y }
// ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
func ConstantTimeByteEq(x, y uint8) int {
- z := ^(x ^ y);
- z &= z >> 4;
- z &= z >> 2;
- z &= z >> 1;
+ z := ^(x ^ y)
+ z &= z >> 4
+ z &= z >> 2
+ z &= z >> 1
- return int(z);
+ return int(z)
}
// ConstantTimeEq returns 1 if x == y and 0 otherwise.
func ConstantTimeEq(x, y int32) int {
- z := ^(x ^ y);
- z &= z >> 16;
- z &= z >> 8;
- z &= z >> 4;
- z &= z >> 2;
- z &= z >> 1;
+ z := ^(x ^ y)
+ z &= z >> 16
+ z &= z >> 8
+ z &= z >> 4
+ z &= z >> 2
+ z &= z >> 1
- return int(z & 1);
+ return int(z & 1)
}
// ConstantTimeCopy copies the contents of y into x iff v == 1. If v == 0, x is left unchanged.
// Its behavior is undefined if v takes any other value.
func ConstantTimeCopy(v int, x, y []byte) {
- xmask := byte(v - 1);
- ymask := byte(^(v - 1));
+ xmask := byte(v - 1)
+ ymask := byte(^(v - 1))
for i := 0; i < len(x); i++ {
x[i] = x[i]&xmask | y[i]&ymask
}
- return;
+ return
}
diff --git a/src/pkg/crypto/subtle/constant_time_test.go b/src/pkg/crypto/subtle/constant_time_test.go
index d9faafe5ff..25962b9ae5 100644
--- a/src/pkg/crypto/subtle/constant_time_test.go
+++ b/src/pkg/crypto/subtle/constant_time_test.go
@@ -5,13 +5,13 @@
package subtle
import (
- "testing";
- "testing/quick";
+ "testing"
+ "testing/quick"
)
type TestConstantTimeCompareStruct struct {
- a, b []byte;
- out int;
+ a, b []byte
+ out int
}
var testConstandTimeCompareData = []TestConstantTimeCompareStruct{
@@ -29,8 +29,8 @@ func TestConstantTimeCompare(t *testing.T) {
}
type TestConstantTimeByteEqStruct struct {
- a, b uint8;
- out int;
+ a, b uint8
+ out int
}
var testConstandTimeByteEqData = []TestConstantTimeByteEqStruct{
@@ -45,7 +45,7 @@ func byteEq(a, b uint8) int {
if a == b {
return 1
}
- return 0;
+ return 0
}
func TestConstantTimeByteEq(t *testing.T) {
@@ -54,7 +54,7 @@ func TestConstantTimeByteEq(t *testing.T) {
t.Errorf("#%d bad result (got %x, want %x)", i, r, test.out)
}
}
- err := quick.CheckEqual(ConstantTimeByteEq, byteEq, nil);
+ err := quick.CheckEqual(ConstantTimeByteEq, byteEq, nil)
if err != nil {
t.Error(err)
}
@@ -64,11 +64,11 @@ func eq(a, b int32) int {
if a == b {
return 1
}
- return 0;
+ return 0
}
func TestConstantTimeEq(t *testing.T) {
- err := quick.CheckEqual(ConstantTimeEq, eq, nil);
+ err := quick.CheckEqual(ConstantTimeEq, eq, nil)
if err != nil {
t.Error(err)
}
@@ -83,7 +83,7 @@ func makeCopy(v int, x, y []byte) []byte {
if v == 1 {
copy(x, y)
}
- return x;
+ return x
}
func constantTimeCopyWrapper(v int, x, y []byte) []byte {
@@ -92,13 +92,13 @@ func constantTimeCopyWrapper(v int, x, y []byte) []byte {
} else {
y = y[0:len(x)]
}
- v &= 1;
- ConstantTimeCopy(v, x, y);
- return x;
+ v &= 1
+ ConstantTimeCopy(v, x, y)
+ return x
}
func TestConstantTimeCopy(t *testing.T) {
- err := quick.CheckEqual(constantTimeCopyWrapper, makeCopy, nil);
+ err := quick.CheckEqual(constantTimeCopyWrapper, makeCopy, nil)
if err != nil {
t.Error(err)
}
diff --git a/src/pkg/crypto/tls/alert.go b/src/pkg/crypto/tls/alert.go
index 4cf62e7a4e..2f740b39ea 100644
--- a/src/pkg/crypto/tls/alert.go
+++ b/src/pkg/crypto/tls/alert.go
@@ -8,36 +8,36 @@ type alertLevel int
type alertType int
const (
- alertLevelWarning alertLevel = 1;
- alertLevelError alertLevel = 2;
+ alertLevelWarning alertLevel = 1
+ alertLevelError alertLevel = 2
)
const (
- alertCloseNotify alertType = 0;
- alertUnexpectedMessage alertType = 10;
- alertBadRecordMAC alertType = 20;
- alertDecryptionFailed alertType = 21;
- alertRecordOverflow alertType = 22;
- alertDecompressionFailure alertType = 30;
- alertHandshakeFailure alertType = 40;
- alertBadCertificate alertType = 42;
- alertUnsupportedCertificate alertType = 43;
- alertCertificateRevoked alertType = 44;
- alertCertificateExpired alertType = 45;
- alertCertificateUnknown alertType = 46;
- alertIllegalParameter alertType = 47;
- alertUnknownCA alertType = 48;
- alertAccessDenied alertType = 49;
- alertDecodeError alertType = 50;
- alertDecryptError alertType = 51;
- alertProtocolVersion alertType = 70;
- alertInsufficientSecurity alertType = 71;
- alertInternalError alertType = 80;
- alertUserCanceled alertType = 90;
- alertNoRenegotiation alertType = 100;
+ alertCloseNotify alertType = 0
+ alertUnexpectedMessage alertType = 10
+ alertBadRecordMAC alertType = 20
+ alertDecryptionFailed alertType = 21
+ alertRecordOverflow alertType = 22
+ alertDecompressionFailure alertType = 30
+ alertHandshakeFailure alertType = 40
+ alertBadCertificate alertType = 42
+ alertUnsupportedCertificate alertType = 43
+ alertCertificateRevoked alertType = 44
+ alertCertificateExpired alertType = 45
+ alertCertificateUnknown alertType = 46
+ alertIllegalParameter alertType = 47
+ alertUnknownCA alertType = 48
+ alertAccessDenied alertType = 49
+ alertDecodeError alertType = 50
+ alertDecryptError alertType = 51
+ alertProtocolVersion alertType = 70
+ alertInsufficientSecurity alertType = 71
+ alertInternalError alertType = 80
+ alertUserCanceled alertType = 90
+ alertNoRenegotiation alertType = 100
)
type alert struct {
- level alertLevel;
- error alertType;
+ level alertLevel
+ error alertType
}
diff --git a/src/pkg/crypto/tls/ca_set.go b/src/pkg/crypto/tls/ca_set.go
index e8cddd6f4c..00f6a87306 100644
--- a/src/pkg/crypto/tls/ca_set.go
+++ b/src/pkg/crypto/tls/ca_set.go
@@ -5,14 +5,14 @@
package tls
import (
- "crypto/x509";
- "encoding/pem";
+ "crypto/x509"
+ "encoding/pem"
)
// A CASet is a set of certificates.
type CASet struct {
- bySubjectKeyId map[string]*x509.Certificate;
- byName map[string]*x509.Certificate;
+ bySubjectKeyId map[string]*x509.Certificate
+ byName map[string]*x509.Certificate
}
func NewCASet() *CASet {
@@ -29,7 +29,7 @@ func nameToKey(name *x509.Name) string {
// FindParent attempts to find the certificate in s which signs the given
// certificate. If no such certificate can be found, it returns nil.
func (s *CASet) FindParent(cert *x509.Certificate) (parent *x509.Certificate) {
- var ok bool;
+ var ok bool
if len(cert.AuthorityKeyId) > 0 {
parent, ok = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
@@ -40,7 +40,7 @@ func (s *CASet) FindParent(cert *x509.Certificate) (parent *x509.Certificate) {
if !ok {
return nil
}
- return parent;
+ return parent
}
// SetFromPEM attempts to parse a series of PEM encoded root certificates. It
@@ -50,8 +50,8 @@ func (s *CASet) FindParent(cert *x509.Certificate) (parent *x509.Certificate) {
// function.
func (s *CASet) SetFromPEM(pemCerts []byte) (ok bool) {
for len(pemCerts) > 0 {
- var block *pem.Block;
- block, pemCerts = pem.Decode(pemCerts);
+ var block *pem.Block
+ block, pemCerts = pem.Decode(pemCerts)
if block == nil {
break
}
@@ -59,7 +59,7 @@ func (s *CASet) SetFromPEM(pemCerts []byte) (ok bool) {
continue
}
- cert, err := x509.ParseCertificate(block.Bytes);
+ cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
continue
}
@@ -67,9 +67,9 @@ func (s *CASet) SetFromPEM(pemCerts []byte) (ok bool) {
if len(cert.SubjectKeyId) > 0 {
s.bySubjectKeyId[string(cert.SubjectKeyId)] = cert
}
- s.byName[nameToKey(&cert.Subject)] = cert;
- ok = true;
+ s.byName[nameToKey(&cert.Subject)] = cert
+ ok = true
}
- return;
+ return
}
diff --git a/src/pkg/crypto/tls/common.go b/src/pkg/crypto/tls/common.go
index e1318a8930..51de53389a 100644
--- a/src/pkg/crypto/tls/common.go
+++ b/src/pkg/crypto/tls/common.go
@@ -5,21 +5,21 @@
package tls
import (
- "crypto/rsa";
- "io";
- "os";
+ "crypto/rsa"
+ "io"
+ "os"
)
const (
// maxTLSCiphertext is the maximum length of a plaintext payload.
- maxTLSPlaintext = 16384;
+ maxTLSPlaintext = 16384
// maxTLSCiphertext is the maximum length payload after compression and encryption.
- maxTLSCiphertext = 16384 + 2048;
+ maxTLSCiphertext = 16384 + 2048
// maxHandshakeMsg is the largest single handshake message that we'll buffer.
- maxHandshakeMsg = 65536;
+ maxHandshakeMsg = 65536
// defaultMajor and defaultMinor are the maximum TLS version that we support.
- defaultMajor = 3;
- defaultMinor = 2;
+ defaultMajor = 3
+ defaultMinor = 2
)
@@ -27,68 +27,68 @@ const (
type recordType uint8
const (
- recordTypeChangeCipherSpec recordType = 20;
- recordTypeAlert recordType = 21;
- recordTypeHandshake recordType = 22;
- recordTypeApplicationData recordType = 23;
+ recordTypeChangeCipherSpec recordType = 20
+ recordTypeAlert recordType = 21
+ recordTypeHandshake recordType = 22
+ recordTypeApplicationData recordType = 23
)
// TLS handshake message types.
const (
- typeClientHello uint8 = 1;
- typeServerHello uint8 = 2;
- typeCertificate uint8 = 11;
- typeServerHelloDone uint8 = 14;
- typeClientKeyExchange uint8 = 16;
- typeFinished uint8 = 20;
+ typeClientHello uint8 = 1
+ typeServerHello uint8 = 2
+ typeCertificate uint8 = 11
+ typeServerHelloDone uint8 = 14
+ typeClientKeyExchange uint8 = 16
+ typeFinished uint8 = 20
)
// TLS cipher suites.
var (
- TLS_RSA_WITH_RC4_128_SHA uint16 = 5;
+ TLS_RSA_WITH_RC4_128_SHA uint16 = 5
)
// TLS compression types.
var (
- compressionNone uint8 = 0;
+ compressionNone uint8 = 0
)
type ConnectionState struct {
- HandshakeComplete bool;
- CipherSuite string;
- Error alertType;
+ HandshakeComplete bool
+ CipherSuite string
+ Error alertType
}
// A Config structure is used to configure a TLS client or server. After one
// has been passed to a TLS function it must not be modified.
type Config struct {
// Rand provides the source of entropy for nonces and RSA blinding.
- Rand io.Reader;
+ Rand io.Reader
// Time returns the current time as the number of seconds since the epoch.
- Time func() int64;
- Certificates []Certificate;
- RootCAs *CASet;
+ Time func() int64
+ Certificates []Certificate
+ RootCAs *CASet
}
type Certificate struct {
- Certificate [][]byte;
- PrivateKey *rsa.PrivateKey;
+ Certificate [][]byte
+ PrivateKey *rsa.PrivateKey
}
// A TLS record.
type record struct {
- contentType recordType;
- major, minor uint8;
- payload []byte;
+ contentType recordType
+ major, minor uint8
+ payload []byte
}
type handshakeMessage interface {
- marshal() []byte;
+ marshal() []byte
}
type encryptor interface {
// XORKeyStream xors the contents of the slice with bytes from the key stream.
- XORKeyStream(buf []byte);
+ XORKeyStream(buf []byte)
}
// mutualVersion returns the protocol version to use given the advertised
@@ -98,24 +98,24 @@ func mutualVersion(theirMajor, theirMinor uint8) (major, minor uint8, ok bool) {
if theirMajor < 3 || theirMajor == 3 && theirMinor < 1 {
return 0, 0, false
}
- major = 3;
- minor = 2;
+ major = 3
+ minor = 2
if theirMinor < minor {
minor = theirMinor
}
- ok = true;
- return;
+ ok = true
+ return
}
// A nop implements the NULL encryption and MAC algorithms.
type nop struct{}
-func (nop) XORKeyStream(buf []byte) {}
+func (nop) XORKeyStream(buf []byte) {}
-func (nop) Write(buf []byte) (int, os.Error) { return len(buf), nil }
+func (nop) Write(buf []byte) (int, os.Error) { return len(buf), nil }
-func (nop) Sum() []byte { return nil }
+func (nop) Sum() []byte { return nil }
-func (nop) Reset() {}
+func (nop) Reset() {}
-func (nop) Size() int { return 0 }
+func (nop) Size() int { return 0 }
diff --git a/src/pkg/crypto/tls/handshake_client.go b/src/pkg/crypto/tls/handshake_client.go
index 1c6bd4b81b..4e31e70941 100644
--- a/src/pkg/crypto/tls/handshake_client.go
+++ b/src/pkg/crypto/tls/handshake_client.go
@@ -5,33 +5,33 @@
package tls
import (
- "crypto/hmac";
- "crypto/rc4";
- "crypto/rsa";
- "crypto/sha1";
- "crypto/subtle";
- "crypto/x509";
- "io";
+ "crypto/hmac"
+ "crypto/rc4"
+ "crypto/rsa"
+ "crypto/sha1"
+ "crypto/subtle"
+ "crypto/x509"
+ "io"
)
// A serverHandshake performs the server side of the TLS 1.1 handshake protocol.
type clientHandshake struct {
- writeChan chan<- interface{};
- controlChan chan<- interface{};
- msgChan <-chan interface{};
- config *Config;
+ writeChan chan<- interface{}
+ controlChan chan<- interface{}
+ msgChan <-chan interface{}
+ config *Config
}
func (h *clientHandshake) loop(writeChan chan<- interface{}, controlChan chan<- interface{}, msgChan <-chan interface{}, config *Config) {
- h.writeChan = writeChan;
- h.controlChan = controlChan;
- h.msgChan = msgChan;
- h.config = config;
+ h.writeChan = writeChan
+ h.controlChan = controlChan
+ h.msgChan = msgChan
+ h.config = config
- defer close(writeChan);
- defer close(controlChan);
+ defer close(writeChan)
+ defer close(controlChan)
- finishedHash := newFinishedHash();
+ finishedHash := newFinishedHash()
hello := &clientHelloMsg{
major: defaultMajor,
@@ -39,175 +39,175 @@ func (h *clientHandshake) loop(writeChan chan<- interface{}, controlChan chan<-
cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
compressionMethods: []uint8{compressionNone},
random: make([]byte, 32),
- };
+ }
- currentTime := uint32(config.Time());
- hello.random[0] = byte(currentTime >> 24);
- hello.random[1] = byte(currentTime >> 16);
- hello.random[2] = byte(currentTime >> 8);
- hello.random[3] = byte(currentTime);
- _, err := io.ReadFull(config.Rand, hello.random[4:]);
+ currentTime := uint32(config.Time())
+ hello.random[0] = byte(currentTime >> 24)
+ hello.random[1] = byte(currentTime >> 16)
+ hello.random[2] = byte(currentTime >> 8)
+ hello.random[3] = byte(currentTime)
+ _, err := io.ReadFull(config.Rand, hello.random[4:])
if err != nil {
- h.error(alertInternalError);
- return;
+ h.error(alertInternalError)
+ return
}
- finishedHash.Write(hello.marshal());
- writeChan <- writerSetVersion{defaultMajor, defaultMinor};
- writeChan <- hello;
+ finishedHash.Write(hello.marshal())
+ writeChan <- writerSetVersion{defaultMajor, defaultMinor}
+ writeChan <- hello
- serverHello, ok := h.readHandshakeMsg().(*serverHelloMsg);
+ serverHello, ok := h.readHandshakeMsg().(*serverHelloMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- finishedHash.Write(serverHello.marshal());
- major, minor, ok := mutualVersion(serverHello.major, serverHello.minor);
+ finishedHash.Write(serverHello.marshal())
+ major, minor, ok := mutualVersion(serverHello.major, serverHello.minor)
if !ok {
- h.error(alertProtocolVersion);
- return;
+ h.error(alertProtocolVersion)
+ return
}
- writeChan <- writerSetVersion{major, minor};
+ writeChan <- writerSetVersion{major, minor}
if serverHello.cipherSuite != TLS_RSA_WITH_RC4_128_SHA ||
serverHello.compressionMethod != compressionNone {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- certMsg, ok := h.readHandshakeMsg().(*certificateMsg);
+ certMsg, ok := h.readHandshakeMsg().(*certificateMsg)
if !ok || len(certMsg.certificates) == 0 {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- finishedHash.Write(certMsg.marshal());
+ finishedHash.Write(certMsg.marshal())
- certs := make([]*x509.Certificate, len(certMsg.certificates));
+ certs := make([]*x509.Certificate, len(certMsg.certificates))
for i, asn1Data := range certMsg.certificates {
- cert, err := x509.ParseCertificate(asn1Data);
+ cert, err := x509.ParseCertificate(asn1Data)
if err != nil {
- h.error(alertBadCertificate);
- return;
+ h.error(alertBadCertificate)
+ return
}
- certs[i] = cert;
+ certs[i] = cert
}
// TODO(agl): do better validation of certs: max path length, name restrictions etc.
for i := 1; i < len(certs); i++ {
if certs[i-1].CheckSignatureFrom(certs[i]) != nil {
- h.error(alertBadCertificate);
- return;
+ h.error(alertBadCertificate)
+ return
}
}
if config.RootCAs != nil {
- root := config.RootCAs.FindParent(certs[len(certs)-1]);
+ root := config.RootCAs.FindParent(certs[len(certs)-1])
if root == nil {
- h.error(alertBadCertificate);
- return;
+ h.error(alertBadCertificate)
+ return
}
if certs[len(certs)-1].CheckSignatureFrom(root) != nil {
- h.error(alertBadCertificate);
- return;
+ h.error(alertBadCertificate)
+ return
}
}
- pub, ok := certs[0].PublicKey.(*rsa.PublicKey);
+ pub, ok := certs[0].PublicKey.(*rsa.PublicKey)
if !ok {
- h.error(alertUnsupportedCertificate);
- return;
+ h.error(alertUnsupportedCertificate)
+ return
}
- shd, ok := h.readHandshakeMsg().(*serverHelloDoneMsg);
+ shd, ok := h.readHandshakeMsg().(*serverHelloDoneMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- finishedHash.Write(shd.marshal());
+ finishedHash.Write(shd.marshal())
- ckx := new(clientKeyExchangeMsg);
- preMasterSecret := make([]byte, 48);
+ ckx := new(clientKeyExchangeMsg)
+ preMasterSecret := make([]byte, 48)
// Note that the version number in the preMasterSecret must be the
// version offered in the ClientHello.
- preMasterSecret[0] = defaultMajor;
- preMasterSecret[1] = defaultMinor;
- _, err = io.ReadFull(config.Rand, preMasterSecret[2:]);
+ preMasterSecret[0] = defaultMajor
+ preMasterSecret[1] = defaultMinor
+ _, err = io.ReadFull(config.Rand, preMasterSecret[2:])
if err != nil {
- h.error(alertInternalError);
- return;
+ h.error(alertInternalError)
+ return
}
- ckx.ciphertext, err = rsa.EncryptPKCS1v15(config.Rand, pub, preMasterSecret);
+ ckx.ciphertext, err = rsa.EncryptPKCS1v15(config.Rand, pub, preMasterSecret)
if err != nil {
- h.error(alertInternalError);
- return;
+ h.error(alertInternalError)
+ return
}
- finishedHash.Write(ckx.marshal());
- writeChan <- ckx;
+ finishedHash.Write(ckx.marshal())
+ writeChan <- ckx
- suite := cipherSuites[0];
+ suite := cipherSuites[0]
masterSecret, clientMAC, serverMAC, clientKey, serverKey :=
- keysFromPreMasterSecret11(preMasterSecret, hello.random, serverHello.random, suite.hashLength, suite.cipherKeyLength);
+ keysFromPreMasterSecret11(preMasterSecret, hello.random, serverHello.random, suite.hashLength, suite.cipherKeyLength)
- cipher, _ := rc4.NewCipher(clientKey);
- writeChan <- writerChangeCipherSpec{cipher, hmac.New(sha1.New(), clientMAC)};
+ cipher, _ := rc4.NewCipher(clientKey)
+ writeChan <- writerChangeCipherSpec{cipher, hmac.New(sha1.New(), clientMAC)}
- finished := new(finishedMsg);
- finished.verifyData = finishedHash.clientSum(masterSecret);
- finishedHash.Write(finished.marshal());
- writeChan <- finished;
+ finished := new(finishedMsg)
+ finished.verifyData = finishedHash.clientSum(masterSecret)
+ finishedHash.Write(finished.marshal())
+ writeChan <- finished
// TODO(agl): this is cut-through mode which should probably be an option.
- writeChan <- writerEnableApplicationData{};
+ writeChan <- writerEnableApplicationData{}
- _, ok = h.readHandshakeMsg().(changeCipherSpec);
+ _, ok = h.readHandshakeMsg().(changeCipherSpec)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- cipher2, _ := rc4.NewCipher(serverKey);
- controlChan <- &newCipherSpec{cipher2, hmac.New(sha1.New(), serverMAC)};
+ cipher2, _ := rc4.NewCipher(serverKey)
+ controlChan <- &newCipherSpec{cipher2, hmac.New(sha1.New(), serverMAC)}
- serverFinished, ok := h.readHandshakeMsg().(*finishedMsg);
+ serverFinished, ok := h.readHandshakeMsg().(*finishedMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- verify := finishedHash.serverSum(masterSecret);
+ verify := finishedHash.serverSum(masterSecret)
if len(verify) != len(serverFinished.verifyData) ||
subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
- h.error(alertHandshakeFailure);
- return;
+ h.error(alertHandshakeFailure)
+ return
}
- controlChan <- ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0};
+ controlChan <- ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0}
// This should just block forever.
- _ = h.readHandshakeMsg();
- h.error(alertUnexpectedMessage);
- return;
+ _ = h.readHandshakeMsg()
+ h.error(alertUnexpectedMessage)
+ return
}
func (h *clientHandshake) readHandshakeMsg() interface{} {
- v := <-h.msgChan;
+ v := <-h.msgChan
if closed(h.msgChan) {
// If the channel closed then the processor received an error
// from the peer and we don't want to echo it back to them.
- h.msgChan = nil;
- return 0;
+ h.msgChan = nil
+ return 0
}
if _, ok := v.(alert); ok {
// We got an alert from the processor. We forward to the writer
// and shutdown.
- h.writeChan <- v;
- h.msgChan = nil;
- return 0;
+ h.writeChan <- v
+ h.msgChan = nil
+ return 0
}
- return v;
+ return v
}
func (h *clientHandshake) error(e alertType) {
@@ -217,9 +217,9 @@ func (h *clientHandshake) error(e alertType) {
go func() {
for _ = range h.msgChan {
}
- }();
- h.controlChan <- ConnectionState{false, "", e};
- close(h.controlChan);
- h.writeChan <- alert{alertLevelError, e};
+ }()
+ h.controlChan <- ConnectionState{false, "", e}
+ close(h.controlChan)
+ h.writeChan <- alert{alertLevelError, e}
}
}
diff --git a/src/pkg/crypto/tls/handshake_messages.go b/src/pkg/crypto/tls/handshake_messages.go
index b5f2aa731f..2870969eb3 100644
--- a/src/pkg/crypto/tls/handshake_messages.go
+++ b/src/pkg/crypto/tls/handshake_messages.go
@@ -5,12 +5,12 @@
package tls
type clientHelloMsg struct {
- raw []byte;
- major, minor uint8;
- random []byte;
- sessionId []byte;
- cipherSuites []uint16;
- compressionMethods []uint8;
+ raw []byte
+ major, minor uint8
+ random []byte
+ sessionId []byte
+ cipherSuites []uint16
+ compressionMethods []uint8
}
func (m *clientHelloMsg) marshal() []byte {
@@ -18,81 +18,81 @@ func (m *clientHelloMsg) marshal() []byte {
return m.raw
}
- length := 2 + 32 + 1 + len(m.sessionId) + 2 + len(m.cipherSuites)*2 + 1 + len(m.compressionMethods);
- x := make([]byte, 4+length);
- x[0] = typeClientHello;
- x[1] = uint8(length >> 16);
- x[2] = uint8(length >> 8);
- x[3] = uint8(length);
- x[4] = m.major;
- x[5] = m.minor;
- copy(x[6:38], m.random);
- x[38] = uint8(len(m.sessionId));
- copy(x[39:39+len(m.sessionId)], m.sessionId);
- y := x[39+len(m.sessionId):];
- y[0] = uint8(len(m.cipherSuites) >> 7);
- y[1] = uint8(len(m.cipherSuites) << 1);
+ length := 2 + 32 + 1 + len(m.sessionId) + 2 + len(m.cipherSuites)*2 + 1 + len(m.compressionMethods)
+ x := make([]byte, 4+length)
+ x[0] = typeClientHello
+ x[1] = uint8(length >> 16)
+ x[2] = uint8(length >> 8)
+ x[3] = uint8(length)
+ x[4] = m.major
+ x[5] = m.minor
+ copy(x[6:38], m.random)
+ x[38] = uint8(len(m.sessionId))
+ copy(x[39:39+len(m.sessionId)], m.sessionId)
+ y := x[39+len(m.sessionId):]
+ y[0] = uint8(len(m.cipherSuites) >> 7)
+ y[1] = uint8(len(m.cipherSuites) << 1)
for i, suite := range m.cipherSuites {
- y[2+i*2] = uint8(suite >> 8);
- y[3+i*2] = uint8(suite);
+ y[2+i*2] = uint8(suite >> 8)
+ y[3+i*2] = uint8(suite)
}
- z := y[2+len(m.cipherSuites)*2:];
- z[0] = uint8(len(m.compressionMethods));
- copy(z[1:], m.compressionMethods);
- m.raw = x;
+ z := y[2+len(m.cipherSuites)*2:]
+ z[0] = uint8(len(m.compressionMethods))
+ copy(z[1:], m.compressionMethods)
+ m.raw = x
- return x;
+ return x
}
func (m *clientHelloMsg) unmarshal(data []byte) bool {
if len(data) < 43 {
return false
}
- m.raw = data;
- m.major = data[4];
- m.minor = data[5];
- m.random = data[6:38];
- sessionIdLen := int(data[38]);
+ m.raw = data
+ m.major = data[4]
+ m.minor = data[5]
+ m.random = data[6:38]
+ sessionIdLen := int(data[38])
if sessionIdLen > 32 || len(data) < 39+sessionIdLen {
return false
}
- m.sessionId = data[39 : 39+sessionIdLen];
- data = data[39+sessionIdLen:];
+ m.sessionId = data[39 : 39+sessionIdLen]
+ data = data[39+sessionIdLen:]
if len(data) < 2 {
return false
}
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
// they are uint16s, the number must be even.
- cipherSuiteLen := int(data[0])<<8 | int(data[1]);
+ cipherSuiteLen := int(data[0])<<8 | int(data[1])
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
return false
}
- numCipherSuites := cipherSuiteLen / 2;
- m.cipherSuites = make([]uint16, numCipherSuites);
+ numCipherSuites := cipherSuiteLen / 2
+ m.cipherSuites = make([]uint16, numCipherSuites)
for i := 0; i < numCipherSuites; i++ {
m.cipherSuites[i] = uint16(data[2+2*i])<<8 | uint16(data[3+2*i])
}
- data = data[2+cipherSuiteLen:];
+ data = data[2+cipherSuiteLen:]
if len(data) < 2 {
return false
}
- compressionMethodsLen := int(data[0]);
+ compressionMethodsLen := int(data[0])
if len(data) < 1+compressionMethodsLen {
return false
}
- m.compressionMethods = data[1 : 1+compressionMethodsLen];
+ m.compressionMethods = data[1 : 1+compressionMethodsLen]
// A ClientHello may be following by trailing data: RFC 4346 section 7.4.1.2
- return true;
+ return true
}
type serverHelloMsg struct {
- raw []byte;
- major, minor uint8;
- random []byte;
- sessionId []byte;
- cipherSuite uint16;
- compressionMethod uint8;
+ raw []byte
+ major, minor uint8
+ random []byte
+ sessionId []byte
+ cipherSuite uint16
+ compressionMethod uint8
}
func (m *serverHelloMsg) marshal() []byte {
@@ -100,53 +100,53 @@ func (m *serverHelloMsg) marshal() []byte {
return m.raw
}
- length := 38 + len(m.sessionId);
- x := make([]byte, 4+length);
- x[0] = typeServerHello;
- x[1] = uint8(length >> 16);
- x[2] = uint8(length >> 8);
- x[3] = uint8(length);
- x[4] = m.major;
- x[5] = m.minor;
- copy(x[6:38], m.random);
- x[38] = uint8(len(m.sessionId));
- copy(x[39:39+len(m.sessionId)], m.sessionId);
- z := x[39+len(m.sessionId):];
- z[0] = uint8(m.cipherSuite >> 8);
- z[1] = uint8(m.cipherSuite);
- z[2] = uint8(m.compressionMethod);
- m.raw = x;
+ length := 38 + len(m.sessionId)
+ x := make([]byte, 4+length)
+ x[0] = typeServerHello
+ x[1] = uint8(length >> 16)
+ x[2] = uint8(length >> 8)
+ x[3] = uint8(length)
+ x[4] = m.major
+ x[5] = m.minor
+ copy(x[6:38], m.random)
+ x[38] = uint8(len(m.sessionId))
+ copy(x[39:39+len(m.sessionId)], m.sessionId)
+ z := x[39+len(m.sessionId):]
+ z[0] = uint8(m.cipherSuite >> 8)
+ z[1] = uint8(m.cipherSuite)
+ z[2] = uint8(m.compressionMethod)
+ m.raw = x
- return x;
+ return x
}
func (m *serverHelloMsg) unmarshal(data []byte) bool {
if len(data) < 42 {
return false
}
- m.raw = data;
- m.major = data[4];
- m.minor = data[5];
- m.random = data[6:38];
- sessionIdLen := int(data[38]);
+ m.raw = data
+ m.major = data[4]
+ m.minor = data[5]
+ m.random = data[6:38]
+ sessionIdLen := int(data[38])
if sessionIdLen > 32 || len(data) < 39+sessionIdLen {
return false
}
- m.sessionId = data[39 : 39+sessionIdLen];
- data = data[39+sessionIdLen:];
+ m.sessionId = data[39 : 39+sessionIdLen]
+ data = data[39+sessionIdLen:]
if len(data) < 3 {
return false
}
- m.cipherSuite = uint16(data[0])<<8 | uint16(data[1]);
- m.compressionMethod = data[2];
+ m.cipherSuite = uint16(data[0])<<8 | uint16(data[1])
+ m.compressionMethod = data[2]
// Trailing data is allowed because extensions may be present.
- return true;
+ return true
}
type certificateMsg struct {
- raw []byte;
- certificates [][]byte;
+ raw []byte
+ certificates [][]byte
}
func (m *certificateMsg) marshal() (x []byte) {
@@ -154,34 +154,34 @@ func (m *certificateMsg) marshal() (x []byte) {
return m.raw
}
- var i int;
+ var i int
for _, slice := range m.certificates {
i += len(slice)
}
- length := 3 + 3*len(m.certificates) + i;
- x = make([]byte, 4+length);
- x[0] = typeCertificate;
- x[1] = uint8(length >> 16);
- x[2] = uint8(length >> 8);
- x[3] = uint8(length);
+ length := 3 + 3*len(m.certificates) + i
+ x = make([]byte, 4+length)
+ x[0] = typeCertificate
+ x[1] = uint8(length >> 16)
+ x[2] = uint8(length >> 8)
+ x[3] = uint8(length)
- certificateOctets := length - 3;
- x[4] = uint8(certificateOctets >> 16);
- x[5] = uint8(certificateOctets >> 8);
- x[6] = uint8(certificateOctets);
+ certificateOctets := length - 3
+ x[4] = uint8(certificateOctets >> 16)
+ x[5] = uint8(certificateOctets >> 8)
+ x[6] = uint8(certificateOctets)
- y := x[7:];
+ y := x[7:]
for _, slice := range m.certificates {
- y[0] = uint8(len(slice) >> 16);
- y[1] = uint8(len(slice) >> 8);
- y[2] = uint8(len(slice));
- copy(y[3:], slice);
- y = y[3+len(slice):];
+ y[0] = uint8(len(slice) >> 16)
+ y[1] = uint8(len(slice) >> 8)
+ y[2] = uint8(len(slice))
+ copy(y[3:], slice)
+ y = y[3+len(slice):]
}
- m.raw = x;
- return;
+ m.raw = x
+ return
}
func (m *certificateMsg) unmarshal(data []byte) bool {
@@ -189,44 +189,44 @@ func (m *certificateMsg) unmarshal(data []byte) bool {
return false
}
- m.raw = data;
- certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6]);
+ m.raw = data
+ certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6])
if uint32(len(data)) != certsLen+7 {
return false
}
- numCerts := 0;
- d := data[7:];
+ numCerts := 0
+ d := data[7:]
for certsLen > 0 {
if len(d) < 4 {
return false
}
- certLen := uint32(d[0])<<24 | uint32(d[1])<<8 | uint32(d[2]);
+ certLen := uint32(d[0])<<24 | uint32(d[1])<<8 | uint32(d[2])
if uint32(len(d)) < 3+certLen {
return false
}
- d = d[3+certLen:];
- certsLen -= 3 + certLen;
- numCerts++;
+ d = d[3+certLen:]
+ certsLen -= 3 + certLen
+ numCerts++
}
- m.certificates = make([][]byte, numCerts);
- d = data[7:];
+ m.certificates = make([][]byte, numCerts)
+ d = data[7:]
for i := 0; i < numCerts; i++ {
- certLen := uint32(d[0])<<24 | uint32(d[1])<<8 | uint32(d[2]);
- m.certificates[i] = d[3 : 3+certLen];
- d = d[3+certLen:];
+ certLen := uint32(d[0])<<24 | uint32(d[1])<<8 | uint32(d[2])
+ m.certificates[i] = d[3 : 3+certLen]
+ d = d[3+certLen:]
}
- return true;
+ return true
}
type serverHelloDoneMsg struct{}
func (m *serverHelloDoneMsg) marshal() []byte {
- x := make([]byte, 4);
- x[0] = typeServerHelloDone;
- return x;
+ x := make([]byte, 4)
+ x[0] = typeServerHelloDone
+ return x
}
func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
@@ -234,44 +234,44 @@ func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
}
type clientKeyExchangeMsg struct {
- raw []byte;
- ciphertext []byte;
+ raw []byte
+ ciphertext []byte
}
func (m *clientKeyExchangeMsg) marshal() []byte {
if m.raw != nil {
return m.raw
}
- length := len(m.ciphertext) + 2;
- x := make([]byte, length+4);
- x[0] = typeClientKeyExchange;
- x[1] = uint8(length >> 16);
- x[2] = uint8(length >> 8);
- x[3] = uint8(length);
- x[4] = uint8(len(m.ciphertext) >> 8);
- x[5] = uint8(len(m.ciphertext));
- copy(x[6:], m.ciphertext);
+ length := len(m.ciphertext) + 2
+ x := make([]byte, length+4)
+ x[0] = typeClientKeyExchange
+ x[1] = uint8(length >> 16)
+ x[2] = uint8(length >> 8)
+ x[3] = uint8(length)
+ x[4] = uint8(len(m.ciphertext) >> 8)
+ x[5] = uint8(len(m.ciphertext))
+ copy(x[6:], m.ciphertext)
- m.raw = x;
- return x;
+ m.raw = x
+ return x
}
func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool {
- m.raw = data;
+ m.raw = data
if len(data) < 7 {
return false
}
- cipherTextLen := int(data[4])<<8 | int(data[5]);
+ cipherTextLen := int(data[4])<<8 | int(data[5])
if len(data) != 6+cipherTextLen {
return false
}
- m.ciphertext = data[6:];
- return true;
+ m.ciphertext = data[6:]
+ return true
}
type finishedMsg struct {
- raw []byte;
- verifyData []byte;
+ raw []byte
+ verifyData []byte
}
func (m *finishedMsg) marshal() (x []byte) {
@@ -279,19 +279,19 @@ func (m *finishedMsg) marshal() (x []byte) {
return m.raw
}
- x = make([]byte, 16);
- x[0] = typeFinished;
- x[3] = 12;
- copy(x[4:], m.verifyData);
- m.raw = x;
- return;
+ x = make([]byte, 16)
+ x[0] = typeFinished
+ x[3] = 12
+ copy(x[4:], m.verifyData)
+ m.raw = x
+ return
}
func (m *finishedMsg) unmarshal(data []byte) bool {
- m.raw = data;
+ m.raw = data
if len(data) != 4+12 {
return false
}
- m.verifyData = data[4:];
- return true;
+ m.verifyData = data[4:]
+ return true
}
diff --git a/src/pkg/crypto/tls/handshake_messages_test.go b/src/pkg/crypto/tls/handshake_messages_test.go
index c580f65c68..4bfdd6c5f1 100644
--- a/src/pkg/crypto/tls/handshake_messages_test.go
+++ b/src/pkg/crypto/tls/handshake_messages_test.go
@@ -5,10 +5,10 @@
package tls
import (
- "rand";
- "reflect";
- "testing";
- "testing/quick";
+ "rand"
+ "reflect"
+ "testing"
+ "testing/quick"
)
var tests = []interface{}{
@@ -20,41 +20,41 @@ var tests = []interface{}{
}
type testMessage interface {
- marshal() []byte;
- unmarshal([]byte) bool;
+ marshal() []byte
+ unmarshal([]byte) bool
}
func TestMarshalUnmarshal(t *testing.T) {
- rand := rand.New(rand.NewSource(0));
+ rand := rand.New(rand.NewSource(0))
for i, iface := range tests {
- ty := reflect.NewValue(iface).Type();
+ ty := reflect.NewValue(iface).Type()
for j := 0; j < 100; j++ {
- v, ok := quick.Value(ty, rand);
+ v, ok := quick.Value(ty, rand)
if !ok {
- t.Errorf("#%d: failed to create value", i);
- break;
+ t.Errorf("#%d: failed to create value", i)
+ break
}
- m1 := v.Interface().(testMessage);
- marshaled := m1.marshal();
- m2 := iface.(testMessage);
+ m1 := v.Interface().(testMessage)
+ marshaled := m1.marshal()
+ m2 := iface.(testMessage)
if !m2.unmarshal(marshaled) {
- t.Errorf("#%d failed to unmarshal %#v", i, m1);
- break;
+ t.Errorf("#%d failed to unmarshal %#v", i, m1)
+ break
}
- m2.marshal(); // to fill any marshal cache in the message
+ m2.marshal() // to fill any marshal cache in the message
if !reflect.DeepEqual(m1, m2) {
- t.Errorf("#%d got:%#v want:%#v", i, m1, m2);
- break;
+ t.Errorf("#%d got:%#v want:%#v", i, m1, m2)
+ break
}
// Now check that all prefixes are invalid.
for j := 0; j < len(marshaled); j++ {
if m2.unmarshal(marshaled[0:j]) {
- t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1);
- break;
+ t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1)
+ break
}
}
}
@@ -62,71 +62,71 @@ func TestMarshalUnmarshal(t *testing.T) {
}
func TestFuzz(t *testing.T) {
- rand := rand.New(rand.NewSource(0));
+ rand := rand.New(rand.NewSource(0))
for _, iface := range tests {
- m := iface.(testMessage);
+ m := iface.(testMessage)
for j := 0; j < 1000; j++ {
- len := rand.Intn(100);
- bytes := randomBytes(len, rand);
+ len := rand.Intn(100)
+ bytes := randomBytes(len, rand)
// This just looks for crashes due to bounds errors etc.
- m.unmarshal(bytes);
+ m.unmarshal(bytes)
}
}
}
func randomBytes(n int, rand *rand.Rand) []byte {
- r := make([]byte, n);
+ r := make([]byte, n)
for i := 0; i < n; i++ {
r[i] = byte(rand.Int31())
}
- return r;
+ return r
}
func (*clientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
- m := &clientHelloMsg{};
- m.major = uint8(rand.Intn(256));
- m.minor = uint8(rand.Intn(256));
- m.random = randomBytes(32, rand);
- m.sessionId = randomBytes(rand.Intn(32), rand);
- m.cipherSuites = make([]uint16, rand.Intn(63)+1);
+ m := &clientHelloMsg{}
+ m.major = uint8(rand.Intn(256))
+ m.minor = uint8(rand.Intn(256))
+ m.random = randomBytes(32, rand)
+ m.sessionId = randomBytes(rand.Intn(32), rand)
+ m.cipherSuites = make([]uint16, rand.Intn(63)+1)
for i := 0; i < len(m.cipherSuites); i++ {
m.cipherSuites[i] = uint16(rand.Int31())
}
- m.compressionMethods = randomBytes(rand.Intn(63)+1, rand);
+ m.compressionMethods = randomBytes(rand.Intn(63)+1, rand)
- return reflect.NewValue(m);
+ return reflect.NewValue(m)
}
func (*serverHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
- m := &serverHelloMsg{};
- m.major = uint8(rand.Intn(256));
- m.minor = uint8(rand.Intn(256));
- m.random = randomBytes(32, rand);
- m.sessionId = randomBytes(rand.Intn(32), rand);
- m.cipherSuite = uint16(rand.Int31());
- m.compressionMethod = uint8(rand.Intn(256));
- return reflect.NewValue(m);
+ m := &serverHelloMsg{}
+ m.major = uint8(rand.Intn(256))
+ m.minor = uint8(rand.Intn(256))
+ m.random = randomBytes(32, rand)
+ m.sessionId = randomBytes(rand.Intn(32), rand)
+ m.cipherSuite = uint16(rand.Int31())
+ m.compressionMethod = uint8(rand.Intn(256))
+ return reflect.NewValue(m)
}
func (*certificateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
- m := &certificateMsg{};
- numCerts := rand.Intn(20);
- m.certificates = make([][]byte, numCerts);
+ m := &certificateMsg{}
+ numCerts := rand.Intn(20)
+ m.certificates = make([][]byte, numCerts)
for i := 0; i < numCerts; i++ {
m.certificates[i] = randomBytes(rand.Intn(10)+1, rand)
}
- return reflect.NewValue(m);
+ return reflect.NewValue(m)
}
func (*clientKeyExchangeMsg) Generate(rand *rand.Rand, size int) reflect.Value {
- m := &clientKeyExchangeMsg{};
- m.ciphertext = randomBytes(rand.Intn(1000)+1, rand);
- return reflect.NewValue(m);
+ m := &clientKeyExchangeMsg{}
+ m.ciphertext = randomBytes(rand.Intn(1000)+1, rand)
+ return reflect.NewValue(m)
}
func (*finishedMsg) Generate(rand *rand.Rand, size int) reflect.Value {
- m := &finishedMsg{};
- m.verifyData = randomBytes(12, rand);
- return reflect.NewValue(m);
+ m := &finishedMsg{}
+ m.verifyData = randomBytes(12, rand)
+ return reflect.NewValue(m)
}
diff --git a/src/pkg/crypto/tls/handshake_server.go b/src/pkg/crypto/tls/handshake_server.go
index 2e7760365c..5314e5cd19 100644
--- a/src/pkg/crypto/tls/handshake_server.go
+++ b/src/pkg/crypto/tls/handshake_server.go
@@ -13,17 +13,17 @@ package tls
// channel in the message (ChangeCipherSpec).
import (
- "crypto/hmac";
- "crypto/rc4";
- "crypto/rsa";
- "crypto/sha1";
- "crypto/subtle";
- "io";
+ "crypto/hmac"
+ "crypto/rc4"
+ "crypto/rsa"
+ "crypto/sha1"
+ "crypto/subtle"
+ "io"
)
type cipherSuite struct {
- id uint16; // The number of this suite on the wire.
- hashLength, cipherKeyLength int;
+ id uint16 // The number of this suite on the wire.
+ hashLength, cipherKeyLength int
// TODO(agl): need a method to create the cipher and hash interfaces.
}
@@ -33,118 +33,118 @@ var cipherSuites = []cipherSuite{
// A serverHandshake performs the server side of the TLS 1.1 handshake protocol.
type serverHandshake struct {
- writeChan chan<- interface{};
- controlChan chan<- interface{};
- msgChan <-chan interface{};
- config *Config;
+ writeChan chan<- interface{}
+ controlChan chan<- interface{}
+ msgChan <-chan interface{}
+ config *Config
}
func (h *serverHandshake) loop(writeChan chan<- interface{}, controlChan chan<- interface{}, msgChan <-chan interface{}, config *Config) {
- h.writeChan = writeChan;
- h.controlChan = controlChan;
- h.msgChan = msgChan;
- h.config = config;
+ h.writeChan = writeChan
+ h.controlChan = controlChan
+ h.msgChan = msgChan
+ h.config = config
- defer close(writeChan);
- defer close(controlChan);
+ defer close(writeChan)
+ defer close(controlChan)
- clientHello, ok := h.readHandshakeMsg().(*clientHelloMsg);
+ clientHello, ok := h.readHandshakeMsg().(*clientHelloMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- major, minor, ok := mutualVersion(clientHello.major, clientHello.minor);
+ major, minor, ok := mutualVersion(clientHello.major, clientHello.minor)
if !ok {
- h.error(alertProtocolVersion);
- return;
+ h.error(alertProtocolVersion)
+ return
}
- finishedHash := newFinishedHash();
- finishedHash.Write(clientHello.marshal());
+ finishedHash := newFinishedHash()
+ finishedHash.Write(clientHello.marshal())
- hello := new(serverHelloMsg);
+ hello := new(serverHelloMsg)
// We only support a single ciphersuite so we look for it in the list
// of client supported suites.
//
// TODO(agl): Add additional cipher suites.
- var suite *cipherSuite;
+ var suite *cipherSuite
for _, id := range clientHello.cipherSuites {
for _, supported := range cipherSuites {
if supported.id == id {
- suite = &supported;
- break;
+ suite = &supported
+ break
}
}
}
- foundCompression := false;
+ foundCompression := false
// We only support null compression, so check that the client offered it.
for _, compression := range clientHello.compressionMethods {
if compression == compressionNone {
- foundCompression = true;
- break;
+ foundCompression = true
+ break
}
}
if suite == nil || !foundCompression {
- h.error(alertHandshakeFailure);
- return;
+ h.error(alertHandshakeFailure)
+ return
}
- hello.major = major;
- hello.minor = minor;
- hello.cipherSuite = suite.id;
- currentTime := uint32(config.Time());
- hello.random = make([]byte, 32);
- hello.random[0] = byte(currentTime >> 24);
- hello.random[1] = byte(currentTime >> 16);
- hello.random[2] = byte(currentTime >> 8);
- hello.random[3] = byte(currentTime);
- _, err := io.ReadFull(config.Rand, hello.random[4:]);
+ hello.major = major
+ hello.minor = minor
+ hello.cipherSuite = suite.id
+ currentTime := uint32(config.Time())
+ hello.random = make([]byte, 32)
+ hello.random[0] = byte(currentTime >> 24)
+ hello.random[1] = byte(currentTime >> 16)
+ hello.random[2] = byte(currentTime >> 8)
+ hello.random[3] = byte(currentTime)
+ _, err := io.ReadFull(config.Rand, hello.random[4:])
if err != nil {
- h.error(alertInternalError);
- return;
+ h.error(alertInternalError)
+ return
}
- hello.compressionMethod = compressionNone;
+ hello.compressionMethod = compressionNone
- finishedHash.Write(hello.marshal());
- writeChan <- writerSetVersion{major, minor};
- writeChan <- hello;
+ finishedHash.Write(hello.marshal())
+ writeChan <- writerSetVersion{major, minor}
+ writeChan <- hello
if len(config.Certificates) == 0 {
- h.error(alertInternalError);
- return;
+ h.error(alertInternalError)
+ return
}
- certMsg := new(certificateMsg);
- certMsg.certificates = config.Certificates[0].Certificate;
- finishedHash.Write(certMsg.marshal());
- writeChan <- certMsg;
+ certMsg := new(certificateMsg)
+ certMsg.certificates = config.Certificates[0].Certificate
+ finishedHash.Write(certMsg.marshal())
+ writeChan <- certMsg
- helloDone := new(serverHelloDoneMsg);
- finishedHash.Write(helloDone.marshal());
- writeChan <- helloDone;
+ helloDone := new(serverHelloDoneMsg)
+ finishedHash.Write(helloDone.marshal())
+ writeChan <- helloDone
- ckx, ok := h.readHandshakeMsg().(*clientKeyExchangeMsg);
+ ckx, ok := h.readHandshakeMsg().(*clientKeyExchangeMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- finishedHash.Write(ckx.marshal());
+ finishedHash.Write(ckx.marshal())
- preMasterSecret := make([]byte, 48);
- _, err = io.ReadFull(config.Rand, preMasterSecret[2:]);
+ preMasterSecret := make([]byte, 48)
+ _, err = io.ReadFull(config.Rand, preMasterSecret[2:])
if err != nil {
- h.error(alertInternalError);
- return;
+ h.error(alertInternalError)
+ return
}
- err = rsa.DecryptPKCS1v15SessionKey(config.Rand, config.Certificates[0].PrivateKey, ckx.ciphertext, preMasterSecret);
+ err = rsa.DecryptPKCS1v15SessionKey(config.Rand, config.Certificates[0].PrivateKey, ckx.ciphertext, preMasterSecret)
if err != nil {
- h.error(alertHandshakeFailure);
- return;
+ h.error(alertHandshakeFailure)
+ return
}
// We don't check the version number in the premaster secret. For one,
// by checking it, we would leak information about the validity of the
@@ -154,70 +154,70 @@ func (h *serverHandshake) loop(writeChan chan<- interface{}, controlChan chan<-
// 7.4.7.1 of RFC 4346.
masterSecret, clientMAC, serverMAC, clientKey, serverKey :=
- keysFromPreMasterSecret11(preMasterSecret, clientHello.random, hello.random, suite.hashLength, suite.cipherKeyLength);
+ keysFromPreMasterSecret11(preMasterSecret, clientHello.random, hello.random, suite.hashLength, suite.cipherKeyLength)
- _, ok = h.readHandshakeMsg().(changeCipherSpec);
+ _, ok = h.readHandshakeMsg().(changeCipherSpec)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- cipher, _ := rc4.NewCipher(clientKey);
- controlChan <- &newCipherSpec{cipher, hmac.New(sha1.New(), clientMAC)};
+ cipher, _ := rc4.NewCipher(clientKey)
+ controlChan <- &newCipherSpec{cipher, hmac.New(sha1.New(), clientMAC)}
- clientFinished, ok := h.readHandshakeMsg().(*finishedMsg);
+ clientFinished, ok := h.readHandshakeMsg().(*finishedMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
- verify := finishedHash.clientSum(masterSecret);
+ verify := finishedHash.clientSum(masterSecret)
if len(verify) != len(clientFinished.verifyData) ||
subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
- h.error(alertHandshakeFailure);
- return;
+ h.error(alertHandshakeFailure)
+ return
}
- controlChan <- ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0};
+ controlChan <- ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0}
- finishedHash.Write(clientFinished.marshal());
+ finishedHash.Write(clientFinished.marshal())
- cipher2, _ := rc4.NewCipher(serverKey);
- writeChan <- writerChangeCipherSpec{cipher2, hmac.New(sha1.New(), serverMAC)};
+ cipher2, _ := rc4.NewCipher(serverKey)
+ writeChan <- writerChangeCipherSpec{cipher2, hmac.New(sha1.New(), serverMAC)}
- finished := new(finishedMsg);
- finished.verifyData = finishedHash.serverSum(masterSecret);
- writeChan <- finished;
+ finished := new(finishedMsg)
+ finished.verifyData = finishedHash.serverSum(masterSecret)
+ writeChan <- finished
- writeChan <- writerEnableApplicationData{};
+ writeChan <- writerEnableApplicationData{}
for {
- _, ok := h.readHandshakeMsg().(*clientHelloMsg);
+ _, ok := h.readHandshakeMsg().(*clientHelloMsg)
if !ok {
- h.error(alertUnexpectedMessage);
- return;
+ h.error(alertUnexpectedMessage)
+ return
}
// We reject all renegotication requests.
- writeChan <- alert{alertLevelWarning, alertNoRenegotiation};
+ writeChan <- alert{alertLevelWarning, alertNoRenegotiation}
}
}
func (h *serverHandshake) readHandshakeMsg() interface{} {
- v := <-h.msgChan;
+ v := <-h.msgChan
if closed(h.msgChan) {
// If the channel closed then the processor received an error
// from the peer and we don't want to echo it back to them.
- h.msgChan = nil;
- return 0;
+ h.msgChan = nil
+ return 0
}
if _, ok := v.(alert); ok {
// We got an alert from the processor. We forward to the writer
// and shutdown.
- h.writeChan <- v;
- h.msgChan = nil;
- return 0;
+ h.writeChan <- v
+ h.msgChan = nil
+ return 0
}
- return v;
+ return v
}
func (h *serverHandshake) error(e alertType) {
@@ -227,9 +227,9 @@ func (h *serverHandshake) error(e alertType) {
go func() {
for _ = range h.msgChan {
}
- }();
- h.controlChan <- ConnectionState{false, "", e};
- close(h.controlChan);
- h.writeChan <- alert{alertLevelError, e};
+ }()
+ h.controlChan <- ConnectionState{false, "", e}
+ close(h.controlChan)
+ h.writeChan <- alert{alertLevelError, e}
}
}
diff --git a/src/pkg/crypto/tls/handshake_server_test.go b/src/pkg/crypto/tls/handshake_server_test.go
index 91583d2da5..716098530c 100644
--- a/src/pkg/crypto/tls/handshake_server_test.go
+++ b/src/pkg/crypto/tls/handshake_server_test.go
@@ -5,12 +5,12 @@
package tls
import (
- "bytes";
- "big";
- "crypto/rsa";
- "os";
- "testing";
- "testing/script";
+ "bytes"
+ "big"
+ "crypto/rsa"
+ "os"
+ "testing"
+ "testing/script"
)
type zeroSource struct{}
@@ -20,41 +20,41 @@ func (zeroSource) Read(b []byte) (n int, err os.Error) {
b[i] = 0
}
- return len(b), nil;
+ return len(b), nil
}
var testConfig *Config
func init() {
- testConfig = new(Config);
- testConfig.Time = func() int64 { return 0 };
- testConfig.Rand = zeroSource{};
- testConfig.Certificates = make([]Certificate, 1);
- testConfig.Certificates[0].Certificate = [][]byte{testCertificate};
- testConfig.Certificates[0].PrivateKey = testPrivateKey;
+ testConfig = new(Config)
+ testConfig.Time = func() int64 { return 0 }
+ testConfig.Rand = zeroSource{}
+ testConfig.Certificates = make([]Certificate, 1)
+ testConfig.Certificates[0].Certificate = [][]byte{testCertificate}
+ testConfig.Certificates[0].PrivateKey = testPrivateKey
}
func setupServerHandshake() (writeChan chan interface{}, controlChan chan interface{}, msgChan chan interface{}) {
- sh := new(serverHandshake);
- writeChan = make(chan interface{});
- controlChan = make(chan interface{});
- msgChan = make(chan interface{});
+ sh := new(serverHandshake)
+ writeChan = make(chan interface{})
+ controlChan = make(chan interface{})
+ msgChan = make(chan interface{})
- go sh.loop(writeChan, controlChan, msgChan, testConfig);
- return;
+ go sh.loop(writeChan, controlChan, msgChan, testConfig)
+ return
}
func testClientHelloFailure(t *testing.T, clientHello interface{}, expectedAlert alertType) {
- writeChan, controlChan, msgChan := setupServerHandshake();
- defer close(msgChan);
+ writeChan, controlChan, msgChan := setupServerHandshake()
+ defer close(msgChan)
- send := script.NewEvent("send", nil, script.Send{msgChan, clientHello});
- recvAlert := script.NewEvent("recv alert", []*script.Event{send}, script.Recv{writeChan, alert{alertLevelError, expectedAlert}});
- close1 := script.NewEvent("msgChan close", []*script.Event{recvAlert}, script.Closed{writeChan});
- recvState := script.NewEvent("recv state", []*script.Event{send}, script.Recv{controlChan, ConnectionState{false, "", expectedAlert}});
- close2 := script.NewEvent("controlChan close", []*script.Event{recvState}, script.Closed{controlChan});
+ send := script.NewEvent("send", nil, script.Send{msgChan, clientHello})
+ recvAlert := script.NewEvent("recv alert", []*script.Event{send}, script.Recv{writeChan, alert{alertLevelError, expectedAlert}})
+ close1 := script.NewEvent("msgChan close", []*script.Event{recvAlert}, script.Closed{writeChan})
+ recvState := script.NewEvent("recv state", []*script.Event{send}, script.Recv{controlChan, ConnectionState{false, "", expectedAlert}})
+ close2 := script.NewEvent("controlChan close", []*script.Event{recvState}, script.Closed{controlChan})
- err := script.Perform(0, []*script.Event{send, recvAlert, close1, recvState, close2});
+ err := script.Perform(0, []*script.Event{send, recvAlert, close1, recvState, close2})
if err != nil {
t.Errorf("Got error: %s", err)
}
@@ -67,125 +67,125 @@ func TestSimpleError(t *testing.T) {
var badProtocolVersions = []uint8{0, 0, 0, 5, 1, 0, 1, 5, 2, 0, 2, 5, 3, 0}
func TestRejectBadProtocolVersion(t *testing.T) {
- clientHello := new(clientHelloMsg);
+ clientHello := new(clientHelloMsg)
for i := 0; i < len(badProtocolVersions); i += 2 {
- clientHello.major = badProtocolVersions[i];
- clientHello.minor = badProtocolVersions[i+1];
+ clientHello.major = badProtocolVersions[i]
+ clientHello.minor = badProtocolVersions[i+1]
- testClientHelloFailure(t, clientHello, alertProtocolVersion);
+ testClientHelloFailure(t, clientHello, alertProtocolVersion)
}
}
func TestNoSuiteOverlap(t *testing.T) {
- clientHello := &clientHelloMsg{nil, 3, 1, nil, nil, []uint16{0xff00}, []uint8{0}};
- testClientHelloFailure(t, clientHello, alertHandshakeFailure);
+ clientHello := &clientHelloMsg{nil, 3, 1, nil, nil, []uint16{0xff00}, []uint8{0}}
+ testClientHelloFailure(t, clientHello, alertHandshakeFailure)
}
func TestNoCompressionOverlap(t *testing.T) {
- clientHello := &clientHelloMsg{nil, 3, 1, nil, nil, []uint16{TLS_RSA_WITH_RC4_128_SHA}, []uint8{0xff}};
- testClientHelloFailure(t, clientHello, alertHandshakeFailure);
+ clientHello := &clientHelloMsg{nil, 3, 1, nil, nil, []uint16{TLS_RSA_WITH_RC4_128_SHA}, []uint8{0xff}}
+ testClientHelloFailure(t, clientHello, alertHandshakeFailure)
}
func matchServerHello(v interface{}) bool {
- serverHello, ok := v.(*serverHelloMsg);
+ serverHello, ok := v.(*serverHelloMsg)
if !ok {
return false
}
return serverHello.major == 3 &&
serverHello.minor == 2 &&
serverHello.cipherSuite == TLS_RSA_WITH_RC4_128_SHA &&
- serverHello.compressionMethod == compressionNone;
+ serverHello.compressionMethod == compressionNone
}
func TestAlertForwarding(t *testing.T) {
- writeChan, controlChan, msgChan := setupServerHandshake();
- defer close(msgChan);
+ writeChan, controlChan, msgChan := setupServerHandshake()
+ defer close(msgChan)
- a := alert{alertLevelError, alertNoRenegotiation};
- sendAlert := script.NewEvent("send alert", nil, script.Send{msgChan, a});
- recvAlert := script.NewEvent("recv alert", []*script.Event{sendAlert}, script.Recv{writeChan, a});
- closeWriter := script.NewEvent("close writer", []*script.Event{recvAlert}, script.Closed{writeChan});
- closeControl := script.NewEvent("close control", []*script.Event{recvAlert}, script.Closed{controlChan});
+ a := alert{alertLevelError, alertNoRenegotiation}
+ sendAlert := script.NewEvent("send alert", nil, script.Send{msgChan, a})
+ recvAlert := script.NewEvent("recv alert", []*script.Event{sendAlert}, script.Recv{writeChan, a})
+ closeWriter := script.NewEvent("close writer", []*script.Event{recvAlert}, script.Closed{writeChan})
+ closeControl := script.NewEvent("close control", []*script.Event{recvAlert}, script.Closed{controlChan})
- err := script.Perform(0, []*script.Event{sendAlert, recvAlert, closeWriter, closeControl});
+ err := script.Perform(0, []*script.Event{sendAlert, recvAlert, closeWriter, closeControl})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestClose(t *testing.T) {
- writeChan, controlChan, msgChan := setupServerHandshake();
+ writeChan, controlChan, msgChan := setupServerHandshake()
- close := script.NewEvent("close", nil, script.Close{msgChan});
- closed1 := script.NewEvent("closed1", []*script.Event{close}, script.Closed{writeChan});
- closed2 := script.NewEvent("closed2", []*script.Event{close}, script.Closed{controlChan});
+ close := script.NewEvent("close", nil, script.Close{msgChan})
+ closed1 := script.NewEvent("closed1", []*script.Event{close}, script.Closed{writeChan})
+ closed2 := script.NewEvent("closed2", []*script.Event{close}, script.Closed{controlChan})
- err := script.Perform(0, []*script.Event{close, closed1, closed2});
+ err := script.Perform(0, []*script.Event{close, closed1, closed2})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func matchCertificate(v interface{}) bool {
- cert, ok := v.(*certificateMsg);
+ cert, ok := v.(*certificateMsg)
if !ok {
return false
}
return len(cert.certificates) == 1 &&
- bytes.Compare(cert.certificates[0], testCertificate) == 0;
+ bytes.Compare(cert.certificates[0], testCertificate) == 0
}
func matchSetCipher(v interface{}) bool {
- _, ok := v.(writerChangeCipherSpec);
- return ok;
+ _, ok := v.(writerChangeCipherSpec)
+ return ok
}
func matchDone(v interface{}) bool {
- _, ok := v.(*serverHelloDoneMsg);
- return ok;
+ _, ok := v.(*serverHelloDoneMsg)
+ return ok
}
func matchFinished(v interface{}) bool {
- finished, ok := v.(*finishedMsg);
+ finished, ok := v.(*finishedMsg)
if !ok {
return false
}
- return bytes.Compare(finished.verifyData, fromHex("29122ae11453e631487b02ed")) == 0;
+ return bytes.Compare(finished.verifyData, fromHex("29122ae11453e631487b02ed")) == 0
}
func matchNewCipherSpec(v interface{}) bool {
- _, ok := v.(*newCipherSpec);
- return ok;
+ _, ok := v.(*newCipherSpec)
+ return ok
}
func TestFullHandshake(t *testing.T) {
- writeChan, controlChan, msgChan := setupServerHandshake();
- defer close(msgChan);
+ writeChan, controlChan, msgChan := setupServerHandshake()
+ defer close(msgChan)
// The values for this test were obtained from running `gnutls-cli --insecure --debug 9`
- clientHello := &clientHelloMsg{fromHex("0100007603024aef7d77e4686d5dfd9d953dfe280788759ffd440867d687670216da45516b310000340033004500390088001600320044003800870013006600900091008f008e002f004100350084000a00050004008c008d008b008a01000019000900030200010000000e000c0000093132372e302e302e31"), 3, 2, fromHex("4aef7d77e4686d5dfd9d953dfe280788759ffd440867d687670216da45516b31"), nil, []uint16{0x33, 0x45, 0x39, 0x88, 0x16, 0x32, 0x44, 0x38, 0x87, 0x13, 0x66, 0x90, 0x91, 0x8f, 0x8e, 0x2f, 0x41, 0x35, 0x84, 0xa, 0x5, 0x4, 0x8c, 0x8d, 0x8b, 0x8a}, []uint8{0x0}};
+ clientHello := &clientHelloMsg{fromHex("0100007603024aef7d77e4686d5dfd9d953dfe280788759ffd440867d687670216da45516b310000340033004500390088001600320044003800870013006600900091008f008e002f004100350084000a00050004008c008d008b008a01000019000900030200010000000e000c0000093132372e302e302e31"), 3, 2, fromHex("4aef7d77e4686d5dfd9d953dfe280788759ffd440867d687670216da45516b31"), nil, []uint16{0x33, 0x45, 0x39, 0x88, 0x16, 0x32, 0x44, 0x38, 0x87, 0x13, 0x66, 0x90, 0x91, 0x8f, 0x8e, 0x2f, 0x41, 0x35, 0x84, 0xa, 0x5, 0x4, 0x8c, 0x8d, 0x8b, 0x8a}, []uint8{0x0}}
- sendHello := script.NewEvent("send hello", nil, script.Send{msgChan, clientHello});
- setVersion := script.NewEvent("set version", []*script.Event{sendHello}, script.Recv{writeChan, writerSetVersion{3, 2}});
- recvHello := script.NewEvent("recv hello", []*script.Event{setVersion}, script.RecvMatch{writeChan, matchServerHello});
- recvCert := script.NewEvent("recv cert", []*script.Event{recvHello}, script.RecvMatch{writeChan, matchCertificate});
- recvDone := script.NewEvent("recv done", []*script.Event{recvCert}, script.RecvMatch{writeChan, matchDone});
+ sendHello := script.NewEvent("send hello", nil, script.Send{msgChan, clientHello})
+ setVersion := script.NewEvent("set version", []*script.Event{sendHello}, script.Recv{writeChan, writerSetVersion{3, 2}})
+ recvHello := script.NewEvent("recv hello", []*script.Event{setVersion}, script.RecvMatch{writeChan, matchServerHello})
+ recvCert := script.NewEvent("recv cert", []*script.Event{recvHello}, script.RecvMatch{writeChan, matchCertificate})
+ recvDone := script.NewEvent("recv done", []*script.Event{recvCert}, script.RecvMatch{writeChan, matchDone})
- ckx := &clientKeyExchangeMsg{nil, fromHex("872e1fee5f37dd86f3215938ac8de20b302b90074e9fb93097e6b7d1286d0f45abf2daf179deb618bb3c70ed0afee6ee24476ee4649e5a23358143c0f1d9c251")};
- sendCKX := script.NewEvent("send ckx", []*script.Event{recvDone}, script.Send{msgChan, ckx});
+ ckx := &clientKeyExchangeMsg{nil, fromHex("872e1fee5f37dd86f3215938ac8de20b302b90074e9fb93097e6b7d1286d0f45abf2daf179deb618bb3c70ed0afee6ee24476ee4649e5a23358143c0f1d9c251")}
+ sendCKX := script.NewEvent("send ckx", []*script.Event{recvDone}, script.Send{msgChan, ckx})
- sendCCS := script.NewEvent("send ccs", []*script.Event{sendCKX}, script.Send{msgChan, changeCipherSpec{}});
- recvNCS := script.NewEvent("recv done", []*script.Event{sendCCS}, script.RecvMatch{controlChan, matchNewCipherSpec});
+ sendCCS := script.NewEvent("send ccs", []*script.Event{sendCKX}, script.Send{msgChan, changeCipherSpec{}})
+ recvNCS := script.NewEvent("recv done", []*script.Event{sendCCS}, script.RecvMatch{controlChan, matchNewCipherSpec})
- finished := &finishedMsg{nil, fromHex("c8faca5d242f4423325c5b1a")};
- sendFinished := script.NewEvent("send finished", []*script.Event{recvNCS}, script.Send{msgChan, finished});
- recvFinished := script.NewEvent("recv finished", []*script.Event{sendFinished}, script.RecvMatch{writeChan, matchFinished});
- setCipher := script.NewEvent("set cipher", []*script.Event{sendFinished}, script.RecvMatch{writeChan, matchSetCipher});
- recvConnectionState := script.NewEvent("recv state", []*script.Event{sendFinished}, script.Recv{controlChan, ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0}});
+ finished := &finishedMsg{nil, fromHex("c8faca5d242f4423325c5b1a")}
+ sendFinished := script.NewEvent("send finished", []*script.Event{recvNCS}, script.Send{msgChan, finished})
+ recvFinished := script.NewEvent("recv finished", []*script.Event{sendFinished}, script.RecvMatch{writeChan, matchFinished})
+ setCipher := script.NewEvent("set cipher", []*script.Event{sendFinished}, script.RecvMatch{writeChan, matchSetCipher})
+ recvConnectionState := script.NewEvent("recv state", []*script.Event{sendFinished}, script.Recv{controlChan, ConnectionState{true, "TLS_RSA_WITH_RC4_128_SHA", 0}})
- err := script.Perform(0, []*script.Event{sendHello, setVersion, recvHello, recvCert, recvDone, sendCKX, sendCCS, recvNCS, sendFinished, setCipher, recvConnectionState, recvFinished});
+ err := script.Perform(0, []*script.Event{sendHello, setVersion, recvHello, recvCert, recvDone, sendCKX, sendCCS, recvNCS, sendFinished, setCipher, recvConnectionState, recvFinished})
if err != nil {
t.Errorf("Got error: %s", err)
}
@@ -194,9 +194,9 @@ func TestFullHandshake(t *testing.T) {
var testCertificate = fromHex("3082025930820203a003020102020900c2ec326b95228959300d06092a864886f70d01010505003054310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464310d300b0603550403130474657374301e170d3039313032303232323434355a170d3130313032303232323434355a3054310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464310d300b0603550403130474657374305c300d06092a864886f70d0101010500034b003048024100b2990f49c47dfa8cd400ae6a4d1b8a3b6a13642b23f28b003bfb97790ade9a4cc82b8b2a81747ddec08b6296e53a08c331687ef25c4bf4936ba1c0e6041e9d150203010001a381b73081b4301d0603551d0e0416041478a06086837c9293a8c9b70c0bdabdb9d77eeedf3081840603551d23047d307b801478a06086837c9293a8c9b70c0bdabdb9d77eeedfa158a4563054310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464310d300b0603550403130474657374820900c2ec326b95228959300c0603551d13040530030101ff300d06092a864886f70d0101050500034100ac23761ae1349d85a439caad4d0b932b09ea96de1917c3e0507c446f4838cb3076fb4d431db8c1987e96f1d7a8a2054dea3a64ec99a3f0eda4d47a163bf1f6ac")
func bigFromString(s string) *big.Int {
- ret := new(big.Int);
- ret.SetString(s, 10);
- return ret;
+ ret := new(big.Int)
+ ret.SetString(s, 10)
+ return ret
}
var testPrivateKey = &rsa.PrivateKey{
diff --git a/src/pkg/crypto/tls/prf.go b/src/pkg/crypto/tls/prf.go
index b89b59c296..6b9c44c077 100644
--- a/src/pkg/crypto/tls/prf.go
+++ b/src/pkg/crypto/tls/prf.go
@@ -5,59 +5,59 @@
package tls
import (
- "crypto/hmac";
- "crypto/md5";
- "crypto/sha1";
- "hash";
- "os";
- "strings";
+ "crypto/hmac"
+ "crypto/md5"
+ "crypto/sha1"
+ "hash"
+ "os"
+ "strings"
)
// Split a premaster secret in two as specified in RFC 4346, section 5.
func splitPreMasterSecret(secret []byte) (s1, s2 []byte) {
- s1 = secret[0 : (len(secret)+1)/2];
- s2 = secret[len(secret)/2:];
- return;
+ s1 = secret[0 : (len(secret)+1)/2]
+ s2 = secret[len(secret)/2:]
+ return
}
// pHash implements the P_hash function, as defined in RFC 4346, section 5.
func pHash(result, secret, seed []byte, hash hash.Hash) {
- h := hmac.New(hash, secret);
- h.Write(seed);
- a := h.Sum();
+ h := hmac.New(hash, secret)
+ h.Write(seed)
+ a := h.Sum()
- j := 0;
+ j := 0
for j < len(result) {
- h.Reset();
- h.Write(a);
- h.Write(seed);
- b := h.Sum();
- todo := len(b);
+ h.Reset()
+ h.Write(a)
+ h.Write(seed)
+ b := h.Sum()
+ todo := len(b)
if j+todo > len(result) {
todo = len(result) - j
}
- copy(result[j:j+todo], b);
- j += todo;
+ copy(result[j:j+todo], b)
+ j += todo
- h.Reset();
- h.Write(a);
- a = h.Sum();
+ h.Reset()
+ h.Write(a)
+ a = h.Sum()
}
}
// pRF11 implements the TLS 1.1 pseudo-random function, as defined in RFC 4346, section 5.
func pRF11(result, secret, label, seed []byte) {
- hashSHA1 := sha1.New();
- hashMD5 := md5.New();
+ hashSHA1 := sha1.New()
+ hashMD5 := md5.New()
- labelAndSeed := make([]byte, len(label)+len(seed));
- copy(labelAndSeed, label);
- copy(labelAndSeed[len(label):], seed);
+ labelAndSeed := make([]byte, len(label)+len(seed))
+ copy(labelAndSeed, label)
+ copy(labelAndSeed[len(label):], seed)
- s1, s2 := splitPreMasterSecret(secret);
- pHash(result, s1, labelAndSeed, hashMD5);
- result2 := make([]byte, len(result));
- pHash(result2, s2, labelAndSeed, hashSHA1);
+ s1, s2 := splitPreMasterSecret(secret)
+ pHash(result, s1, labelAndSeed, hashMD5)
+ result2 := make([]byte, len(result))
+ pHash(result2, s2, labelAndSeed, hashSHA1)
for i, b := range result2 {
result[i] ^= b
@@ -65,9 +65,9 @@ func pRF11(result, secret, label, seed []byte) {
}
const (
- tlsRandomLength = 32; // Length of a random nonce in TLS 1.1.
- masterSecretLength = 48; // Length of a master secret in TLS 1.1.
- finishedVerifyLength = 12; // Length of verify_data in a Finished message.
+ tlsRandomLength = 32 // Length of a random nonce in TLS 1.1.
+ masterSecretLength = 48 // Length of a master secret in TLS 1.1.
+ finishedVerifyLength = 12 // Length of verify_data in a Finished message.
)
var masterSecretLabel = strings.Bytes("master secret")
@@ -79,32 +79,32 @@ var serverFinishedLabel = strings.Bytes("server finished")
// secret, given the lengths of the MAC and cipher keys, as defined in RFC
// 4346, section 6.3.
func keysFromPreMasterSecret11(preMasterSecret, clientRandom, serverRandom []byte, macLen, keyLen int) (masterSecret, clientMAC, serverMAC, clientKey, serverKey []byte) {
- var seed [tlsRandomLength * 2]byte;
- copy(seed[0:len(clientRandom)], clientRandom);
- copy(seed[len(clientRandom):], serverRandom);
- masterSecret = make([]byte, masterSecretLength);
- pRF11(masterSecret, preMasterSecret, masterSecretLabel, seed[0:]);
+ var seed [tlsRandomLength * 2]byte
+ copy(seed[0:len(clientRandom)], clientRandom)
+ copy(seed[len(clientRandom):], serverRandom)
+ masterSecret = make([]byte, masterSecretLength)
+ pRF11(masterSecret, preMasterSecret, masterSecretLabel, seed[0:])
- copy(seed[0:len(clientRandom)], serverRandom);
- copy(seed[len(serverRandom):], clientRandom);
+ copy(seed[0:len(clientRandom)], serverRandom)
+ copy(seed[len(serverRandom):], clientRandom)
- n := 2*macLen + 2*keyLen;
- keyMaterial := make([]byte, n);
- pRF11(keyMaterial, masterSecret, keyExpansionLabel, seed[0:]);
- clientMAC = keyMaterial[0:macLen];
- serverMAC = keyMaterial[macLen : macLen*2];
- clientKey = keyMaterial[macLen*2 : macLen*2+keyLen];
- serverKey = keyMaterial[macLen*2+keyLen:];
- return;
+ n := 2*macLen + 2*keyLen
+ keyMaterial := make([]byte, n)
+ pRF11(keyMaterial, masterSecret, keyExpansionLabel, seed[0:])
+ clientMAC = keyMaterial[0:macLen]
+ serverMAC = keyMaterial[macLen : macLen*2]
+ clientKey = keyMaterial[macLen*2 : macLen*2+keyLen]
+ serverKey = keyMaterial[macLen*2+keyLen:]
+ return
}
// A finishedHash calculates the hash of a set of handshake messages suitable
// for including in a Finished message.
type finishedHash struct {
- clientMD5 hash.Hash;
- clientSHA1 hash.Hash;
- serverMD5 hash.Hash;
- serverSHA1 hash.Hash;
+ clientMD5 hash.Hash
+ clientSHA1 hash.Hash
+ serverMD5 hash.Hash
+ serverSHA1 hash.Hash
}
func newFinishedHash() finishedHash {
@@ -112,36 +112,36 @@ func newFinishedHash() finishedHash {
}
func (h finishedHash) Write(msg []byte) (n int, err os.Error) {
- h.clientMD5.Write(msg);
- h.clientSHA1.Write(msg);
- h.serverMD5.Write(msg);
- h.serverSHA1.Write(msg);
- return len(msg), nil;
+ h.clientMD5.Write(msg)
+ h.clientSHA1.Write(msg)
+ h.serverMD5.Write(msg)
+ h.serverSHA1.Write(msg)
+ return len(msg), nil
}
// finishedSum calculates the contents of the verify_data member of a Finished
// message given the MD5 and SHA1 hashes of a set of handshake messages.
func finishedSum(md5, sha1, label, masterSecret []byte) []byte {
- seed := make([]byte, len(md5)+len(sha1));
- copy(seed, md5);
- copy(seed[len(md5):], sha1);
- out := make([]byte, finishedVerifyLength);
- pRF11(out, masterSecret, label, seed);
- return out;
+ seed := make([]byte, len(md5)+len(sha1))
+ copy(seed, md5)
+ copy(seed[len(md5):], sha1)
+ out := make([]byte, finishedVerifyLength)
+ pRF11(out, masterSecret, label, seed)
+ return out
}
// clientSum returns the contents of the verify_data member of a client's
// Finished message.
func (h finishedHash) clientSum(masterSecret []byte) []byte {
- md5 := h.clientMD5.Sum();
- sha1 := h.clientSHA1.Sum();
- return finishedSum(md5, sha1, clientFinishedLabel, masterSecret);
+ md5 := h.clientMD5.Sum()
+ sha1 := h.clientSHA1.Sum()
+ return finishedSum(md5, sha1, clientFinishedLabel, masterSecret)
}
// serverSum returns the contents of the verify_data member of a server's
// Finished message.
func (h finishedHash) serverSum(masterSecret []byte) []byte {
- md5 := h.serverMD5.Sum();
- sha1 := h.serverSHA1.Sum();
- return finishedSum(md5, sha1, serverFinishedLabel, masterSecret);
+ md5 := h.serverMD5.Sum()
+ sha1 := h.serverSHA1.Sum()
+ return finishedSum(md5, sha1, serverFinishedLabel, masterSecret)
}
diff --git a/src/pkg/crypto/tls/prf_test.go b/src/pkg/crypto/tls/prf_test.go
index 0d4a4db35e..5c23f368db 100644
--- a/src/pkg/crypto/tls/prf_test.go
+++ b/src/pkg/crypto/tls/prf_test.go
@@ -5,12 +5,12 @@
package tls
import (
- "encoding/hex";
- "testing";
+ "encoding/hex"
+ "testing"
)
type testSplitPreMasterSecretTest struct {
- in, out1, out2 string;
+ in, out1, out2 string
}
var testSplitPreMasterSecretTests = []testSplitPreMasterSecretTest{
@@ -23,10 +23,10 @@ var testSplitPreMasterSecretTests = []testSplitPreMasterSecretTest{
func TestSplitPreMasterSecret(t *testing.T) {
for i, test := range testSplitPreMasterSecretTests {
- in, _ := hex.DecodeString(test.in);
- out1, out2 := splitPreMasterSecret(in);
- s1 := hex.EncodeToString(out1);
- s2 := hex.EncodeToString(out2);
+ in, _ := hex.DecodeString(test.in)
+ out1, out2 := splitPreMasterSecret(in)
+ s1 := hex.EncodeToString(out1)
+ s2 := hex.EncodeToString(out2)
if s1 != test.out1 || s2 != test.out2 {
t.Errorf("#%d: got: (%s, %s) want: (%s, %s)", i, s1, s2, test.out1, test.out2)
}
@@ -34,25 +34,25 @@ func TestSplitPreMasterSecret(t *testing.T) {
}
type testKeysFromTest struct {
- preMasterSecret string;
- clientRandom, serverRandom string;
- masterSecret string;
- clientMAC, serverMAC string;
- clientKey, serverKey string;
- macLen, keyLen int;
+ preMasterSecret string
+ clientRandom, serverRandom string
+ masterSecret string
+ clientMAC, serverMAC string
+ clientKey, serverKey string
+ macLen, keyLen int
}
func TestKeysFromPreMasterSecret(t *testing.T) {
for i, test := range testKeysFromTests {
- in, _ := hex.DecodeString(test.preMasterSecret);
- clientRandom, _ := hex.DecodeString(test.clientRandom);
- serverRandom, _ := hex.DecodeString(test.serverRandom);
- master, clientMAC, serverMAC, clientKey, serverKey := keysFromPreMasterSecret11(in, clientRandom, serverRandom, test.macLen, test.keyLen);
- masterString := hex.EncodeToString(master);
- clientMACString := hex.EncodeToString(clientMAC);
- serverMACString := hex.EncodeToString(serverMAC);
- clientKeyString := hex.EncodeToString(clientKey);
- serverKeyString := hex.EncodeToString(serverKey);
+ in, _ := hex.DecodeString(test.preMasterSecret)
+ clientRandom, _ := hex.DecodeString(test.clientRandom)
+ serverRandom, _ := hex.DecodeString(test.serverRandom)
+ master, clientMAC, serverMAC, clientKey, serverKey := keysFromPreMasterSecret11(in, clientRandom, serverRandom, test.macLen, test.keyLen)
+ masterString := hex.EncodeToString(master)
+ clientMACString := hex.EncodeToString(clientMAC)
+ serverMACString := hex.EncodeToString(serverMAC)
+ clientKeyString := hex.EncodeToString(clientKey)
+ serverKeyString := hex.EncodeToString(serverKey)
if masterString != test.masterSecret ||
clientMACString != test.clientMAC ||
serverMACString != test.serverMAC ||
diff --git a/src/pkg/crypto/tls/record_process.go b/src/pkg/crypto/tls/record_process.go
index e356d67ca2..ddeca0e2b5 100644
--- a/src/pkg/crypto/tls/record_process.go
+++ b/src/pkg/crypto/tls/record_process.go
@@ -10,27 +10,27 @@ package tls
// state, or for a notification when the state changes.
import (
- "container/list";
- "crypto/subtle";
- "hash";
+ "container/list"
+ "crypto/subtle"
+ "hash"
)
// getConnectionState is a request from the application to get the current
// ConnectionState.
type getConnectionState struct {
- reply chan<- ConnectionState;
+ reply chan<- ConnectionState
}
// waitConnectionState is a request from the application to be notified when
// the connection state changes.
type waitConnectionState struct {
- reply chan<- ConnectionState;
+ reply chan<- ConnectionState
}
// connectionStateChange is a message from the handshake processor that the
// connection state has changed.
type connectionStateChange struct {
- connState ConnectionState;
+ connState ConnectionState
}
// changeCipherSpec is a message send to the handshake processor to signal that
@@ -40,32 +40,32 @@ type changeCipherSpec struct{}
// newCipherSpec is a message from the handshake processor that future
// records should be processed with a new cipher and MAC function.
type newCipherSpec struct {
- encrypt encryptor;
- mac hash.Hash;
+ encrypt encryptor
+ mac hash.Hash
}
type recordProcessor struct {
- decrypt encryptor;
- mac hash.Hash;
- seqNum uint64;
- handshakeBuf []byte;
- appDataChan chan<- []byte;
- requestChan <-chan interface{};
- controlChan <-chan interface{};
- recordChan <-chan *record;
- handshakeChan chan<- interface{};
+ decrypt encryptor
+ mac hash.Hash
+ seqNum uint64
+ handshakeBuf []byte
+ appDataChan chan<- []byte
+ requestChan <-chan interface{}
+ controlChan <-chan interface{}
+ recordChan <-chan *record
+ handshakeChan chan<- interface{}
// recordRead is nil when we don't wish to read any more.
- recordRead <-chan *record;
+ recordRead <-chan *record
// appDataSend is nil when len(appData) == 0.
- appDataSend chan<- []byte;
+ appDataSend chan<- []byte
// appData contains any application data queued for upstream.
- appData []byte;
+ appData []byte
// A list of channels waiting for connState to change.
- waitQueue *list.List;
- connState ConnectionState;
- shutdown bool;
- header [13]byte;
+ waitQueue *list.List
+ connState ConnectionState
+ shutdown bool
+ header [13]byte
}
// drainRequestChannel processes messages from the request channel until it's closed.
@@ -84,24 +84,24 @@ func drainRequestChannel(requestChan <-chan interface{}, c ConnectionState) {
}
func (p *recordProcessor) loop(appDataChan chan<- []byte, requestChan <-chan interface{}, controlChan <-chan interface{}, recordChan <-chan *record, handshakeChan chan<- interface{}) {
- noop := nop{};
- p.decrypt = noop;
- p.mac = noop;
- p.waitQueue = list.New();
+ noop := nop{}
+ p.decrypt = noop
+ p.mac = noop
+ p.waitQueue = list.New()
- p.appDataChan = appDataChan;
- p.requestChan = requestChan;
- p.controlChan = controlChan;
- p.recordChan = recordChan;
- p.handshakeChan = handshakeChan;
- p.recordRead = recordChan;
+ p.appDataChan = appDataChan
+ p.requestChan = requestChan
+ p.controlChan = controlChan
+ p.recordChan = recordChan
+ p.handshakeChan = handshakeChan
+ p.recordRead = recordChan
for !p.shutdown {
select {
case p.appDataSend <- p.appData:
- p.appData = nil;
- p.appDataSend = nil;
- p.recordRead = p.recordChan;
+ p.appData = nil
+ p.appDataSend = nil
+ p.recordRead = p.recordChan
case c := <-controlChan:
p.processControlMsg(c)
case r := <-requestChan:
@@ -111,24 +111,24 @@ func (p *recordProcessor) loop(appDataChan chan<- []byte, requestChan <-chan int
}
}
- p.wakeWaiters();
- go drainRequestChannel(p.requestChan, p.connState);
+ p.wakeWaiters()
+ go drainRequestChannel(p.requestChan, p.connState)
go func() {
for _ = range controlChan {
}
- }();
+ }()
- close(handshakeChan);
+ close(handshakeChan)
if len(p.appData) > 0 {
appDataChan <- p.appData
}
- close(appDataChan);
+ close(appDataChan)
}
func (p *recordProcessor) processRequestMsg(requestMsg interface{}) {
if closed(p.requestChan) {
- p.shutdown = true;
- return;
+ p.shutdown = true
+ return
}
switch r := requestMsg.(type) {
@@ -138,51 +138,51 @@ func (p *recordProcessor) processRequestMsg(requestMsg interface{}) {
if p.connState.HandshakeComplete {
r.reply <- p.connState
}
- p.waitQueue.PushBack(r.reply);
+ p.waitQueue.PushBack(r.reply)
}
}
func (p *recordProcessor) processControlMsg(msg interface{}) {
- connState, ok := msg.(ConnectionState);
+ connState, ok := msg.(ConnectionState)
if !ok || closed(p.controlChan) {
- p.shutdown = true;
- return;
+ p.shutdown = true
+ return
}
- p.connState = connState;
- p.wakeWaiters();
+ p.connState = connState
+ p.wakeWaiters()
}
func (p *recordProcessor) wakeWaiters() {
for i := p.waitQueue.Front(); i != nil; i = i.Next() {
i.Value.(chan<- ConnectionState) <- p.connState
}
- p.waitQueue.Init();
+ p.waitQueue.Init()
}
func (p *recordProcessor) processRecord(r *record) {
if closed(p.recordChan) {
- p.shutdown = true;
- return;
+ p.shutdown = true
+ return
}
- p.decrypt.XORKeyStream(r.payload);
+ p.decrypt.XORKeyStream(r.payload)
if len(r.payload) < p.mac.Size() {
- p.error(alertBadRecordMAC);
- return;
+ p.error(alertBadRecordMAC)
+ return
}
- fillMACHeader(&p.header, p.seqNum, len(r.payload)-p.mac.Size(), r);
- p.seqNum++;
+ fillMACHeader(&p.header, p.seqNum, len(r.payload)-p.mac.Size(), r)
+ p.seqNum++
- p.mac.Reset();
- p.mac.Write(p.header[0:13]);
- p.mac.Write(r.payload[0 : len(r.payload)-p.mac.Size()]);
- macBytes := p.mac.Sum();
+ p.mac.Reset()
+ p.mac.Write(p.header[0:13])
+ p.mac.Write(r.payload[0 : len(r.payload)-p.mac.Size()])
+ macBytes := p.mac.Sum()
if subtle.ConstantTimeCompare(macBytes, r.payload[len(r.payload)-p.mac.Size():]) != 1 {
- p.error(alertBadRecordMAC);
- return;
+ p.error(alertBadRecordMAC)
+ return
}
switch r.contentType {
@@ -190,31 +190,31 @@ func (p *recordProcessor) processRecord(r *record) {
p.processHandshakeRecord(r.payload[0 : len(r.payload)-p.mac.Size()])
case recordTypeChangeCipherSpec:
if len(r.payload) != 1 || r.payload[0] != 1 {
- p.error(alertUnexpectedMessage);
- return;
+ p.error(alertUnexpectedMessage)
+ return
}
- p.handshakeChan <- changeCipherSpec{};
- newSpec, ok := (<-p.controlChan).(*newCipherSpec);
+ p.handshakeChan <- changeCipherSpec{}
+ newSpec, ok := (<-p.controlChan).(*newCipherSpec)
if !ok {
- p.connState.Error = alertUnexpectedMessage;
- p.shutdown = true;
- return;
+ p.connState.Error = alertUnexpectedMessage
+ p.shutdown = true
+ return
}
- p.decrypt = newSpec.encrypt;
- p.mac = newSpec.mac;
- p.seqNum = 0;
+ p.decrypt = newSpec.encrypt
+ p.mac = newSpec.mac
+ p.seqNum = 0
case recordTypeApplicationData:
if p.connState.HandshakeComplete == false {
- p.error(alertUnexpectedMessage);
- return;
+ p.error(alertUnexpectedMessage)
+ return
}
- p.recordRead = nil;
- p.appData = r.payload[0 : len(r.payload)-p.mac.Size()];
- p.appDataSend = p.appDataChan;
+ p.recordRead = nil
+ p.appData = r.payload[0 : len(r.payload)-p.mac.Size()]
+ p.appDataSend = p.appDataChan
default:
- p.error(alertUnexpectedMessage);
- return;
+ p.error(alertUnexpectedMessage)
+ return
}
}
@@ -223,61 +223,61 @@ func (p *recordProcessor) processHandshakeRecord(data []byte) {
p.handshakeBuf = data
} else {
if len(p.handshakeBuf) > maxHandshakeMsg {
- p.error(alertInternalError);
- return;
+ p.error(alertInternalError)
+ return
}
- newBuf := make([]byte, len(p.handshakeBuf)+len(data));
- copy(newBuf, p.handshakeBuf);
- copy(newBuf[len(p.handshakeBuf):], data);
- p.handshakeBuf = newBuf;
+ newBuf := make([]byte, len(p.handshakeBuf)+len(data))
+ copy(newBuf, p.handshakeBuf)
+ copy(newBuf[len(p.handshakeBuf):], data)
+ p.handshakeBuf = newBuf
}
for len(p.handshakeBuf) >= 4 {
handshakeLen := int(p.handshakeBuf[1])<<16 |
int(p.handshakeBuf[2])<<8 |
- int(p.handshakeBuf[3]);
+ int(p.handshakeBuf[3])
if handshakeLen+4 > len(p.handshakeBuf) {
break
}
- bytes := p.handshakeBuf[0 : handshakeLen+4];
- p.handshakeBuf = p.handshakeBuf[handshakeLen+4:];
+ bytes := p.handshakeBuf[0 : handshakeLen+4]
+ p.handshakeBuf = p.handshakeBuf[handshakeLen+4:]
if bytes[0] == typeFinished {
// Special case because Finished is synchronous: the
// handshake handler has to tell us if it's ok to start
// forwarding application data.
- m := new(finishedMsg);
+ m := new(finishedMsg)
if !m.unmarshal(bytes) {
p.error(alertUnexpectedMessage)
}
- p.handshakeChan <- m;
- var ok bool;
- p.connState, ok = (<-p.controlChan).(ConnectionState);
+ p.handshakeChan <- m
+ var ok bool
+ p.connState, ok = (<-p.controlChan).(ConnectionState)
if !ok || p.connState.Error != 0 {
- p.shutdown = true;
- return;
+ p.shutdown = true
+ return
}
} else {
- msg, ok := parseHandshakeMsg(bytes);
+ msg, ok := parseHandshakeMsg(bytes)
if !ok {
- p.error(alertUnexpectedMessage);
- return;
+ p.error(alertUnexpectedMessage)
+ return
}
- p.handshakeChan <- msg;
+ p.handshakeChan <- msg
}
}
}
func (p *recordProcessor) error(err alertType) {
- close(p.handshakeChan);
- p.connState.Error = err;
- p.wakeWaiters();
- p.shutdown = true;
+ close(p.handshakeChan)
+ p.connState.Error = err
+ p.wakeWaiters()
+ p.shutdown = true
}
func parseHandshakeMsg(data []byte) (interface{}, bool) {
var m interface {
- unmarshal([]byte) bool;
+ unmarshal([]byte) bool
}
switch data[0] {
@@ -295,6 +295,6 @@ func parseHandshakeMsg(data []byte) (interface{}, bool) {
return nil, false
}
- ok := m.unmarshal(data);
- return m, ok;
+ ok := m.unmarshal(data)
+ return m, ok
}
diff --git a/src/pkg/crypto/tls/record_process_test.go b/src/pkg/crypto/tls/record_process_test.go
index 1d019e30de..65ce3eba95 100644
--- a/src/pkg/crypto/tls/record_process_test.go
+++ b/src/pkg/crypto/tls/record_process_test.go
@@ -5,132 +5,132 @@
package tls
import (
- "encoding/hex";
- "testing";
- "testing/script";
+ "encoding/hex"
+ "testing"
+ "testing/script"
)
func setup() (appDataChan chan []byte, requestChan chan interface{}, controlChan chan interface{}, recordChan chan *record, handshakeChan chan interface{}) {
- rp := new(recordProcessor);
- appDataChan = make(chan []byte);
- requestChan = make(chan interface{});
- controlChan = make(chan interface{});
- recordChan = make(chan *record);
- handshakeChan = make(chan interface{});
+ rp := new(recordProcessor)
+ appDataChan = make(chan []byte)
+ requestChan = make(chan interface{})
+ controlChan = make(chan interface{})
+ recordChan = make(chan *record)
+ handshakeChan = make(chan interface{})
- go rp.loop(appDataChan, requestChan, controlChan, recordChan, handshakeChan);
- return;
+ go rp.loop(appDataChan, requestChan, controlChan, recordChan, handshakeChan)
+ return
}
func fromHex(s string) []byte {
- b, _ := hex.DecodeString(s);
- return b;
+ b, _ := hex.DecodeString(s)
+ return b
}
func TestNullConnectionState(t *testing.T) {
- _, requestChan, controlChan, recordChan, _ := setup();
- defer close(requestChan);
- defer close(controlChan);
- defer close(recordChan);
+ _, requestChan, controlChan, recordChan, _ := setup()
+ defer close(requestChan)
+ defer close(controlChan)
+ defer close(recordChan)
// Test a simple request for the connection state.
- replyChan := make(chan ConnectionState);
- sendReq := script.NewEvent("send request", nil, script.Send{requestChan, getConnectionState{replyChan}});
- getReply := script.NewEvent("get reply", []*script.Event{sendReq}, script.Recv{replyChan, ConnectionState{false, "", 0}});
+ replyChan := make(chan ConnectionState)
+ sendReq := script.NewEvent("send request", nil, script.Send{requestChan, getConnectionState{replyChan}})
+ getReply := script.NewEvent("get reply", []*script.Event{sendReq}, script.Recv{replyChan, ConnectionState{false, "", 0}})
- err := script.Perform(0, []*script.Event{sendReq, getReply});
+ err := script.Perform(0, []*script.Event{sendReq, getReply})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestWaitConnectionState(t *testing.T) {
- _, requestChan, controlChan, recordChan, _ := setup();
- defer close(requestChan);
- defer close(controlChan);
- defer close(recordChan);
+ _, requestChan, controlChan, recordChan, _ := setup()
+ defer close(requestChan)
+ defer close(controlChan)
+ defer close(recordChan)
// Test that waitConnectionState doesn't get a reply until the connection state changes.
- replyChan := make(chan ConnectionState);
- sendReq := script.NewEvent("send request", nil, script.Send{requestChan, waitConnectionState{replyChan}});
- replyChan2 := make(chan ConnectionState);
- sendReq2 := script.NewEvent("send request 2", []*script.Event{sendReq}, script.Send{requestChan, getConnectionState{replyChan2}});
- getReply2 := script.NewEvent("get reply 2", []*script.Event{sendReq2}, script.Recv{replyChan2, ConnectionState{false, "", 0}});
- sendState := script.NewEvent("send state", []*script.Event{getReply2}, script.Send{controlChan, ConnectionState{true, "test", 1}});
- getReply := script.NewEvent("get reply", []*script.Event{sendState}, script.Recv{replyChan, ConnectionState{true, "test", 1}});
+ replyChan := make(chan ConnectionState)
+ sendReq := script.NewEvent("send request", nil, script.Send{requestChan, waitConnectionState{replyChan}})
+ replyChan2 := make(chan ConnectionState)
+ sendReq2 := script.NewEvent("send request 2", []*script.Event{sendReq}, script.Send{requestChan, getConnectionState{replyChan2}})
+ getReply2 := script.NewEvent("get reply 2", []*script.Event{sendReq2}, script.Recv{replyChan2, ConnectionState{false, "", 0}})
+ sendState := script.NewEvent("send state", []*script.Event{getReply2}, script.Send{controlChan, ConnectionState{true, "test", 1}})
+ getReply := script.NewEvent("get reply", []*script.Event{sendState}, script.Recv{replyChan, ConnectionState{true, "test", 1}})
- err := script.Perform(0, []*script.Event{sendReq, sendReq2, getReply2, sendState, getReply});
+ err := script.Perform(0, []*script.Event{sendReq, sendReq2, getReply2, sendState, getReply})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestHandshakeAssembly(t *testing.T) {
- _, requestChan, controlChan, recordChan, handshakeChan := setup();
- defer close(requestChan);
- defer close(controlChan);
- defer close(recordChan);
+ _, requestChan, controlChan, recordChan, handshakeChan := setup()
+ defer close(requestChan)
+ defer close(controlChan)
+ defer close(recordChan)
// Test the reassembly of a fragmented handshake message.
- send1 := script.NewEvent("send 1", nil, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("10000003")}});
- send2 := script.NewEvent("send 2", []*script.Event{send1}, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("0001")}});
- send3 := script.NewEvent("send 3", []*script.Event{send2}, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("42")}});
- recvMsg := script.NewEvent("recv", []*script.Event{send3}, script.Recv{handshakeChan, &clientKeyExchangeMsg{fromHex("10000003000142"), fromHex("42")}});
+ send1 := script.NewEvent("send 1", nil, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("10000003")}})
+ send2 := script.NewEvent("send 2", []*script.Event{send1}, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("0001")}})
+ send3 := script.NewEvent("send 3", []*script.Event{send2}, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("42")}})
+ recvMsg := script.NewEvent("recv", []*script.Event{send3}, script.Recv{handshakeChan, &clientKeyExchangeMsg{fromHex("10000003000142"), fromHex("42")}})
- err := script.Perform(0, []*script.Event{send1, send2, send3, recvMsg});
+ err := script.Perform(0, []*script.Event{send1, send2, send3, recvMsg})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestEarlyApplicationData(t *testing.T) {
- _, requestChan, controlChan, recordChan, handshakeChan := setup();
- defer close(requestChan);
- defer close(controlChan);
- defer close(recordChan);
+ _, requestChan, controlChan, recordChan, handshakeChan := setup()
+ defer close(requestChan)
+ defer close(controlChan)
+ defer close(recordChan)
// Test that applicaton data received before the handshake has completed results in an error.
- send := script.NewEvent("send", nil, script.Send{recordChan, &record{recordTypeApplicationData, 0, 0, fromHex("")}});
- recv := script.NewEvent("recv", []*script.Event{send}, script.Closed{handshakeChan});
+ send := script.NewEvent("send", nil, script.Send{recordChan, &record{recordTypeApplicationData, 0, 0, fromHex("")}})
+ recv := script.NewEvent("recv", []*script.Event{send}, script.Closed{handshakeChan})
- err := script.Perform(0, []*script.Event{send, recv});
+ err := script.Perform(0, []*script.Event{send, recv})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestApplicationData(t *testing.T) {
- appDataChan, requestChan, controlChan, recordChan, handshakeChan := setup();
- defer close(requestChan);
- defer close(controlChan);
- defer close(recordChan);
+ appDataChan, requestChan, controlChan, recordChan, handshakeChan := setup()
+ defer close(requestChan)
+ defer close(controlChan)
+ defer close(recordChan)
// Test that the application data is forwarded after a successful Finished message.
- send1 := script.NewEvent("send 1", nil, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("1400000c000000000000000000000000")}});
- recv1 := script.NewEvent("recv finished", []*script.Event{send1}, script.Recv{handshakeChan, &finishedMsg{fromHex("1400000c000000000000000000000000"), fromHex("000000000000000000000000")}});
- send2 := script.NewEvent("send connState", []*script.Event{recv1}, script.Send{controlChan, ConnectionState{true, "", 0}});
- send3 := script.NewEvent("send 2", []*script.Event{send2}, script.Send{recordChan, &record{recordTypeApplicationData, 0, 0, fromHex("0102")}});
- recv2 := script.NewEvent("recv data", []*script.Event{send3}, script.Recv{appDataChan, []byte{0x01, 0x02}});
+ send1 := script.NewEvent("send 1", nil, script.Send{recordChan, &record{recordTypeHandshake, 0, 0, fromHex("1400000c000000000000000000000000")}})
+ recv1 := script.NewEvent("recv finished", []*script.Event{send1}, script.Recv{handshakeChan, &finishedMsg{fromHex("1400000c000000000000000000000000"), fromHex("000000000000000000000000")}})
+ send2 := script.NewEvent("send connState", []*script.Event{recv1}, script.Send{controlChan, ConnectionState{true, "", 0}})
+ send3 := script.NewEvent("send 2", []*script.Event{send2}, script.Send{recordChan, &record{recordTypeApplicationData, 0, 0, fromHex("0102")}})
+ recv2 := script.NewEvent("recv data", []*script.Event{send3}, script.Recv{appDataChan, []byte{0x01, 0x02}})
- err := script.Perform(0, []*script.Event{send1, recv1, send2, send3, recv2});
+ err := script.Perform(0, []*script.Event{send1, recv1, send2, send3, recv2})
if err != nil {
t.Errorf("Got error: %s", err)
}
}
func TestInvalidChangeCipherSpec(t *testing.T) {
- appDataChan, requestChan, controlChan, recordChan, handshakeChan := setup();
- defer close(requestChan);
- defer close(controlChan);
- defer close(recordChan);
+ appDataChan, requestChan, controlChan, recordChan, handshakeChan := setup()
+ defer close(requestChan)
+ defer close(controlChan)
+ defer close(recordChan)
- send1 := script.NewEvent("send 1", nil, script.Send{recordChan, &record{recordTypeChangeCipherSpec, 0, 0, []byte{1}}});
- recv1 := script.NewEvent("recv 1", []*script.Event{send1}, script.Recv{handshakeChan, changeCipherSpec{}});
- send2 := script.NewEvent("send 2", []*script.Event{recv1}, script.Send{controlChan, ConnectionState{false, "", 42}});
- close := script.NewEvent("close 1", []*script.Event{send2}, script.Closed{appDataChan});
- close2 := script.NewEvent("close 2", []*script.Event{send2}, script.Closed{handshakeChan});
+ send1 := script.NewEvent("send 1", nil, script.Send{recordChan, &record{recordTypeChangeCipherSpec, 0, 0, []byte{1}}})
+ recv1 := script.NewEvent("recv 1", []*script.Event{send1}, script.Recv{handshakeChan, changeCipherSpec{}})
+ send2 := script.NewEvent("send 2", []*script.Event{recv1}, script.Send{controlChan, ConnectionState{false, "", 42}})
+ close := script.NewEvent("close 1", []*script.Event{send2}, script.Closed{appDataChan})
+ close2 := script.NewEvent("close 2", []*script.Event{send2}, script.Closed{handshakeChan})
- err := script.Perform(0, []*script.Event{send1, recv1, send2, close, close2});
+ err := script.Perform(0, []*script.Event{send1, recv1, send2, close, close2})
if err != nil {
t.Errorf("Got error: %s", err)
}
diff --git a/src/pkg/crypto/tls/record_read.go b/src/pkg/crypto/tls/record_read.go
index 518a1361be..0ddd884a4e 100644
--- a/src/pkg/crypto/tls/record_read.go
+++ b/src/pkg/crypto/tls/record_read.go
@@ -9,34 +9,34 @@ package tls
// it's outbound channel. On error, it closes its outbound channel.
import (
- "io";
- "bufio";
+ "io"
+ "bufio"
)
// recordReader loops, reading TLS records from source and writing them to the
// given channel. The channel is closed on EOF or on error.
func recordReader(c chan<- *record, source io.Reader) {
- defer close(c);
- buf := bufio.NewReader(source);
+ defer close(c)
+ buf := bufio.NewReader(source)
for {
- var header [5]byte;
- n, _ := buf.Read(header[0:]);
+ var header [5]byte
+ n, _ := buf.Read(header[0:])
if n != 5 {
return
}
- recordLength := int(header[3])<<8 | int(header[4]);
+ recordLength := int(header[3])<<8 | int(header[4])
if recordLength > maxTLSCiphertext {
return
}
- payload := make([]byte, recordLength);
- n, _ = buf.Read(payload);
+ payload := make([]byte, recordLength)
+ n, _ = buf.Read(payload)
if n != recordLength {
return
}
- c <- &record{recordType(header[0]), header[1], header[2], payload};
+ c <- &record{recordType(header[0]), header[1], header[2], payload}
}
}
diff --git a/src/pkg/crypto/tls/record_read_test.go b/src/pkg/crypto/tls/record_read_test.go
index ce1a8e6b4c..f897599ad0 100644
--- a/src/pkg/crypto/tls/record_read_test.go
+++ b/src/pkg/crypto/tls/record_read_test.go
@@ -5,9 +5,9 @@
package tls
import (
- "bytes";
- "testing";
- "testing/iotest";
+ "bytes"
+ "testing"
+ "testing/iotest"
)
func matchRecord(r1, r2 *record) bool {
@@ -20,12 +20,12 @@ func matchRecord(r1, r2 *record) bool {
return r1.contentType == r2.contentType &&
r1.major == r2.major &&
r1.minor == r2.minor &&
- bytes.Compare(r1.payload, r2.payload) == 0;
+ bytes.Compare(r1.payload, r2.payload) == 0
}
type recordReaderTest struct {
- in []byte;
- out []*record;
+ in []byte
+ out []*record
}
var recordReaderTests = []recordReaderTest{
@@ -42,31 +42,31 @@ var recordReaderTests = []recordReaderTest{
func TestRecordReader(t *testing.T) {
for i, test := range recordReaderTests {
- buf := bytes.NewBuffer(test.in);
- c := make(chan *record);
- go recordReader(c, buf);
- matchRecordReaderOutput(t, i, test, c);
+ buf := bytes.NewBuffer(test.in)
+ c := make(chan *record)
+ go recordReader(c, buf)
+ matchRecordReaderOutput(t, i, test, c)
- buf = bytes.NewBuffer(test.in);
- buf2 := iotest.OneByteReader(buf);
- c = make(chan *record);
- go recordReader(c, buf2);
- matchRecordReaderOutput(t, i*2, test, c);
+ buf = bytes.NewBuffer(test.in)
+ buf2 := iotest.OneByteReader(buf)
+ c = make(chan *record)
+ go recordReader(c, buf2)
+ matchRecordReaderOutput(t, i*2, test, c)
}
}
func matchRecordReaderOutput(t *testing.T, i int, test recordReaderTest, c <-chan *record) {
for j, r1 := range test.out {
- r2 := <-c;
+ r2 := <-c
if r2 == nil {
- t.Errorf("#%d truncated after %d values", i, j);
- break;
+ t.Errorf("#%d truncated after %d values", i, j)
+ break
}
if !matchRecord(r1, r2) {
t.Errorf("#%d (%d) got:%#v want:%#v", i, j, r2, r1)
}
}
- <-c;
+ <-c
if !closed(c) {
t.Errorf("#%d: channel didn't close", i)
}
diff --git a/src/pkg/crypto/tls/record_write.go b/src/pkg/crypto/tls/record_write.go
index f55a214c3a..5f3fb5b16b 100644
--- a/src/pkg/crypto/tls/record_write.go
+++ b/src/pkg/crypto/tls/record_write.go
@@ -5,9 +5,9 @@
package tls
import (
- "fmt";
- "hash";
- "io";
+ "fmt"
+ "hash"
+ "io"
)
// writerEnableApplicationData is a message which instructs recordWriter to
@@ -17,14 +17,14 @@ type writerEnableApplicationData struct{}
// writerChangeCipherSpec updates the encryption and MAC functions and resets
// the sequence count.
type writerChangeCipherSpec struct {
- encryptor encryptor;
- mac hash.Hash;
+ encryptor encryptor
+ mac hash.Hash
}
// writerSetVersion sets the version number bytes that we included in the
// record header for future records.
type writerSetVersion struct {
- major, minor uint8;
+ major, minor uint8
}
// A recordWriter accepts messages from the handshake processor and
@@ -32,37 +32,37 @@ type writerSetVersion struct {
// writing. It doesn't read from the application data channel until the
// handshake processor has signaled that the handshake is complete.
type recordWriter struct {
- writer io.Writer;
- encryptor encryptor;
- mac hash.Hash;
- seqNum uint64;
- major, minor uint8;
- shutdown bool;
- appChan <-chan []byte;
- controlChan <-chan interface{};
- header [13]byte;
+ writer io.Writer
+ encryptor encryptor
+ mac hash.Hash
+ seqNum uint64
+ major, minor uint8
+ shutdown bool
+ appChan <-chan []byte
+ controlChan <-chan interface{}
+ header [13]byte
}
func (w *recordWriter) loop(writer io.Writer, appChan <-chan []byte, controlChan <-chan interface{}) {
- w.writer = writer;
- w.encryptor = nop{};
- w.mac = nop{};
- w.appChan = appChan;
- w.controlChan = controlChan;
+ w.writer = writer
+ w.encryptor = nop{}
+ w.mac = nop{}
+ w.appChan = appChan
+ w.controlChan = controlChan
for !w.shutdown {
- msg := <-controlChan;
+ msg := <-controlChan
if _, ok := msg.(writerEnableApplicationData); ok {
break
}
- w.processControlMessage(msg);
+ w.processControlMessage(msg)
}
for !w.shutdown {
// Always process control messages first.
if controlMsg, ok := <-controlChan; ok {
- w.processControlMessage(controlMsg);
- continue;
+ w.processControlMessage(controlMsg)
+ continue
}
select {
@@ -89,58 +89,58 @@ func (w *recordWriter) loop(writer io.Writer, appChan <-chan []byte, controlChan
// fillMACHeader generates a MAC header. See RFC 4346, section 6.2.3.1.
func fillMACHeader(header *[13]byte, seqNum uint64, length int, r *record) {
- header[0] = uint8(seqNum >> 56);
- header[1] = uint8(seqNum >> 48);
- header[2] = uint8(seqNum >> 40);
- header[3] = uint8(seqNum >> 32);
- header[4] = uint8(seqNum >> 24);
- header[5] = uint8(seqNum >> 16);
- header[6] = uint8(seqNum >> 8);
- header[7] = uint8(seqNum);
- header[8] = uint8(r.contentType);
- header[9] = r.major;
- header[10] = r.minor;
- header[11] = uint8(length >> 8);
- header[12] = uint8(length);
+ header[0] = uint8(seqNum >> 56)
+ header[1] = uint8(seqNum >> 48)
+ header[2] = uint8(seqNum >> 40)
+ header[3] = uint8(seqNum >> 32)
+ header[4] = uint8(seqNum >> 24)
+ header[5] = uint8(seqNum >> 16)
+ header[6] = uint8(seqNum >> 8)
+ header[7] = uint8(seqNum)
+ header[8] = uint8(r.contentType)
+ header[9] = r.major
+ header[10] = r.minor
+ header[11] = uint8(length >> 8)
+ header[12] = uint8(length)
}
func (w *recordWriter) writeRecord(r *record) {
- w.mac.Reset();
+ w.mac.Reset()
- fillMACHeader(&w.header, w.seqNum, len(r.payload), r);
+ fillMACHeader(&w.header, w.seqNum, len(r.payload), r)
- w.mac.Write(w.header[0:13]);
- w.mac.Write(r.payload);
- macBytes := w.mac.Sum();
+ w.mac.Write(w.header[0:13])
+ w.mac.Write(r.payload)
+ macBytes := w.mac.Sum()
- w.encryptor.XORKeyStream(r.payload);
- w.encryptor.XORKeyStream(macBytes);
+ w.encryptor.XORKeyStream(r.payload)
+ w.encryptor.XORKeyStream(macBytes)
- length := len(r.payload) + len(macBytes);
- w.header[11] = uint8(length >> 8);
- w.header[12] = uint8(length);
- w.writer.Write(w.header[8:13]);
- w.writer.Write(r.payload);
- w.writer.Write(macBytes);
+ length := len(r.payload) + len(macBytes)
+ w.header[11] = uint8(length >> 8)
+ w.header[12] = uint8(length)
+ w.writer.Write(w.header[8:13])
+ w.writer.Write(r.payload)
+ w.writer.Write(macBytes)
- w.seqNum++;
+ w.seqNum++
}
func (w *recordWriter) processControlMessage(controlMsg interface{}) {
if controlMsg == nil {
- w.shutdown = true;
- return;
+ w.shutdown = true
+ return
}
switch msg := controlMsg.(type) {
case writerChangeCipherSpec:
- w.writeRecord(&record{recordTypeChangeCipherSpec, w.major, w.minor, []byte{0x01}});
- w.encryptor = msg.encryptor;
- w.mac = msg.mac;
- w.seqNum = 0;
+ w.writeRecord(&record{recordTypeChangeCipherSpec, w.major, w.minor, []byte{0x01}})
+ w.encryptor = msg.encryptor
+ w.mac = msg.mac
+ w.seqNum = 0
case writerSetVersion:
- w.major = msg.major;
- w.minor = msg.minor;
+ w.major = msg.major
+ w.minor = msg.minor
case alert:
w.writeRecord(&record{recordTypeAlert, w.major, w.minor, []byte{byte(msg.level), byte(msg.error)}})
case handshakeMessage:
@@ -153,18 +153,18 @@ func (w *recordWriter) processControlMessage(controlMsg interface{}) {
func (w *recordWriter) processAppMessage(appMsg []byte) {
if closed(w.appChan) {
- w.writeRecord(&record{recordTypeApplicationData, w.major, w.minor, []byte{byte(alertCloseNotify)}});
- w.shutdown = true;
- return;
+ w.writeRecord(&record{recordTypeApplicationData, w.major, w.minor, []byte{byte(alertCloseNotify)}})
+ w.shutdown = true
+ return
}
- var done int;
+ var done int
for done < len(appMsg) {
- todo := len(appMsg);
+ todo := len(appMsg)
if todo > maxTLSPlaintext {
todo = maxTLSPlaintext
}
- w.writeRecord(&record{recordTypeApplicationData, w.major, w.minor, appMsg[done : done+todo]});
- done += todo;
+ w.writeRecord(&record{recordTypeApplicationData, w.major, w.minor, appMsg[done : done+todo]})
+ done += todo
}
}
diff --git a/src/pkg/crypto/tls/tls.go b/src/pkg/crypto/tls/tls.go
index c5a0f69d5d..29d918e4b0 100644
--- a/src/pkg/crypto/tls/tls.go
+++ b/src/pkg/crypto/tls/tls.go
@@ -6,26 +6,26 @@
package tls
import (
- "io";
- "os";
- "net";
- "time";
+ "io"
+ "os"
+ "net"
+ "time"
)
// A Conn represents a secure connection.
type Conn struct {
- net.Conn;
- writeChan chan<- []byte;
- readChan <-chan []byte;
- requestChan chan<- interface{};
- readBuf []byte;
- eof bool;
- readTimeout, writeTimeout int64;
+ net.Conn
+ writeChan chan<- []byte
+ readChan <-chan []byte
+ requestChan chan<- interface{}
+ readBuf []byte
+ eof bool
+ readTimeout, writeTimeout int64
}
func timeout(c chan<- bool, nsecs int64) {
- time.Sleep(nsecs);
- c <- true;
+ time.Sleep(nsecs)
+ c <- true
}
func (tls *Conn) Read(p []byte) (int, os.Error) {
@@ -34,10 +34,10 @@ func (tls *Conn) Read(p []byte) (int, os.Error) {
return 0, os.EOF
}
- var timeoutChan chan bool;
+ var timeoutChan chan bool
if tls.readTimeout > 0 {
- timeoutChan = make(chan bool);
- go timeout(timeoutChan, tls.readTimeout);
+ timeoutChan = make(chan bool)
+ go timeout(timeoutChan, tls.readTimeout)
}
select {
@@ -53,14 +53,14 @@ func (tls *Conn) Read(p []byte) (int, os.Error) {
return 0, io.ErrUnexpectedEOF
}
if len(tls.readBuf) == 0 {
- tls.eof = true;
- return 0, os.EOF;
+ tls.eof = true
+ return 0, os.EOF
}
}
- n := copy(p, tls.readBuf);
- tls.readBuf = tls.readBuf[n:];
- return n, nil;
+ n := copy(p, tls.readBuf)
+ tls.readBuf = tls.readBuf[n:]
+ return n, nil
}
func (tls *Conn) Write(p []byte) (int, os.Error) {
@@ -68,10 +68,10 @@ func (tls *Conn) Write(p []byte) (int, os.Error) {
return 0, os.EOF
}
- var timeoutChan chan bool;
+ var timeoutChan chan bool
if tls.writeTimeout > 0 {
- timeoutChan = make(chan bool);
- go timeout(timeoutChan, tls.writeTimeout);
+ timeoutChan = make(chan bool)
+ go timeout(timeoutChan, tls.writeTimeout)
}
select {
@@ -80,73 +80,73 @@ func (tls *Conn) Write(p []byte) (int, os.Error) {
return 0, os.EAGAIN
}
- return len(p), nil;
+ return len(p), nil
}
func (tls *Conn) Close() os.Error {
- close(tls.writeChan);
- close(tls.requestChan);
- tls.eof = true;
- return nil;
+ close(tls.writeChan)
+ close(tls.requestChan)
+ tls.eof = true
+ return nil
}
func (tls *Conn) SetTimeout(nsec int64) os.Error {
- tls.readTimeout = nsec;
- tls.writeTimeout = nsec;
- return nil;
+ tls.readTimeout = nsec
+ tls.writeTimeout = nsec
+ return nil
}
func (tls *Conn) SetReadTimeout(nsec int64) os.Error {
- tls.readTimeout = nsec;
- return nil;
+ tls.readTimeout = nsec
+ return nil
}
func (tls *Conn) SetWriteTimeout(nsec int64) os.Error {
- tls.writeTimeout = nsec;
- return nil;
+ tls.writeTimeout = nsec
+ return nil
}
func (tls *Conn) GetConnectionState() ConnectionState {
- replyChan := make(chan ConnectionState);
- tls.requestChan <- getConnectionState{replyChan};
- return <-replyChan;
+ replyChan := make(chan ConnectionState)
+ tls.requestChan <- getConnectionState{replyChan}
+ return <-replyChan
}
func (tls *Conn) WaitConnectionState() ConnectionState {
- replyChan := make(chan ConnectionState);
- tls.requestChan <- waitConnectionState{replyChan};
- return <-replyChan;
+ replyChan := make(chan ConnectionState)
+ tls.requestChan <- waitConnectionState{replyChan}
+ return <-replyChan
}
type handshaker interface {
- loop(writeChan chan<- interface{}, controlChan chan<- interface{}, msgChan <-chan interface{}, config *Config);
+ loop(writeChan chan<- interface{}, controlChan chan<- interface{}, msgChan <-chan interface{}, config *Config)
}
// Server establishes a secure connection over the given connection and acts
// as a TLS server.
func startTLSGoroutines(conn net.Conn, h handshaker, config *Config) *Conn {
- tls := new(Conn);
- tls.Conn = conn;
+ tls := new(Conn)
+ tls.Conn = conn
- writeChan := make(chan []byte);
- readChan := make(chan []byte);
- requestChan := make(chan interface{});
+ writeChan := make(chan []byte)
+ readChan := make(chan []byte)
+ requestChan := make(chan interface{})
- tls.writeChan = writeChan;
- tls.readChan = readChan;
- tls.requestChan = requestChan;
+ tls.writeChan = writeChan
+ tls.readChan = readChan
+ tls.requestChan = requestChan
- handshakeWriterChan := make(chan interface{});
- processorHandshakeChan := make(chan interface{});
- handshakeProcessorChan := make(chan interface{});
- readerProcessorChan := make(chan *record);
+ handshakeWriterChan := make(chan interface{})
+ processorHandshakeChan := make(chan interface{})
+ handshakeProcessorChan := make(chan interface{})
+ readerProcessorChan := make(chan *record)
- go new(recordWriter).loop(conn, writeChan, handshakeWriterChan);
- go recordReader(readerProcessorChan, conn);
- go new(recordProcessor).loop(readChan, requestChan, handshakeProcessorChan, readerProcessorChan, processorHandshakeChan);
- go h.loop(handshakeWriterChan, handshakeProcessorChan, processorHandshakeChan, config);
+ go new(recordWriter).loop(conn, writeChan, handshakeWriterChan)
+ go recordReader(readerProcessorChan, conn)
+ go new(recordProcessor).loop(readChan, requestChan, handshakeProcessorChan, readerProcessorChan, processorHandshakeChan)
+ go h.loop(handshakeWriterChan, handshakeProcessorChan, processorHandshakeChan, config)
- return tls;
+ return tls
}
func Server(conn net.Conn, config *Config) *Conn {
@@ -158,28 +158,28 @@ func Client(conn net.Conn, config *Config) *Conn {
}
type Listener struct {
- listener net.Listener;
- config *Config;
+ listener net.Listener
+ config *Config
}
func (l Listener) Accept() (c net.Conn, err os.Error) {
- c, err = l.listener.Accept();
+ c, err = l.listener.Accept()
if err != nil {
return
}
- c = Server(c, l.config);
- return;
+ c = Server(c, l.config)
+ return
}
-func (l Listener) Close() os.Error { return l.listener.Close() }
+func (l Listener) Close() os.Error { return l.listener.Close() }
-func (l Listener) Addr() net.Addr { return l.listener.Addr() }
+func (l Listener) Addr() net.Addr { return l.listener.Addr() }
// NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
func NewListener(listener net.Listener, config *Config) (l Listener) {
- l.listener = listener;
- l.config = config;
- return;
+ l.listener = listener
+ l.config = config
+ return
}
diff --git a/src/pkg/crypto/x509/x509.go b/src/pkg/crypto/x509/x509.go
index 6a6239b1b6..dcd12f05fb 100644
--- a/src/pkg/crypto/x509/x509.go
+++ b/src/pkg/crypto/x509/x509.go
@@ -6,25 +6,25 @@
package x509
import (
- "asn1";
- "big";
- "container/vector";
- "crypto/rsa";
- "crypto/sha1";
- "hash";
- "os";
- "strings";
- "time";
+ "asn1"
+ "big"
+ "container/vector"
+ "crypto/rsa"
+ "crypto/sha1"
+ "hash"
+ "os"
+ "strings"
+ "time"
)
// pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
type pkcs1PrivateKey struct {
- Version int;
- N asn1.RawValue;
- E int;
- D asn1.RawValue;
- P asn1.RawValue;
- Q asn1.RawValue;
+ Version int
+ N asn1.RawValue
+ E int
+ D asn1.RawValue
+ P asn1.RawValue
+ Q asn1.RawValue
}
// rawValueIsInteger returns true iff the given ASN.1 RawValue is an INTEGER type.
@@ -34,11 +34,11 @@ func rawValueIsInteger(raw *asn1.RawValue) bool {
// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
- var priv pkcs1PrivateKey;
- rest, err := asn1.Unmarshal(&priv, der);
+ var priv pkcs1PrivateKey
+ rest, err := asn1.Unmarshal(&priv, der)
if len(rest) > 0 {
- err = asn1.SyntaxError{"trailing data"};
- return;
+ err = asn1.SyntaxError{"trailing data"}
+ return
}
if err != nil {
return
@@ -48,8 +48,8 @@ func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
!rawValueIsInteger(&priv.D) ||
!rawValueIsInteger(&priv.P) ||
!rawValueIsInteger(&priv.Q) {
- err = asn1.StructuralError{"tags don't match"};
- return;
+ err = asn1.StructuralError{"tags don't match"}
+ return
}
key = &rsa.PrivateKey{
@@ -60,39 +60,39 @@ func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
D: new(big.Int).SetBytes(priv.D.Bytes),
P: new(big.Int).SetBytes(priv.P.Bytes),
Q: new(big.Int).SetBytes(priv.Q.Bytes),
- };
+ }
- err = key.Validate();
+ err = key.Validate()
if err != nil {
return nil, err
}
- return;
+ return
}
// These structures reflect the ASN.1 structure of X.509 certificates.:
type certificate struct {
- TBSCertificate tbsCertificate;
- SignatureAlgorithm algorithmIdentifier;
- SignatureValue asn1.BitString;
+ TBSCertificate tbsCertificate
+ SignatureAlgorithm algorithmIdentifier
+ SignatureValue asn1.BitString
}
type tbsCertificate struct {
- Raw asn1.RawContent;
- Version int "optional,explicit,default:1,tag:0";
- SerialNumber asn1.RawValue;
- SignatureAlgorithm algorithmIdentifier;
- Issuer rdnSequence;
- Validity validity;
- Subject rdnSequence;
- PublicKey publicKeyInfo;
- UniqueId asn1.BitString "optional,explicit,tag:1";
- SubjectUniqueId asn1.BitString "optional,explicit,tag:2";
- Extensions []extension "optional,explicit,tag:3";
+ Raw asn1.RawContent
+ Version int "optional,explicit,default:1,tag:0"
+ SerialNumber asn1.RawValue
+ SignatureAlgorithm algorithmIdentifier
+ Issuer rdnSequence
+ Validity validity
+ Subject rdnSequence
+ PublicKey publicKeyInfo
+ UniqueId asn1.BitString "optional,explicit,tag:1"
+ SubjectUniqueId asn1.BitString "optional,explicit,tag:2"
+ Extensions []extension "optional,explicit,tag:3"
}
type algorithmIdentifier struct {
- Algorithm asn1.ObjectIdentifier;
+ Algorithm asn1.ObjectIdentifier
}
type rdnSequence []relativeDistinguishedName
@@ -100,55 +100,55 @@ type rdnSequence []relativeDistinguishedName
type relativeDistinguishedName []attributeTypeAndValue
type attributeTypeAndValue struct {
- Type asn1.ObjectIdentifier;
- Value interface{};
+ Type asn1.ObjectIdentifier
+ Value interface{}
}
type validity struct {
- NotBefore, NotAfter *time.Time;
+ NotBefore, NotAfter *time.Time
}
type publicKeyInfo struct {
- Algorithm algorithmIdentifier;
- PublicKey asn1.BitString;
+ Algorithm algorithmIdentifier
+ PublicKey asn1.BitString
}
type extension struct {
- Id asn1.ObjectIdentifier;
- Critical bool "optional";
- Value []byte;
+ Id asn1.ObjectIdentifier
+ Critical bool "optional"
+ Value []byte
}
// RFC 5280, 4.2.1.1
type authKeyId struct {
- Id []byte "optional,tag:0";
+ Id []byte "optional,tag:0"
}
type SignatureAlgorithm int
const (
- UnknownSignatureAlgorithm SignatureAlgorithm = iota;
- MD2WithRSA;
- MD5WithRSA;
- SHA1WithRSA;
- SHA256WithRSA;
- SHA384WithRSA;
- SHA512WithRSA;
+ UnknownSignatureAlgorithm SignatureAlgorithm = iota
+ MD2WithRSA
+ MD5WithRSA
+ SHA1WithRSA
+ SHA256WithRSA
+ SHA384WithRSA
+ SHA512WithRSA
)
type PublicKeyAlgorithm int
const (
- UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota;
- RSA;
+ UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
+ RSA
)
// Name represents an X.509 distinguished name. This only includes the common
// elements of a DN. Additional elements in the name are ignored.
type Name struct {
- Country, Organization, OrganizationalUnit string;
- CommonName, SerialNumber, Locality string;
- Province, StreetAddress, PostalCode string;
+ Country, Organization, OrganizationalUnit string
+ CommonName, SerialNumber, Locality string
+ Province, StreetAddress, PostalCode string
}
func (n *Name) fillFromRDNSequence(rdns *rdnSequence) {
@@ -156,13 +156,13 @@ func (n *Name) fillFromRDNSequence(rdns *rdnSequence) {
if len(rdn) == 0 {
continue
}
- atv := rdn[0];
- value, ok := atv.Value.(string);
+ atv := rdn[0]
+ value, ok := atv.Value.(string)
if !ok {
continue
}
- t := atv.Type;
+ t := atv.Type
if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 {
switch t[3] {
case 3:
@@ -207,7 +207,7 @@ func getSignatureAlgorithmFromOID(oid []int) SignatureAlgorithm {
}
}
- return UnknownSignatureAlgorithm;
+ return UnknownSignatureAlgorithm
}
func getPublicKeyAlgorithmFromOID(oid []int) PublicKeyAlgorithm {
@@ -219,7 +219,7 @@ func getPublicKeyAlgorithmFromOID(oid []int) PublicKeyAlgorithm {
}
}
- return UnknownPublicKeyAlgorithm;
+ return UnknownPublicKeyAlgorithm
}
// KeyUsage represents the set of actions that are valid for a given key. It's
@@ -227,43 +227,43 @@ func getPublicKeyAlgorithmFromOID(oid []int) PublicKeyAlgorithm {
type KeyUsage int
const (
- KeyUsageDigitalSignature KeyUsage = 1 << iota;
- KeyUsageContentCommitment;
- KeyUsageKeyEncipherment;
- KeyUsageDataEncipherment;
- KeyUsageKeyAgreement;
- KeyUsageCertSign;
- KeyUsageCRLSign;
- KeyUsageEncipherOnly;
- KeyUsageDecipherOnly;
+ KeyUsageDigitalSignature KeyUsage = 1 << iota
+ KeyUsageContentCommitment
+ KeyUsageKeyEncipherment
+ KeyUsageDataEncipherment
+ KeyUsageKeyAgreement
+ KeyUsageCertSign
+ KeyUsageCRLSign
+ KeyUsageEncipherOnly
+ KeyUsageDecipherOnly
)
// A Certificate represents an X.509 certificate.
type Certificate struct {
- Raw []byte; // Raw ASN.1 DER contents.
- Signature []byte;
- SignatureAlgorithm SignatureAlgorithm;
+ Raw []byte // Raw ASN.1 DER contents.
+ Signature []byte
+ SignatureAlgorithm SignatureAlgorithm
- PublicKeyAlgorithm PublicKeyAlgorithm;
- PublicKey interface{};
+ PublicKeyAlgorithm PublicKeyAlgorithm
+ PublicKey interface{}
- Version int;
- SerialNumber []byte;
- Issuer Name;
- Subject Name;
- NotBefore, NotAfter *time.Time; // Validity bounds.
- KeyUsage KeyUsage;
+ Version int
+ SerialNumber []byte
+ Issuer Name
+ Subject Name
+ NotBefore, NotAfter *time.Time // Validity bounds.
+ KeyUsage KeyUsage
- BasicConstraintsValid bool; // if true then the next two fields are valid.
- IsCA bool;
- MaxPathLen int;
+ BasicConstraintsValid bool // if true then the next two fields are valid.
+ IsCA bool
+ MaxPathLen int
- SubjectKeyId []byte;
- AuthorityKeyId []byte;
+ SubjectKeyId []byte
+ AuthorityKeyId []byte
// Subject Alternate Name values
- DNSNames []string;
- EmailAddresses []string;
+ DNSNames []string
+ EmailAddresses []string
}
// UnsupportedAlgorithmError results from attempting to perform an operation
@@ -306,26 +306,26 @@ func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err os.Error) {
// TODO(agl): don't ignore the path length constraint.
- var h hash.Hash;
- var hashType rsa.PKCS1v15Hash;
+ var h hash.Hash
+ var hashType rsa.PKCS1v15Hash
switch c.SignatureAlgorithm {
case SHA1WithRSA:
- h = sha1.New();
- hashType = rsa.HashSHA1;
+ h = sha1.New()
+ hashType = rsa.HashSHA1
default:
return UnsupportedAlgorithmError{}
}
- pub, ok := parent.PublicKey.(*rsa.PublicKey);
+ pub, ok := parent.PublicKey.(*rsa.PublicKey)
if !ok {
return UnsupportedAlgorithmError{}
}
- h.Write(c.Raw);
- digest := h.Sum();
+ h.Write(c.Raw)
+ digest := h.Sum()
- return rsa.VerifyPKCS1v15(pub, hashType, digest, c.Signature);
+ return rsa.VerifyPKCS1v15(pub, hashType, digest, c.Signature)
}
func matchHostnames(pattern, host string) bool {
@@ -333,8 +333,8 @@ func matchHostnames(pattern, host string) bool {
return false
}
- patternParts := strings.Split(pattern, ".", 0);
- hostParts := strings.Split(host, ".", 0);
+ patternParts := strings.Split(pattern, ".", 0)
+ hostParts := strings.Split(host, ".", 0)
if len(patternParts) != len(hostParts) {
return false
@@ -349,7 +349,7 @@ func matchHostnames(pattern, host string) bool {
}
}
- return true;
+ return true
}
// IsValidForHost returns true iff c is a valid certificate for the given host.
@@ -361,10 +361,10 @@ func (c *Certificate) IsValidForHost(h string) bool {
}
}
// If Subject Alt Name is given, we ignore the common name.
- return false;
+ return false
}
- return matchHostnames(c.Subject.CommonName, h);
+ return matchHostnames(c.Subject.CommonName, h)
}
type UnhandledCriticalExtension struct{}
@@ -374,20 +374,20 @@ func (h UnhandledCriticalExtension) String() string {
}
type basicConstraints struct {
- IsCA bool "optional";
- MaxPathLen int "optional";
+ IsCA bool "optional"
+ MaxPathLen int "optional"
}
type rsaPublicKey struct {
- N asn1.RawValue;
- E int;
+ N asn1.RawValue
+ E int
}
func parsePublicKey(algo PublicKeyAlgorithm, asn1Data []byte) (interface{}, os.Error) {
switch algo {
case RSA:
- p := new(rsaPublicKey);
- _, err := asn1.Unmarshal(p, asn1Data);
+ p := new(rsaPublicKey)
+ _, err := asn1.Unmarshal(p, asn1Data)
if err != nil {
return nil, err
}
@@ -399,79 +399,79 @@ func parsePublicKey(algo PublicKeyAlgorithm, asn1Data []byte) (interface{}, os.E
pub := &rsa.PublicKey{
E: p.E,
N: new(big.Int).SetBytes(p.N.Bytes),
- };
- return pub, nil;
+ }
+ return pub, nil
default:
return nil, nil
}
- panic("unreachable");
+ panic("unreachable")
}
func appendString(in []string, v string) (out []string) {
if cap(in)-len(in) < 1 {
- out = make([]string, len(in)+1, len(in)*2+1);
+ out = make([]string, len(in)+1, len(in)*2+1)
for i, v := range in {
out[i] = v
}
} else {
out = in[0 : len(in)+1]
}
- out[len(in)] = v;
- return out;
+ out[len(in)] = v
+ return out
}
func parseCertificate(in *certificate) (*Certificate, os.Error) {
- out := new(Certificate);
- out.Raw = in.TBSCertificate.Raw;
+ out := new(Certificate)
+ out.Raw = in.TBSCertificate.Raw
- out.Signature = in.SignatureValue.RightAlign();
+ out.Signature = in.SignatureValue.RightAlign()
out.SignatureAlgorithm =
- getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm);
+ getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
out.PublicKeyAlgorithm =
- getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm);
- var err os.Error;
- out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, in.TBSCertificate.PublicKey.PublicKey.RightAlign());
+ getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
+ var err os.Error
+ out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, in.TBSCertificate.PublicKey.PublicKey.RightAlign())
if err != nil {
return nil, err
}
- out.Version = in.TBSCertificate.Version;
- out.SerialNumber = in.TBSCertificate.SerialNumber.Bytes;
- out.Issuer.fillFromRDNSequence(&in.TBSCertificate.Issuer);
- out.Subject.fillFromRDNSequence(&in.TBSCertificate.Subject);
- out.NotBefore = in.TBSCertificate.Validity.NotBefore;
- out.NotAfter = in.TBSCertificate.Validity.NotAfter;
+ out.Version = in.TBSCertificate.Version
+ out.SerialNumber = in.TBSCertificate.SerialNumber.Bytes
+ out.Issuer.fillFromRDNSequence(&in.TBSCertificate.Issuer)
+ out.Subject.fillFromRDNSequence(&in.TBSCertificate.Subject)
+ out.NotBefore = in.TBSCertificate.Validity.NotBefore
+ out.NotAfter = in.TBSCertificate.Validity.NotAfter
for _, e := range in.TBSCertificate.Extensions {
if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
switch e.Id[3] {
case 15:
// RFC 5280, 4.2.1.3
- var usageBits asn1.BitString;
- _, err := asn1.Unmarshal(&usageBits, e.Value);
+ var usageBits asn1.BitString
+ _, err := asn1.Unmarshal(&usageBits, e.Value)
if err == nil {
- var usage int;
+ var usage int
for i := 0; i < 9; i++ {
if usageBits.At(i) != 0 {
usage |= 1 << uint(i)
}
}
- out.KeyUsage = KeyUsage(usage);
- continue;
+ out.KeyUsage = KeyUsage(usage)
+ continue
}
case 19:
// RFC 5280, 4.2.1.9
- var constriants basicConstraints;
- _, err := asn1.Unmarshal(&constriants, e.Value);
+ var constriants basicConstraints
+ _, err := asn1.Unmarshal(&constriants, e.Value)
if err == nil {
- out.BasicConstraintsValid = true;
- out.IsCA = constriants.IsCA;
- out.MaxPathLen = constriants.MaxPathLen;
- continue;
+ out.BasicConstraintsValid = true
+ out.IsCA = constriants.IsCA
+ out.MaxPathLen = constriants.MaxPathLen
+ continue
}
case 17:
// RFC 5280, 4.2.1.6
@@ -490,8 +490,8 @@ func parseCertificate(in *certificate) (*Certificate, os.Error) {
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }
- var seq asn1.RawValue;
- _, err := asn1.Unmarshal(&seq, e.Value);
+ var seq asn1.RawValue
+ _, err := asn1.Unmarshal(&seq, e.Value)
if err != nil {
return nil, err
}
@@ -499,22 +499,22 @@ func parseCertificate(in *certificate) (*Certificate, os.Error) {
return nil, asn1.StructuralError{"bad SAN sequence"}
}
- parsedName := false;
+ parsedName := false
- rest := seq.Bytes;
+ rest := seq.Bytes
for len(rest) > 0 {
- var v asn1.RawValue;
- rest, err = asn1.Unmarshal(&v, rest);
+ var v asn1.RawValue
+ rest, err = asn1.Unmarshal(&v, rest)
if err != nil {
return nil, err
}
switch v.Tag {
case 1:
- out.EmailAddresses = appendString(out.EmailAddresses, string(v.Bytes));
- parsedName = true;
+ out.EmailAddresses = appendString(out.EmailAddresses, string(v.Bytes))
+ parsedName = true
case 2:
- out.DNSNames = appendString(out.DNSNames, string(v.Bytes));
- parsedName = true;
+ out.DNSNames = appendString(out.DNSNames, string(v.Bytes))
+ parsedName = true
}
}
@@ -526,18 +526,18 @@ func parseCertificate(in *certificate) (*Certificate, os.Error) {
case 35:
// RFC 5280, 4.2.1.1
- var a authKeyId;
- _, err = asn1.Unmarshal(&a, e.Value);
+ var a authKeyId
+ _, err = asn1.Unmarshal(&a, e.Value)
if err != nil {
return nil, err
}
- out.AuthorityKeyId = a.Id;
- continue;
+ out.AuthorityKeyId = a.Id
+ continue
case 14:
// RFC 5280, 4.2.1.2
- out.SubjectKeyId = e.Value;
- continue;
+ out.SubjectKeyId = e.Value
+ continue
}
}
@@ -546,13 +546,13 @@ func parseCertificate(in *certificate) (*Certificate, os.Error) {
}
}
- return out, nil;
+ return out, nil
}
// ParseCertificate parses a single certificate from the given ASN.1 DER data.
func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) {
- var cert certificate;
- rest, err := asn1.Unmarshal(&cert, asn1Data);
+ var cert certificate
+ rest, err := asn1.Unmarshal(&cert, asn1Data)
if err != nil {
return nil, err
}
@@ -560,32 +560,32 @@ func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) {
return nil, asn1.SyntaxError{"trailing data"}
}
- return parseCertificate(&cert);
+ return parseCertificate(&cert)
}
// ParseCertificates parses one or more certificates from the given ASN.1 DER
// data. The certificates must be concatenated with no intermediate padding.
func ParseCertificates(asn1Data []byte) ([]*Certificate, os.Error) {
- v := new(vector.Vector);
+ v := new(vector.Vector)
for len(asn1Data) > 0 {
- cert := new(certificate);
- var err os.Error;
- asn1Data, err = asn1.Unmarshal(cert, asn1Data);
+ cert := new(certificate)
+ var err os.Error
+ asn1Data, err = asn1.Unmarshal(cert, asn1Data)
if err != nil {
return nil, err
}
- v.Push(cert);
+ v.Push(cert)
}
- ret := make([]*Certificate, v.Len());
+ ret := make([]*Certificate, v.Len())
for i := 0; i < v.Len(); i++ {
- cert, err := parseCertificate(v.At(i).(*certificate));
+ cert, err := parseCertificate(v.At(i).(*certificate))
if err != nil {
return nil, err
}
- ret[i] = cert;
+ ret[i] = cert
}
- return ret, nil;
+ return ret, nil
}
diff --git a/src/pkg/crypto/x509/x509_test.go b/src/pkg/crypto/x509/x509_test.go
index c6a63253f1..796807b4bb 100644
--- a/src/pkg/crypto/x509/x509_test.go
+++ b/src/pkg/crypto/x509/x509_test.go
@@ -5,18 +5,18 @@
package x509
import (
- "big";
- "crypto/rsa";
- "encoding/hex";
- "encoding/pem";
- "reflect";
- "strings";
- "testing";
+ "big"
+ "crypto/rsa"
+ "encoding/hex"
+ "encoding/pem"
+ "reflect"
+ "strings"
+ "testing"
)
func TestParsePKCS1PrivateKey(t *testing.T) {
- block, _ := pem.Decode(strings.Bytes(pemPrivateKey));
- priv, err := ParsePKCS1PrivateKey(block.Bytes);
+ block, _ := pem.Decode(strings.Bytes(pemPrivateKey))
+ priv, err := ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
t.Errorf("Failed to parse private key: %s", err)
}
@@ -37,9 +37,9 @@ tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
`
func bigFromString(s string) *big.Int {
- ret := new(big.Int);
- ret.SetString(s, 10);
- return ret;
+ ret := new(big.Int)
+ ret.SetString(s, 10)
+ return ret
}
var rsaPrivateKey = &rsa.PrivateKey{
@@ -53,8 +53,8 @@ var rsaPrivateKey = &rsa.PrivateKey{
}
type matchHostnamesTest struct {
- pattern, host string;
- ok bool;
+ pattern, host string
+ ok bool
}
var matchHostnamesTests = []matchHostnamesTest{
@@ -72,7 +72,7 @@ var matchHostnamesTests = []matchHostnamesTest{
func TestMatchHostnames(t *testing.T) {
for i, test := range matchHostnamesTests {
- r := matchHostnames(test.pattern, test.host);
+ r := matchHostnames(test.pattern, test.host)
if r != test.ok {
t.Errorf("#%d mismatch got: %t want: %t", i, r, test.ok)
}
@@ -80,17 +80,17 @@ func TestMatchHostnames(t *testing.T) {
}
func TestCertificateParse(t *testing.T) {
- s, _ := hex.DecodeString(certBytes);
- certs, err := ParseCertificates(s);
+ s, _ := hex.DecodeString(certBytes)
+ certs, err := ParseCertificates(s)
if err != nil {
t.Error(err)
}
if len(certs) != 2 {
- t.Errorf("Wrong number of certs: got %d want 2", len(certs));
- return;
+ t.Errorf("Wrong number of certs: got %d want 2", len(certs))
+ return
}
- err = certs[0].CheckSignatureFrom(certs[1]);
+ err = certs[0].CheckSignatureFrom(certs[1])
if err != nil {
t.Error(err)
}
diff --git a/src/pkg/crypto/xtea/block.go b/src/pkg/crypto/xtea/block.go
index 7cf768153b..dfb82e1e2f 100644
--- a/src/pkg/crypto/xtea/block.go
+++ b/src/pkg/crypto/xtea/block.go
@@ -17,50 +17,50 @@ const numRounds = 64
// blockToUint32 reads an 8 byte slice into two uint32s.
// The block is treated as big endian.
func blockToUint32(src []byte) (uint32, uint32) {
- r0 := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]);
- r1 := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]);
- return r0, r1;
+ r0 := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
+ r1 := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
+ return r0, r1
}
// uint32ToBlock writes two unint32s into an 8 byte data block.
// Values are written as big endian.
func uint32ToBlock(v0, v1 uint32, dst []byte) {
- dst[0] = byte(v0 >> 24);
- dst[1] = byte(v0 >> 16);
- dst[2] = byte(v0 >> 8);
- dst[3] = byte(v0);
- dst[4] = byte(v1 >> 24);
- dst[5] = byte(v1 >> 16);
- dst[6] = byte(v1 >> 8);
- dst[7] = byte(v1 >> 0);
+ dst[0] = byte(v0 >> 24)
+ dst[1] = byte(v0 >> 16)
+ dst[2] = byte(v0 >> 8)
+ dst[3] = byte(v0)
+ dst[4] = byte(v1 >> 24)
+ dst[5] = byte(v1 >> 16)
+ dst[6] = byte(v1 >> 8)
+ dst[7] = byte(v1 >> 0)
}
// encryptBlock encrypts a single 8 byte block using XTEA.
func encryptBlock(c *Cipher, src, dst []byte) {
- v0, v1 := blockToUint32(src);
+ v0, v1 := blockToUint32(src)
// Two rounds of XTEA applied per loop
for i := 0; i < numRounds; {
- v0 += ((v1<<4 ^ v1>>5) + v1) ^ c.table[i];
- i++;
- v1 += ((v0<<4 ^ v0>>5) + v0) ^ c.table[i];
- i++;
+ v0 += ((v1<<4 ^ v1>>5) + v1) ^ c.table[i]
+ i++
+ v1 += ((v0<<4 ^ v0>>5) + v0) ^ c.table[i]
+ i++
}
- uint32ToBlock(v0, v1, dst);
+ uint32ToBlock(v0, v1, dst)
}
// decryptBlock decrypt a single 8 byte block using XTEA.
func decryptBlock(c *Cipher, src, dst []byte) {
- v0, v1 := blockToUint32(src);
+ v0, v1 := blockToUint32(src)
// Two rounds of XTEA applied per loop
for i := numRounds; i > 0; {
- i--;
- v1 -= ((v0<<4 ^ v0>>5) + v0) ^ c.table[i];
- i--;
- v0 -= ((v1<<4 ^ v1>>5) + v1) ^ c.table[i];
+ i--
+ v1 -= ((v0<<4 ^ v0>>5) + v0) ^ c.table[i]
+ i--
+ v0 -= ((v1<<4 ^ v1>>5) + v1) ^ c.table[i]
}
- uint32ToBlock(v0, v1, dst);
+ uint32ToBlock(v0, v1, dst)
}
diff --git a/src/pkg/crypto/xtea/cipher.go b/src/pkg/crypto/xtea/cipher.go
index 71545b5acc..4fb3acbef3 100644
--- a/src/pkg/crypto/xtea/cipher.go
+++ b/src/pkg/crypto/xtea/cipher.go
@@ -9,8 +9,8 @@ package xtea
// For details, see http://www.cix.co.uk/~klockstone/xtea.pdf
import (
- "os";
- "strconv";
+ "os"
+ "strconv"
)
// The XTEA block size in bytes.
@@ -19,7 +19,7 @@ const BlockSize = 8
// A Cipher is an instance of an XTEA cipher using a particular key.
// table contains a series of precalculated values that are used each round.
type Cipher struct {
- table [64]uint32;
+ table [64]uint32
}
type KeySizeError int
@@ -32,7 +32,7 @@ func (k KeySizeError) String() string {
// The key argument should be the XTEA key.
// XTEA only supports 128 bit (16 byte) keys.
func NewCipher(key []byte) (*Cipher, os.Error) {
- k := len(key);
+ k := len(key)
switch k {
default:
return nil, KeySizeError(k)
@@ -40,25 +40,25 @@ func NewCipher(key []byte) (*Cipher, os.Error) {
break
}
- c := new(Cipher);
- initCipher(c, key);
+ c := new(Cipher)
+ initCipher(c, key)
- return c, nil;
+ return c, nil
}
// BlockSize returns the XTEA block size, 8 bytes.
// It is necessary to satisfy the Key interface in the
// package "crypto/modes".
-func (c *Cipher) BlockSize() int { return BlockSize }
+func (c *Cipher) BlockSize() int { return BlockSize }
// Encrypt encrypts the 8 byte buffer src using the key and stores the result in dst.
// Note that for amounts of data larger than a block,
// it is not safe to just call Encrypt on successive blocks;
// instead, use an encryption mode like XTEACBC (see modes.go).
-func (c *Cipher) Encrypt(src, dst []byte) { encryptBlock(c, src, dst) }
+func (c *Cipher) Encrypt(src, dst []byte) { encryptBlock(c, src, dst) }
// Decrypt decrypts the 8 byte buffer src using the key k and stores the result in dst.
-func (c *Cipher) Decrypt(src, dst []byte) { decryptBlock(c, src, dst) }
+func (c *Cipher) Decrypt(src, dst []byte) { decryptBlock(c, src, dst) }
// Reset zeros the table, so that it will no longer appear in the process's memory.
func (c *Cipher) Reset() {
@@ -71,22 +71,22 @@ func (c *Cipher) Reset() {
// of precalculated values that are based on the key.
func initCipher(c *Cipher, key []byte) {
// Load the key into four uint32s
- var k [4]uint32;
+ var k [4]uint32
for i := 0; i < len(k); i++ {
- j := i << 2; // Multiply by 4
- k[i] = uint32(key[j+0])<<24 | uint32(key[j+1])<<16 | uint32(key[j+2])<<8 | uint32(key[j+3]);
+ j := i << 2 // Multiply by 4
+ k[i] = uint32(key[j+0])<<24 | uint32(key[j+1])<<16 | uint32(key[j+2])<<8 | uint32(key[j+3])
}
// Precalculate the table
- const delta = 0x9E3779B9;
- var sum uint32 = 0;
+ const delta = 0x9E3779B9
+ var sum uint32 = 0
// Two rounds of XTEA applied per loop
for i := 0; i < numRounds; {
- c.table[i] = sum + k[sum&3];
- i++;
- sum += delta;
- c.table[i] = sum + k[(sum>>11)&3];
- i++;
+ c.table[i] = sum + k[sum&3]
+ i++
+ sum += delta
+ c.table[i] = sum + k[(sum>>11)&3]
+ i++
}
}
diff --git a/src/pkg/crypto/xtea/xtea_test.go b/src/pkg/crypto/xtea/xtea_test.go
index 26221c4b42..94756f79f5 100644
--- a/src/pkg/crypto/xtea/xtea_test.go
+++ b/src/pkg/crypto/xtea/xtea_test.go
@@ -5,7 +5,7 @@
package xtea
import (
- "testing";
+ "testing"
)
// A sample test key for when we just want to initialise a cipher
@@ -14,20 +14,20 @@ var testKey = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
// Test that the block size for XTEA is correct
func TestBlocksize(t *testing.T) {
if BlockSize != 8 {
- t.Errorf("BlockSize constant - expected 8, got %d", BlockSize);
- return;
+ t.Errorf("BlockSize constant - expected 8, got %d", BlockSize)
+ return
}
- c, err := NewCipher(testKey);
+ c, err := NewCipher(testKey)
if err != nil {
- t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err);
- return;
+ t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err)
+ return
}
- result := c.BlockSize();
+ result := c.BlockSize()
if result != 8 {
- t.Errorf("BlockSize function - expected 8, gotr %d", result);
- return;
+ t.Errorf("BlockSize function - expected 8, gotr %d", result)
+ return
}
}
@@ -45,16 +45,16 @@ var testTable = []uint32{
// Test that the cipher context is initialised correctly
func TestCipherInit(t *testing.T) {
- c, err := NewCipher(testKey);
+ c, err := NewCipher(testKey)
if err != nil {
- t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err);
- return;
+ t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err)
+ return
}
for i := 0; i < len(c.table); i++ {
if c.table[i] != testTable[i] {
- t.Errorf("NewCipher() failed to initialise Cipher.table[%d] correctly. Expected %08X, got %08X", i, testTable[i], c.table[i]);
- break;
+ t.Errorf("NewCipher() failed to initialise Cipher.table[%d] correctly. Expected %08X, got %08X", i, testTable[i], c.table[i])
+ break
}
}
}
@@ -65,17 +65,17 @@ func TestInvalidKeySize(t *testing.T) {
key := []byte{
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
- };
+ }
- _, err := NewCipher(key);
+ _, err := NewCipher(key)
if err == nil {
t.Errorf("Invalid key size %d didn't result in an error.", len(key))
}
// Test a short key
- key = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77};
+ key = []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}
- _, err = NewCipher(key);
+ _, err = NewCipher(key)
if err == nil {
t.Errorf("Invalid key size %d didn't result in an error.", len(key))
}
@@ -83,51 +83,51 @@ func TestInvalidKeySize(t *testing.T) {
// Test that we can correctly decode some bytes we have encoded
func TestEncodeDecode(t *testing.T) {
- original := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
- input := original;
- output := make([]byte, BlockSize);
+ original := []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}
+ input := original
+ output := make([]byte, BlockSize)
- c, err := NewCipher(testKey);
+ c, err := NewCipher(testKey)
if err != nil {
- t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err);
- return;
+ t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err)
+ return
}
// Encrypt the input block
- c.Encrypt(input, output);
+ c.Encrypt(input, output)
// Check that the output does not match the input
- differs := false;
+ differs := false
for i := 0; i < len(input); i++ {
if output[i] != input[i] {
- differs = true;
- break;
+ differs = true
+ break
}
}
if differs == false {
- t.Error("Cipher.Encrypt: Failed to encrypt the input block.");
- return;
+ t.Error("Cipher.Encrypt: Failed to encrypt the input block.")
+ return
}
// Decrypt the block we just encrypted
- input = output;
- output = make([]byte, BlockSize);
- c.Decrypt(input, output);
+ input = output
+ output = make([]byte, BlockSize)
+ c.Decrypt(input, output)
// Check that the output from decrypt matches our initial input
for i := 0; i < len(input); i++ {
if output[i] != original[i] {
- t.Errorf("Decrypted byte %d differed. Expected %02X, got %02X\n", i, original[i], output[i]);
- return;
+ t.Errorf("Decrypted byte %d differed. Expected %02X, got %02X\n", i, original[i], output[i])
+ return
}
}
}
// Test Vectors
type CryptTest struct {
- key []byte;
- plainText []byte;
- cipherText []byte;
+ key []byte
+ plainText []byte
+ cipherText []byte
}
var CryptTests = []CryptTest{
@@ -189,19 +189,19 @@ var CryptTests = []CryptTest{
// Test encryption
func TestCipherEncrypt(t *testing.T) {
for i, tt := range CryptTests {
- c, err := NewCipher(tt.key);
+ c, err := NewCipher(tt.key)
if err != nil {
- t.Errorf("NewCipher(%d bytes), vector %d = %s", len(tt.key), i, err);
- continue;
+ t.Errorf("NewCipher(%d bytes), vector %d = %s", len(tt.key), i, err)
+ continue
}
- out := make([]byte, len(tt.plainText));
- c.Encrypt(tt.plainText, out);
+ out := make([]byte, len(tt.plainText))
+ c.Encrypt(tt.plainText, out)
for j := 0; j < len(out); j++ {
if out[j] != tt.cipherText[j] {
- t.Errorf("Cipher.Encrypt %d: out[%d] = %02X, expected %02X", i, j, out[j], tt.cipherText[j]);
- break;
+ t.Errorf("Cipher.Encrypt %d: out[%d] = %02X, expected %02X", i, j, out[j], tt.cipherText[j])
+ break
}
}
}
@@ -210,19 +210,19 @@ func TestCipherEncrypt(t *testing.T) {
// Test decryption
func TestCipherDecrypt(t *testing.T) {
for i, tt := range CryptTests {
- c, err := NewCipher(tt.key);
+ c, err := NewCipher(tt.key)
if err != nil {
- t.Errorf("NewCipher(%d bytes), vector %d = %s", len(tt.key), i, err);
- continue;
+ t.Errorf("NewCipher(%d bytes), vector %d = %s", len(tt.key), i, err)
+ continue
}
- out := make([]byte, len(tt.cipherText));
- c.Decrypt(tt.cipherText, out);
+ out := make([]byte, len(tt.cipherText))
+ c.Decrypt(tt.cipherText, out)
for j := 0; j < len(out); j++ {
if out[j] != tt.plainText[j] {
- t.Errorf("Cipher.Decrypt %d: out[%d] = %02X, expected %02X", i, j, out[j], tt.plainText[j]);
- break;
+ t.Errorf("Cipher.Decrypt %d: out[%d] = %02X, expected %02X", i, j, out[j], tt.plainText[j])
+ break
}
}
}
@@ -230,17 +230,17 @@ func TestCipherDecrypt(t *testing.T) {
// Test resetting the cipher context
func TestReset(t *testing.T) {
- c, err := NewCipher(testKey);
+ c, err := NewCipher(testKey)
if err != nil {
- t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err);
- return;
+ t.Errorf("NewCipher(%d bytes) = %s", len(testKey), err)
+ return
}
- c.Reset();
+ c.Reset()
for i := 0; i < len(c.table); i++ {
if c.table[i] != 0 {
- t.Errorf("Cipher.Reset: Failed to clear Cipher.table[%d]. expected 0, got %08X", i, c.table[i]);
- return;
+ t.Errorf("Cipher.Reset: Failed to clear Cipher.table[%d]. expected 0, got %08X", i, c.table[i])
+ return
}
}
}