Commit 2fd401c8 by Ian Lance Taylor

libgo: Update to weekly.2011-11-02.

From-SVN: r181964
parent 02e9018f
...@@ -21,7 +21,7 @@ func f(left, right chan int) { ...@@ -21,7 +21,7 @@ func f(left, right chan int) {
func main() { func main() {
var n = 10000 var n = 10000
if len(os.Args) > 1 { if len(os.Args) > 1 {
var err os.Error var err error
n, err = strconv.Atoi(os.Args[1]) n, err = strconv.Atoi(os.Args[1])
if err != nil { if err != nil {
print("bad arg\n") print("bad arg\n")
......
...@@ -14,7 +14,7 @@ import ( ...@@ -14,7 +14,7 @@ import (
func main() { func main() {
ga, e0 := os.Getenverror("GOARCH") ga, e0 := os.Getenverror("GOARCH")
if e0 != nil { if e0 != nil {
print("$GOARCH: ", e0.String(), "\n") print("$GOARCH: ", e0.Error(), "\n")
os.Exit(1) os.Exit(1)
} }
if ga != runtime.GOARCH { if ga != runtime.GOARCH {
...@@ -23,7 +23,7 @@ func main() { ...@@ -23,7 +23,7 @@ func main() {
} }
xxx, e1 := os.Getenverror("DOES_NOT_EXIST") xxx, e1 := os.Getenverror("DOES_NOT_EXIST")
if e1 != os.ENOENV { if e1 != os.ENOENV {
print("$DOES_NOT_EXIST=", xxx, "; err = ", e1.String(), "\n") print("$DOES_NOT_EXIST=", xxx, "; err = ", e1.Error(), "\n")
os.Exit(1) os.Exit(1)
} }
} }
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
package main package main
import os "os" import os "os"
type _ os.Error type _ os.FileInfo
func f() (os int) { func f() (os int) {
// In the next line "os" should refer to the result variable, not // In the next line "os" should refer to the result variable, not
// to the package. // to the package.
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
package main package main
import "os" import "errors"
// Issue 481: closures and var declarations // Issue 481: closures and var declarations
// with multiple variables assigned from one // with multiple variables assigned from one
...@@ -22,7 +22,7 @@ func main() { ...@@ -22,7 +22,7 @@ func main() {
} }
}() }()
var conn, _ = Dial("tcp", "", listen.Addr().String()) var conn, _ = Dial("tcp", "", listen.Addr().Error())
_ = conn _ = conn
} }
...@@ -37,8 +37,8 @@ func Listen(x, y string) (T, string) { ...@@ -37,8 +37,8 @@ func Listen(x, y string) (T, string) {
return global, y return global, y
} }
func (t T) Addr() os.Error { func (t T) Addr() error {
return os.NewError("stringer") return errors.New("stringer")
} }
func (t T) Accept() (int, string) { func (t T) Accept() (int, string) {
......
...@@ -18,9 +18,9 @@ func f() string { ...@@ -18,9 +18,9 @@ func f() string {
return "abc" return "abc"
} }
func g() *os.Error { func g() *error {
trace += "g" trace += "g"
var x os.Error var x error
return &x return &x
} }
...@@ -35,7 +35,6 @@ func i() *int { ...@@ -35,7 +35,6 @@ func i() *int {
return &i return &i
} }
func main() { func main() {
m := make(map[string]int) m := make(map[string]int)
m[f()], *g() = strconv.Atoi(h()) m[f()], *g() = strconv.Atoi(h())
...@@ -43,7 +42,7 @@ func main() { ...@@ -43,7 +42,7 @@ func main() {
println("BUG", m["abc"], trace) println("BUG", m["abc"], trace)
panic("fail") panic("fail")
} }
mm := make(map[string]os.Error) mm := make(map[string]error)
trace = "" trace = ""
mm["abc"] = os.EINVAL mm["abc"] = os.EINVAL
*i(), mm[f()] = strconv.Atoi(h()) *i(), mm[f()] = strconv.Atoi(h())
......
...@@ -6,36 +6,34 @@ ...@@ -6,36 +6,34 @@
package p package p
import "os" func f() (_ int, err error) {
func f() (_ int, err os.Error) {
return return
} }
func g() (x int, _ os.Error) { func g() (x int, _ error) {
return return
} }
func h() (_ int, _ os.Error) { func h() (_ int, _ error) {
return return
} }
func i() (int, os.Error) { func i() (int, error) {
return // ERROR "not enough arguments to return" return // ERROR "not enough arguments to return"
} }
func f1() (_ int, err os.Error) { func f1() (_ int, err error) {
return 1, nil return 1, nil
} }
func g1() (x int, _ os.Error) { func g1() (x int, _ error) {
return 1, nil return 1, nil
} }
func h1() (_ int, _ os.Error) { func h1() (_ int, _ error) {
return 1, nil return 1, nil
} }
func ii() (int, os.Error) { func ii() (int, error) {
return 1, nil return 1, nil
} }
...@@ -6,22 +6,22 @@ ...@@ -6,22 +6,22 @@
package main package main
import "os" import "io"
func f() (_ string, x float64, err os.Error) { func f() (_ string, x float64, err error) {
return return
} }
func g() (_ string, x float64, err os.Error) { func g() (_ string, x float64, err error) {
return "hello", 3.14, os.EOF return "hello", 3.14, io.EOF
} }
var _ func() (string, float64, os.Error) = f var _ func() (string, float64, error) = f
var _ func() (string, float64, os.Error) = g var _ func() (string, float64, error) = g
func main() { func main() {
x, y, z := g() x, y, z := g()
if x != "hello" || y != 3.14 || z != os.EOF { if x != "hello" || y != 3.14 || z != io.EOF {
println("wrong", x, len(x), y, z) println("wrong", x, len(x), y, z)
} }
} }
......
...@@ -9,12 +9,8 @@ ...@@ -9,12 +9,8 @@
package main package main
import (
"os"
)
type Inner struct { type Inner struct {
F func() os.Error F func() error
} }
type Outer struct { type Outer struct {
...@@ -23,4 +19,4 @@ type Outer struct { ...@@ -23,4 +19,4 @@ type Outer struct {
// calls makeclosure twice on same closure // calls makeclosure twice on same closure
var Foo = Outer{[]Inner{Inner{func() os.Error{ return nil }}}} var Foo = Outer{[]Inner{Inner{func() error { return nil }}}}
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package main package main
import os "os"
type t1 int type t1 int
type t2 int type t2 int
...@@ -23,7 +22,7 @@ func f8(os int) int ...@@ -23,7 +22,7 @@ func f8(os int) int
func f9(os int) int { func f9(os int) int {
return os return os
} }
func f10(err os.Error) os.Error { func f10(err error) error {
return err return err
} }
func f11(t1 string) string { func f11(t1 string) string {
......
...@@ -13,13 +13,12 @@ import _os_ "os" ...@@ -13,13 +13,12 @@ import _os_ "os"
import "os" import "os"
import . "os" import . "os"
func f(e os.Error) func f(e *os.File)
func main() { func main() {
var _e_ _os_.Error var _e_ *_os_.File
var dot Error var dot *File
f(_e_) f(_e_)
f(dot) f(dot)
} }
...@@ -11,10 +11,7 @@ ...@@ -11,10 +11,7 @@
package main package main
import ( import "strings"
"os"
"strings"
)
var x = make([]byte, 10) var x = make([]byte, 10)
...@@ -33,7 +30,7 @@ func mustRecover(s string) { ...@@ -33,7 +30,7 @@ func mustRecover(s string) {
if v == nil { if v == nil {
panic("expected panic") panic("expected panic")
} }
if e := v.(os.Error).String(); strings.Index(e, s) < 0 { if e := v.(error).Error(); strings.Index(e, s) < 0 {
panic("want: " + s + "; have: " + e) panic("want: " + s + "; have: " + e)
} }
} }
......
...@@ -35,7 +35,7 @@ func check(name string, f func(), err string) { ...@@ -35,7 +35,7 @@ func check(name string, f func(), err string) {
println(name, "panicked but not with runtime.Error") println(name, "panicked but not with runtime.Error")
return return
} }
s := runt.String() s := runt.Error()
if strings.Index(s, err) < 0 { if strings.Index(s, err) < 0 {
bug() bug()
println(name, "panicked with", s, "not", err) println(name, "panicked with", s, "not", err)
......
941b8015061a 780c85032b17
The first line of this file holds the Mercurial revision number of the The first line of this file holds the Mercurial revision number of the
last merge done from the master library sources. last merge done from the master library sources.
...@@ -107,6 +107,7 @@ toolexeclibgo_DATA = \ ...@@ -107,6 +107,7 @@ toolexeclibgo_DATA = \
cmath.gox \ cmath.gox \
crypto.gox \ crypto.gox \
csv.gox \ csv.gox \
errors.gox \
exec.gox \ exec.gox \
expvar.gox \ expvar.gox \
flag.gox \ flag.gox \
...@@ -563,6 +564,9 @@ go_csv_files = \ ...@@ -563,6 +564,9 @@ go_csv_files = \
go/csv/reader.go \ go/csv/reader.go \
go/csv/writer.go go/csv/writer.go
go_errors_files = \
go/errors/errors.go
go_exec_files = \ go_exec_files = \
go/exec/exec.go \ go/exec/exec.go \
go/exec/lp_unix.go go/exec/lp_unix.go
...@@ -1623,6 +1627,7 @@ libgo_go_objs = \ ...@@ -1623,6 +1627,7 @@ libgo_go_objs = \
cmath/cmath.lo \ cmath/cmath.lo \
crypto/crypto.lo \ crypto/crypto.lo \
csv/csv.lo \ csv/csv.lo \
errors/errors.lo \
exec/exec.lo \ exec/exec.lo \
expvar/expvar.lo \ expvar/expvar.lo \
flag/flag.lo \ flag/flag.lo \
...@@ -1944,6 +1949,15 @@ csv/check: $(CHECK_DEPS) ...@@ -1944,6 +1949,15 @@ csv/check: $(CHECK_DEPS)
@$(CHECK) @$(CHECK)
.PHONY: csv/check .PHONY: csv/check
@go_include@ errors/errors.lo.dep
errors/errors.lo.dep: $(go_errors_files)
$(BUILDDEPS)
errors/errors.lo: $(go_errors_files)
$(BUILDPACKAGE)
errors/check: $(CHECK_DEPS)
@$(CHECK)
.PHONY: errors/check
@go_include@ exec/exec.lo.dep @go_include@ exec/exec.lo.dep
exec/exec.lo.dep: $(go_exec_files) exec/exec.lo.dep: $(go_exec_files)
$(BUILDDEPS) $(BUILDDEPS)
...@@ -3445,6 +3459,8 @@ crypto.gox: crypto/crypto.lo ...@@ -3445,6 +3459,8 @@ crypto.gox: crypto/crypto.lo
$(BUILDGOX) $(BUILDGOX)
csv.gox: csv/csv.lo csv.gox: csv/csv.lo
$(BUILDGOX) $(BUILDGOX)
errors.gox: errors/errors.lo
$(BUILDGOX)
exec.gox: exec/exec.lo exec.gox: exec/exec.lo
$(BUILDGOX) $(BUILDGOX)
expvar.gox: expvar/expvar.lo expvar.gox: expvar/expvar.lo
...@@ -3791,6 +3807,7 @@ TEST_PACKAGES = \ ...@@ -3791,6 +3807,7 @@ TEST_PACKAGES = \
bytes/check \ bytes/check \
cmath/check \ cmath/check \
csv/check \ csv/check \
errors/check \
exec/check \ exec/check \
expvar/check \ expvar/check \
flag/check \ flag/check \
......
...@@ -132,46 +132,46 @@ LTLIBRARIES = $(toolexeclib_LTLIBRARIES) ...@@ -132,46 +132,46 @@ LTLIBRARIES = $(toolexeclib_LTLIBRARIES)
am__DEPENDENCIES_1 = am__DEPENDENCIES_1 =
am__DEPENDENCIES_2 = asn1/asn1.lo big/big.lo bufio/bufio.lo \ am__DEPENDENCIES_2 = asn1/asn1.lo big/big.lo bufio/bufio.lo \
bytes/bytes.lo bytes/index.lo cmath/cmath.lo crypto/crypto.lo \ bytes/bytes.lo bytes/index.lo cmath/cmath.lo crypto/crypto.lo \
csv/csv.lo exec/exec.lo expvar/expvar.lo flag/flag.lo \ csv/csv.lo errors/errors.lo exec/exec.lo expvar/expvar.lo \
fmt/fmt.lo gob/gob.lo hash/hash.lo html/html.lo http/http.lo \ flag/flag.lo fmt/fmt.lo gob/gob.lo hash/hash.lo html/html.lo \
image/image.lo io/io.lo json/json.lo log/log.lo math/math.lo \ http/http.lo image/image.lo io/io.lo json/json.lo log/log.lo \
mail/mail.lo mime/mime.lo net/net.lo os/os.lo patch/patch.lo \ math/math.lo mail/mail.lo mime/mime.lo net/net.lo os/os.lo \
path/path.lo rand/rand.lo reflect/reflect.lo regexp/regexp.lo \ patch/patch.lo path/path.lo rand/rand.lo reflect/reflect.lo \
rpc/rpc.lo runtime/runtime.lo scanner/scanner.lo smtp/smtp.lo \ regexp/regexp.lo rpc/rpc.lo runtime/runtime.lo \
sort/sort.lo strconv/strconv.lo strings/strings.lo \ scanner/scanner.lo smtp/smtp.lo sort/sort.lo \
sync/sync.lo syslog/syslog.lo syslog/syslog_c.lo \ strconv/strconv.lo strings/strings.lo sync/sync.lo \
tabwriter/tabwriter.lo template/template.lo time/time.lo \ syslog/syslog.lo syslog/syslog_c.lo tabwriter/tabwriter.lo \
unicode/unicode.lo url/url.lo utf16/utf16.lo utf8/utf8.lo \ template/template.lo time/time.lo unicode/unicode.lo \
websocket/websocket.lo xml/xml.lo archive/tar.lo \ url/url.lo utf16/utf16.lo utf8/utf8.lo websocket/websocket.lo \
archive/zip.lo compress/bzip2.lo compress/flate.lo \ xml/xml.lo archive/tar.lo archive/zip.lo compress/bzip2.lo \
compress/gzip.lo compress/lzw.lo compress/zlib.lo \ compress/flate.lo compress/gzip.lo compress/lzw.lo \
container/heap.lo container/list.lo container/ring.lo \ compress/zlib.lo container/heap.lo container/list.lo \
crypto/aes.lo crypto/bcrypt.lo crypto/blowfish.lo \ container/ring.lo crypto/aes.lo crypto/bcrypt.lo \
crypto/cast5.lo crypto/cipher.lo crypto/des.lo crypto/dsa.lo \ crypto/blowfish.lo crypto/cast5.lo crypto/cipher.lo \
crypto/ecdsa.lo crypto/elliptic.lo crypto/hmac.lo \ crypto/des.lo crypto/dsa.lo crypto/ecdsa.lo crypto/elliptic.lo \
crypto/md4.lo crypto/md5.lo crypto/ocsp.lo crypto/openpgp.lo \ crypto/hmac.lo crypto/md4.lo crypto/md5.lo crypto/ocsp.lo \
crypto/rand.lo crypto/rc4.lo crypto/ripemd160.lo crypto/rsa.lo \ crypto/openpgp.lo crypto/rand.lo crypto/rc4.lo \
crypto/sha1.lo crypto/sha256.lo crypto/sha512.lo \ crypto/ripemd160.lo crypto/rsa.lo crypto/sha1.lo \
crypto/subtle.lo crypto/tls.lo crypto/twofish.lo \ crypto/sha256.lo crypto/sha512.lo crypto/subtle.lo \
crypto/x509.lo crypto/xtea.lo crypto/openpgp/armor.lo \ crypto/tls.lo crypto/twofish.lo crypto/x509.lo crypto/xtea.lo \
crypto/openpgp/elgamal.lo crypto/openpgp/error.lo \ crypto/openpgp/armor.lo crypto/openpgp/elgamal.lo \
crypto/openpgp/packet.lo crypto/openpgp/s2k.lo \ crypto/openpgp/error.lo crypto/openpgp/packet.lo \
crypto/x509/pkix.lo debug/dwarf.lo debug/elf.lo debug/gosym.lo \ crypto/openpgp/s2k.lo crypto/x509/pkix.lo debug/dwarf.lo \
debug/macho.lo debug/pe.lo encoding/ascii85.lo \ debug/elf.lo debug/gosym.lo debug/macho.lo debug/pe.lo \
encoding/base32.lo encoding/base64.lo encoding/binary.lo \ encoding/ascii85.lo encoding/base32.lo encoding/base64.lo \
encoding/git85.lo encoding/hex.lo encoding/pem.lo exp/ebnf.lo \ encoding/binary.lo encoding/git85.lo encoding/hex.lo \
exp/gui.lo exp/norm.lo exp/spdy.lo exp/sql.lo exp/ssh.lo \ encoding/pem.lo exp/ebnf.lo exp/gui.lo exp/norm.lo exp/spdy.lo \
exp/terminal.lo exp/types.lo exp/gui/x11.lo exp/sql/driver.lo \ exp/sql.lo exp/ssh.lo exp/terminal.lo exp/types.lo \
exp/template/html.lo go/ast.lo go/build.lo go/doc.lo \ exp/gui/x11.lo exp/sql/driver.lo exp/template/html.lo \
go/parser.lo go/printer.lo go/scanner.lo go/token.lo \ go/ast.lo go/build.lo go/doc.lo go/parser.lo go/printer.lo \
hash/adler32.lo hash/crc32.lo hash/crc64.lo hash/fnv.lo \ go/scanner.lo go/token.lo hash/adler32.lo hash/crc32.lo \
http/cgi.lo http/fcgi.lo http/httptest.lo http/pprof.lo \ hash/crc64.lo hash/fnv.lo http/cgi.lo http/fcgi.lo \
image/bmp.lo image/color.lo image/draw.lo image/gif.lo \ http/httptest.lo http/pprof.lo image/bmp.lo image/color.lo \
image/jpeg.lo image/png.lo image/tiff.lo image/ycbcr.lo \ image/draw.lo image/gif.lo image/jpeg.lo image/png.lo \
index/suffixarray.lo io/ioutil.lo mime/multipart.lo \ image/tiff.lo image/ycbcr.lo index/suffixarray.lo io/ioutil.lo \
net/dict.lo net/textproto.lo old/netchan.lo old/regexp.lo \ mime/multipart.lo net/dict.lo net/textproto.lo old/netchan.lo \
old/template.lo $(am__DEPENDENCIES_1) os/user.lo os/signal.lo \ old/regexp.lo old/template.lo $(am__DEPENDENCIES_1) os/user.lo \
path/filepath.lo regexp/syntax.lo rpc/jsonrpc.lo \ os/signal.lo path/filepath.lo regexp/syntax.lo rpc/jsonrpc.lo \
runtime/debug.lo runtime/pprof.lo sync/atomic.lo \ runtime/debug.lo runtime/pprof.lo sync/atomic.lo \
sync/atomic_c.lo syscall/syscall.lo syscall/errno.lo \ sync/atomic_c.lo syscall/syscall.lo syscall/errno.lo \
syscall/wait.lo template/parse.lo testing/testing.lo \ syscall/wait.lo template/parse.lo testing/testing.lo \
...@@ -568,6 +568,7 @@ toolexeclibgo_DATA = \ ...@@ -568,6 +568,7 @@ toolexeclibgo_DATA = \
cmath.gox \ cmath.gox \
crypto.gox \ crypto.gox \
csv.gox \ csv.gox \
errors.gox \
exec.gox \ exec.gox \
expvar.gox \ expvar.gox \
flag.gox \ flag.gox \
...@@ -947,6 +948,9 @@ go_csv_files = \ ...@@ -947,6 +948,9 @@ go_csv_files = \
go/csv/reader.go \ go/csv/reader.go \
go/csv/writer.go go/csv/writer.go
go_errors_files = \
go/errors/errors.go
go_exec_files = \ go_exec_files = \
go/exec/exec.go \ go/exec/exec.go \
go/exec/lp_unix.go go/exec/lp_unix.go
...@@ -1900,6 +1904,7 @@ libgo_go_objs = \ ...@@ -1900,6 +1904,7 @@ libgo_go_objs = \
cmath/cmath.lo \ cmath/cmath.lo \
crypto/crypto.lo \ crypto/crypto.lo \
csv/csv.lo \ csv/csv.lo \
errors/errors.lo \
exec/exec.lo \ exec/exec.lo \
expvar/expvar.lo \ expvar/expvar.lo \
flag/flag.lo \ flag/flag.lo \
...@@ -2167,6 +2172,7 @@ TEST_PACKAGES = \ ...@@ -2167,6 +2172,7 @@ TEST_PACKAGES = \
bytes/check \ bytes/check \
cmath/check \ cmath/check \
csv/check \ csv/check \
errors/check \
exec/check \ exec/check \
expvar/check \ expvar/check \
flag/check \ flag/check \
...@@ -4434,6 +4440,15 @@ csv/check: $(CHECK_DEPS) ...@@ -4434,6 +4440,15 @@ csv/check: $(CHECK_DEPS)
@$(CHECK) @$(CHECK)
.PHONY: csv/check .PHONY: csv/check
@go_include@ errors/errors.lo.dep
errors/errors.lo.dep: $(go_errors_files)
$(BUILDDEPS)
errors/errors.lo: $(go_errors_files)
$(BUILDPACKAGE)
errors/check: $(CHECK_DEPS)
@$(CHECK)
.PHONY: errors/check
@go_include@ exec/exec.lo.dep @go_include@ exec/exec.lo.dep
exec/exec.lo.dep: $(go_exec_files) exec/exec.lo.dep: $(go_exec_files)
$(BUILDDEPS) $(BUILDDEPS)
...@@ -5930,6 +5945,8 @@ crypto.gox: crypto/crypto.lo ...@@ -5930,6 +5945,8 @@ crypto.gox: crypto/crypto.lo
$(BUILDGOX) $(BUILDGOX)
csv.gox: csv/csv.lo csv.gox: csv/csv.lo
$(BUILDGOX) $(BUILDGOX)
errors.gox: errors/errors.lo
$(BUILDGOX)
exec.gox: exec/exec.lo exec.gox: exec/exec.lo
$(BUILDGOX) $(BUILDGOX)
expvar.gox: expvar/expvar.lo expvar.gox: expvar/expvar.lo
......
...@@ -9,6 +9,7 @@ package tar ...@@ -9,6 +9,7 @@ package tar
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
...@@ -16,7 +17,7 @@ import ( ...@@ -16,7 +17,7 @@ import (
) )
var ( var (
HeaderError = os.NewError("invalid tar header") HeaderError = errors.New("invalid tar header")
) )
// A Reader provides sequential access to the contents of a tar archive. // A Reader provides sequential access to the contents of a tar archive.
...@@ -39,7 +40,7 @@ var ( ...@@ -39,7 +40,7 @@ var (
// } // }
type Reader struct { type Reader struct {
r io.Reader r io.Reader
err os.Error err error
nb int64 // number of unread bytes for current file entry nb int64 // number of unread bytes for current file entry
pad int64 // amount of padding (ignored) after current file entry pad int64 // amount of padding (ignored) after current file entry
} }
...@@ -48,7 +49,7 @@ type Reader struct { ...@@ -48,7 +49,7 @@ type Reader struct {
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. // Next advances to the next entry in the tar archive.
func (tr *Reader) Next() (*Header, os.Error) { func (tr *Reader) Next() (*Header, error) {
var hdr *Header var hdr *Header
if tr.err == nil { if tr.err == nil {
tr.skipUnread() tr.skipUnread()
...@@ -119,7 +120,7 @@ func (tr *Reader) readHeader() *Header { ...@@ -119,7 +120,7 @@ func (tr *Reader) readHeader() *Header {
return nil return nil
} }
if bytes.Equal(header, zeroBlock[0:blockSize]) { if bytes.Equal(header, zeroBlock[0:blockSize]) {
tr.err = os.EOF tr.err = io.EOF
} else { } else {
tr.err = HeaderError // zero block and then non-zero block tr.err = HeaderError // zero block and then non-zero block
} }
...@@ -201,10 +202,10 @@ func (tr *Reader) readHeader() *Header { ...@@ -201,10 +202,10 @@ func (tr *Reader) readHeader() *Header {
// Read reads from the current entry in the tar archive. // Read reads from the current entry in the tar archive.
// It returns 0, os.EOF when it reaches the end of that entry, // It returns 0, os.EOF when it reaches the end of that entry,
// until Next is called to advance to the next entry. // until Next is called to advance to the next entry.
func (tr *Reader) Read(b []byte) (n int, err os.Error) { func (tr *Reader) Read(b []byte) (n int, err error) {
if tr.nb == 0 { if tr.nb == 0 {
// file consumed // file consumed
return 0, os.EOF return 0, io.EOF
} }
if int64(len(b)) > tr.nb { if int64(len(b)) > tr.nb {
...@@ -213,7 +214,7 @@ func (tr *Reader) Read(b []byte) (n int, err os.Error) { ...@@ -213,7 +214,7 @@ func (tr *Reader) Read(b []byte) (n int, err os.Error) {
n, err = tr.r.Read(b) n, err = tr.r.Read(b)
tr.nb -= int64(n) tr.nb -= int64(n)
if err == os.EOF && tr.nb > 0 { if err == io.EOF && tr.nb > 0 {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
tr.err = err tr.err = err
......
...@@ -132,7 +132,7 @@ testLoop: ...@@ -132,7 +132,7 @@ testLoop:
} }
} }
hdr, err := tr.Next() hdr, err := tr.Next()
if err == os.EOF { if err == io.EOF {
break break
} }
if hdr != nil || err != nil { if hdr != nil || err != nil {
...@@ -195,7 +195,7 @@ func TestIncrementalRead(t *testing.T) { ...@@ -195,7 +195,7 @@ func TestIncrementalRead(t *testing.T) {
// loop over all files // loop over all files
for ; ; nread++ { for ; ; nread++ {
hdr, err := tr.Next() hdr, err := tr.Next()
if hdr == nil || err == os.EOF { if hdr == nil || err == io.EOF {
break break
} }
...@@ -211,7 +211,7 @@ func TestIncrementalRead(t *testing.T) { ...@@ -211,7 +211,7 @@ func TestIncrementalRead(t *testing.T) {
rdbuf := make([]uint8, 8) rdbuf := make([]uint8, 8)
for { for {
nr, err := tr.Read(rdbuf) nr, err := tr.Read(rdbuf)
if err == os.EOF { if err == io.EOF {
break break
} }
if err != nil { if err != nil {
...@@ -250,7 +250,7 @@ func TestNonSeekable(t *testing.T) { ...@@ -250,7 +250,7 @@ func TestNonSeekable(t *testing.T) {
for { for {
nr, err := f.Read(rdbuf) nr, err := f.Read(rdbuf)
w.Write(rdbuf[0:nr]) w.Write(rdbuf[0:nr])
if err == os.EOF { if err == io.EOF {
break break
} }
} }
...@@ -262,7 +262,7 @@ func TestNonSeekable(t *testing.T) { ...@@ -262,7 +262,7 @@ func TestNonSeekable(t *testing.T) {
for ; ; nread++ { for ; ; nread++ {
hdr, err := tr.Next() hdr, err := tr.Next()
if hdr == nil || err == os.EOF { if hdr == nil || err == io.EOF {
break break
} }
} }
......
...@@ -8,15 +8,15 @@ package tar ...@@ -8,15 +8,15 @@ package tar
// - catch more errors (no first header, write after close, etc.) // - catch more errors (no first header, write after close, etc.)
import ( import (
"errors"
"io" "io"
"os"
"strconv" "strconv"
) )
var ( var (
ErrWriteTooLong = os.NewError("write too long") ErrWriteTooLong = errors.New("write too long")
ErrFieldTooLong = os.NewError("header field too long") ErrFieldTooLong = errors.New("header field too long")
ErrWriteAfterClose = os.NewError("write after close") ErrWriteAfterClose = errors.New("write after close")
) )
// A Writer provides sequential writing of a tar archive in POSIX.1 format. // A Writer provides sequential writing of a tar archive in POSIX.1 format.
...@@ -36,7 +36,7 @@ var ( ...@@ -36,7 +36,7 @@ var (
// tw.Close() // tw.Close()
type Writer struct { type Writer struct {
w io.Writer w io.Writer
err os.Error err error
nb int64 // number of unwritten bytes for current file entry nb int64 // number of unwritten bytes for current file entry
pad int64 // amount of padding to write after current file entry pad int64 // amount of padding to write after current file entry
closed bool closed bool
...@@ -47,7 +47,7 @@ type Writer struct { ...@@ -47,7 +47,7 @@ type Writer struct {
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). // Flush finishes writing the current file (optional).
func (tw *Writer) Flush() os.Error { func (tw *Writer) Flush() error {
n := tw.nb + tw.pad n := tw.nb + tw.pad
for n > 0 && tw.err == nil { for n > 0 && tw.err == nil {
nr := n nr := n
...@@ -107,7 +107,7 @@ func (tw *Writer) numeric(b []byte, x int64) { ...@@ -107,7 +107,7 @@ func (tw *Writer) numeric(b []byte, x int64) {
// WriteHeader writes hdr and prepares to accept the file's contents. // WriteHeader writes hdr and prepares to accept the file's contents.
// WriteHeader calls Flush if it is not the first header. // WriteHeader calls Flush if it is not the first header.
// Calling after a Close will return ErrWriteAfterClose. // Calling after a Close will return ErrWriteAfterClose.
func (tw *Writer) WriteHeader(hdr *Header) os.Error { func (tw *Writer) WriteHeader(hdr *Header) error {
if tw.closed { if tw.closed {
return ErrWriteAfterClose return ErrWriteAfterClose
} }
...@@ -165,7 +165,7 @@ func (tw *Writer) WriteHeader(hdr *Header) os.Error { ...@@ -165,7 +165,7 @@ func (tw *Writer) WriteHeader(hdr *Header) os.Error {
// Write writes to the current entry in the tar archive. // Write writes to the current entry in the tar archive.
// Write returns the error ErrWriteTooLong if more than // Write returns the error ErrWriteTooLong if more than
// hdr.Size bytes are written after WriteHeader. // hdr.Size bytes are written after WriteHeader.
func (tw *Writer) Write(b []byte) (n int, err os.Error) { func (tw *Writer) Write(b []byte) (n int, err error) {
if tw.closed { if tw.closed {
err = ErrWriteTooLong err = ErrWriteTooLong
return return
...@@ -187,7 +187,7 @@ func (tw *Writer) Write(b []byte) (n int, err os.Error) { ...@@ -187,7 +187,7 @@ func (tw *Writer) Write(b []byte) (n int, err os.Error) {
// Close closes the tar archive, flushing any unwritten // Close closes the tar archive, flushing any unwritten
// data to the underlying writer. // data to the underlying writer.
func (tw *Writer) Close() os.Error { func (tw *Writer) Close() error {
if tw.err != nil || tw.closed { if tw.err != nil || tw.closed {
return tw.err return tw.err
} }
......
...@@ -7,6 +7,7 @@ package zip ...@@ -7,6 +7,7 @@ package zip
import ( import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"encoding/binary" "encoding/binary"
...@@ -16,9 +17,9 @@ import ( ...@@ -16,9 +17,9 @@ import (
) )
var ( var (
FormatError = os.NewError("zip: not a valid zip file") FormatError = errors.New("zip: not a valid zip file")
UnsupportedMethod = os.NewError("zip: unsupported compression algorithm") UnsupportedMethod = errors.New("zip: unsupported compression algorithm")
ChecksumError = os.NewError("zip: checksum error") ChecksumError = errors.New("zip: checksum error")
) )
type Reader struct { type Reader struct {
...@@ -44,7 +45,7 @@ func (f *File) hasDataDescriptor() bool { ...@@ -44,7 +45,7 @@ func (f *File) hasDataDescriptor() bool {
} }
// OpenReader will open the Zip file specified by name and return a ReadCloser. // OpenReader will open the Zip file specified by name and return a ReadCloser.
func OpenReader(name string) (*ReadCloser, os.Error) { func OpenReader(name string) (*ReadCloser, error) {
f, err := os.Open(name) f, err := os.Open(name)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -64,7 +65,7 @@ func OpenReader(name string) (*ReadCloser, os.Error) { ...@@ -64,7 +65,7 @@ func OpenReader(name string) (*ReadCloser, os.Error) {
// NewReader returns a new Reader reading from r, which is assumed to // NewReader returns a new Reader reading from r, which is assumed to
// have the given size in bytes. // have the given size in bytes.
func NewReader(r io.ReaderAt, size int64) (*Reader, os.Error) { func NewReader(r io.ReaderAt, size int64) (*Reader, error) {
zr := new(Reader) zr := new(Reader)
if err := zr.init(r, size); err != nil { if err := zr.init(r, size); err != nil {
return nil, err return nil, err
...@@ -72,7 +73,7 @@ func NewReader(r io.ReaderAt, size int64) (*Reader, os.Error) { ...@@ -72,7 +73,7 @@ func NewReader(r io.ReaderAt, size int64) (*Reader, os.Error) {
return zr, nil return zr, nil
} }
func (z *Reader) init(r io.ReaderAt, size int64) os.Error { func (z *Reader) init(r io.ReaderAt, size int64) error {
end, err := readDirectoryEnd(r, size) end, err := readDirectoryEnd(r, size)
if err != nil { if err != nil {
return err return err
...@@ -110,13 +111,13 @@ func (z *Reader) init(r io.ReaderAt, size int64) os.Error { ...@@ -110,13 +111,13 @@ func (z *Reader) init(r io.ReaderAt, size int64) os.Error {
} }
// Close closes the Zip file, rendering it unusable for I/O. // Close closes the Zip file, rendering it unusable for I/O.
func (rc *ReadCloser) Close() os.Error { func (rc *ReadCloser) Close() error {
return rc.f.Close() return rc.f.Close()
} }
// Open returns a ReadCloser that provides access to the File's contents. // Open returns a ReadCloser that provides access to the File's contents.
// It is safe to Open and Read from files concurrently. // It is safe to Open and Read from files concurrently.
func (f *File) Open() (rc io.ReadCloser, err os.Error) { func (f *File) Open() (rc io.ReadCloser, err error) {
bodyOffset, err := f.findBodyOffset() bodyOffset, err := f.findBodyOffset()
if err != nil { if err != nil {
return return
...@@ -148,10 +149,10 @@ type checksumReader struct { ...@@ -148,10 +149,10 @@ type checksumReader struct {
zipr io.Reader // for reading the data descriptor zipr io.Reader // for reading the data descriptor
} }
func (r *checksumReader) Read(b []byte) (n int, err os.Error) { func (r *checksumReader) Read(b []byte) (n int, err error) {
n, err = r.rc.Read(b) n, err = r.rc.Read(b)
r.hash.Write(b[:n]) r.hash.Write(b[:n])
if err != os.EOF { if err != io.EOF {
return return
} }
if r.f.hasDataDescriptor() { if r.f.hasDataDescriptor() {
...@@ -165,9 +166,9 @@ func (r *checksumReader) Read(b []byte) (n int, err os.Error) { ...@@ -165,9 +166,9 @@ func (r *checksumReader) Read(b []byte) (n int, err os.Error) {
return return
} }
func (r *checksumReader) Close() os.Error { return r.rc.Close() } func (r *checksumReader) Close() error { return r.rc.Close() }
func readFileHeader(f *File, r io.Reader) os.Error { func readFileHeader(f *File, r io.Reader) error {
var b [fileHeaderLen]byte var b [fileHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
return err return err
...@@ -197,7 +198,7 @@ func readFileHeader(f *File, r io.Reader) os.Error { ...@@ -197,7 +198,7 @@ func readFileHeader(f *File, r io.Reader) os.Error {
// findBodyOffset does the minimum work to verify the file has a header // findBodyOffset does the minimum work to verify the file has a header
// and returns the file body offset. // and returns the file body offset.
func (f *File) findBodyOffset() (int64, os.Error) { func (f *File) findBodyOffset() (int64, error) {
r := io.NewSectionReader(f.zipr, f.headerOffset, f.zipsize-f.headerOffset) r := io.NewSectionReader(f.zipr, f.headerOffset, f.zipsize-f.headerOffset)
var b [fileHeaderLen]byte var b [fileHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
...@@ -215,7 +216,7 @@ func (f *File) findBodyOffset() (int64, os.Error) { ...@@ -215,7 +216,7 @@ func (f *File) findBodyOffset() (int64, os.Error) {
// readDirectoryHeader attempts to read a directory header from r. // readDirectoryHeader attempts to read a directory header from r.
// It returns io.ErrUnexpectedEOF if it cannot read a complete header, // It returns io.ErrUnexpectedEOF if it cannot read a complete header,
// and FormatError if it doesn't find a valid header signature. // and FormatError if it doesn't find a valid header signature.
func readDirectoryHeader(f *File, r io.Reader) os.Error { func readDirectoryHeader(f *File, r io.Reader) error {
var b [directoryHeaderLen]byte var b [directoryHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
return err return err
...@@ -250,7 +251,7 @@ func readDirectoryHeader(f *File, r io.Reader) os.Error { ...@@ -250,7 +251,7 @@ func readDirectoryHeader(f *File, r io.Reader) os.Error {
return nil return nil
} }
func readDataDescriptor(r io.Reader, f *File) os.Error { func readDataDescriptor(r io.Reader, f *File) error {
var b [dataDescriptorLen]byte var b [dataDescriptorLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil { if _, err := io.ReadFull(r, b[:]); err != nil {
return err return err
...@@ -262,7 +263,7 @@ func readDataDescriptor(r io.Reader, f *File) os.Error { ...@@ -262,7 +263,7 @@ func readDataDescriptor(r io.Reader, f *File) os.Error {
return nil return nil
} }
func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err os.Error) { func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err error) {
// look for directoryEndSignature in the last 1k, then in the last 65k // look for directoryEndSignature in the last 1k, then in the last 65k
var b []byte var b []byte
for i, bLen := range []int64{1024, 65 * 1024} { for i, bLen := range []int64{1024, 65 * 1024} {
...@@ -270,7 +271,7 @@ func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err os.Erro ...@@ -270,7 +271,7 @@ func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err os.Erro
bLen = size bLen = size
} }
b = make([]byte, int(bLen)) b = make([]byte, int(bLen))
if _, err := r.ReadAt(b, size-bLen); err != nil && err != os.EOF { if _, err := r.ReadAt(b, size-bLen); err != nil && err != io.EOF {
return nil, err return nil, err
} }
if p := findSignatureInBlock(b); p >= 0 { if p := findSignatureInBlock(b); p >= 0 {
......
...@@ -9,7 +9,6 @@ import ( ...@@ -9,7 +9,6 @@ import (
"encoding/binary" "encoding/binary"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
"time" "time"
) )
...@@ -18,7 +17,7 @@ type ZipTest struct { ...@@ -18,7 +17,7 @@ type ZipTest struct {
Name string Name string
Comment string Comment string
File []ZipTestFile File []ZipTestFile
Error os.Error // the error that Opening this file should return Error error // the error that Opening this file should return
} }
type ZipTestFile struct { type ZipTestFile struct {
...@@ -245,7 +244,7 @@ func TestInvalidFiles(t *testing.T) { ...@@ -245,7 +244,7 @@ func TestInvalidFiles(t *testing.T) {
type sliceReaderAt []byte type sliceReaderAt []byte
func (r sliceReaderAt) ReadAt(b []byte, off int64) (int, os.Error) { func (r sliceReaderAt) ReadAt(b []byte, off int64) (int, error) {
copy(b, r[int(off):int(off)+len(b)]) copy(b, r[int(off):int(off)+len(b)])
return len(b), nil return len(b), nil
} }
...@@ -11,7 +11,7 @@ This package does not support ZIP64 or disk spanning. ...@@ -11,7 +11,7 @@ This package does not support ZIP64 or disk spanning.
*/ */
package zip package zip
import "os" import "errors"
import "time" import "time"
// Compression methods. // Compression methods.
...@@ -60,9 +60,9 @@ type directoryEnd struct { ...@@ -60,9 +60,9 @@ type directoryEnd struct {
comment string comment string
} }
func recoverError(errp *os.Error) { func recoverError(errp *error) {
if e := recover(); e != nil { if e := recover(); e != nil {
if err, ok := e.(os.Error); ok { if err, ok := e.(error); ok {
*errp = err *errp = err
return return
} }
...@@ -96,11 +96,11 @@ func (h *FileHeader) Mtime_ns() int64 { ...@@ -96,11 +96,11 @@ func (h *FileHeader) Mtime_ns() int64 {
// Mode returns the permission and mode bits for the FileHeader. // Mode returns the permission and mode bits for the FileHeader.
// An error is returned in case the information is not available. // An error is returned in case the information is not available.
func (h *FileHeader) Mode() (mode uint32, err os.Error) { func (h *FileHeader) Mode() (mode uint32, err error) {
if h.CreatorVersion>>8 == creatorUnix { if h.CreatorVersion>>8 == creatorUnix {
return h.ExternalAttrs >> 16, nil return h.ExternalAttrs >> 16, nil
} }
return 0, os.NewError("file mode not available") return 0, errors.New("file mode not available")
} }
// SetMode changes the permission and mode bits for the FileHeader. // SetMode changes the permission and mode bits for the FileHeader.
......
...@@ -8,10 +8,10 @@ import ( ...@@ -8,10 +8,10 @@ import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"encoding/binary" "encoding/binary"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"io" "io"
"os"
) )
// TODO(adg): support zip file comments // TODO(adg): support zip file comments
...@@ -37,7 +37,7 @@ func NewWriter(w io.Writer) *Writer { ...@@ -37,7 +37,7 @@ func NewWriter(w io.Writer) *Writer {
// Close finishes writing the zip file by writing the central directory. // Close finishes writing the zip file by writing the central directory.
// It does not (and can not) close the underlying writer. // It does not (and can not) close the underlying writer.
func (w *Writer) Close() (err os.Error) { func (w *Writer) Close() (err error) {
if w.last != nil && !w.last.closed { if w.last != nil && !w.last.closed {
if err = w.last.close(); err != nil { if err = w.last.close(); err != nil {
return return
...@@ -45,7 +45,7 @@ func (w *Writer) Close() (err os.Error) { ...@@ -45,7 +45,7 @@ func (w *Writer) Close() (err os.Error) {
w.last = nil w.last = nil
} }
if w.closed { if w.closed {
return os.NewError("zip: writer closed twice") return errors.New("zip: writer closed twice")
} }
w.closed = true w.closed = true
...@@ -94,7 +94,7 @@ func (w *Writer) Close() (err os.Error) { ...@@ -94,7 +94,7 @@ func (w *Writer) Close() (err os.Error) {
// It returns a Writer to which the file contents should be written. // It returns a Writer to which the file contents should be written.
// The file's contents must be written to the io.Writer before the next // The file's contents must be written to the io.Writer before the next
// call to Create, CreateHeader, or Close. // call to Create, CreateHeader, or Close.
func (w *Writer) Create(name string) (io.Writer, os.Error) { func (w *Writer) Create(name string) (io.Writer, error) {
header := &FileHeader{ header := &FileHeader{
Name: name, Name: name,
Method: Deflate, Method: Deflate,
...@@ -107,7 +107,7 @@ func (w *Writer) Create(name string) (io.Writer, os.Error) { ...@@ -107,7 +107,7 @@ func (w *Writer) Create(name string) (io.Writer, os.Error) {
// It returns a Writer to which the file contents should be written. // It returns a Writer to which the file contents should be written.
// The file's contents must be written to the io.Writer before the next // The file's contents must be written to the io.Writer before the next
// call to Create, CreateHeader, or Close. // call to Create, CreateHeader, or Close.
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, os.Error) { func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error) {
if w.last != nil && !w.last.closed { if w.last != nil && !w.last.closed {
if err := w.last.close(); err != nil { if err := w.last.close(); err != nil {
return nil, err return nil, err
...@@ -148,7 +148,7 @@ func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, os.Error) { ...@@ -148,7 +148,7 @@ func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, os.Error) {
return fw, nil return fw, nil
} }
func writeHeader(w io.Writer, h *FileHeader) (err os.Error) { func writeHeader(w io.Writer, h *FileHeader) (err error) {
defer recoverError(&err) defer recoverError(&err)
write(w, uint32(fileHeaderSignature)) write(w, uint32(fileHeaderSignature))
write(w, h.ReaderVersion) write(w, h.ReaderVersion)
...@@ -176,17 +176,17 @@ type fileWriter struct { ...@@ -176,17 +176,17 @@ type fileWriter struct {
closed bool closed bool
} }
func (w *fileWriter) Write(p []byte) (int, os.Error) { func (w *fileWriter) Write(p []byte) (int, error) {
if w.closed { if w.closed {
return 0, os.NewError("zip: write to closed file") return 0, errors.New("zip: write to closed file")
} }
w.crc32.Write(p) w.crc32.Write(p)
return w.rawCount.Write(p) return w.rawCount.Write(p)
} }
func (w *fileWriter) close() (err os.Error) { func (w *fileWriter) close() (err error) {
if w.closed { if w.closed {
return os.NewError("zip: file closed twice") return errors.New("zip: file closed twice")
} }
w.closed = true w.closed = true
if err = w.comp.Close(); err != nil { if err = w.comp.Close(); err != nil {
...@@ -213,7 +213,7 @@ type countWriter struct { ...@@ -213,7 +213,7 @@ type countWriter struct {
count int64 count int64
} }
func (w *countWriter) Write(p []byte) (int, os.Error) { func (w *countWriter) Write(p []byte) (int, error) {
n, err := w.w.Write(p) n, err := w.w.Write(p)
w.count += int64(n) w.count += int64(n)
return n, err return n, err
...@@ -223,7 +223,7 @@ type nopCloser struct { ...@@ -223,7 +223,7 @@ type nopCloser struct {
io.Writer io.Writer
} }
func (w nopCloser) Close() os.Error { func (w nopCloser) Close() error {
return nil return nil
} }
......
...@@ -9,15 +9,15 @@ package zip ...@@ -9,15 +9,15 @@ package zip
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"os" "io"
"testing" "testing"
) )
type stringReaderAt string type stringReaderAt string
func (s stringReaderAt) ReadAt(p []byte, off int64) (n int, err os.Error) { func (s stringReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
if off >= int64(len(s)) { if off >= int64(len(s)) {
return 0, os.EOF return 0, io.EOF
} }
n = copy(p, s[off:]) n = copy(p, s[off:])
return return
......
...@@ -22,7 +22,6 @@ package asn1 ...@@ -22,7 +22,6 @@ package asn1
import ( import (
"big" "big"
"fmt" "fmt"
"os"
"reflect" "reflect"
"time" "time"
) )
...@@ -33,20 +32,20 @@ type StructuralError struct { ...@@ -33,20 +32,20 @@ type StructuralError struct {
Msg string Msg string
} }
func (e StructuralError) String() string { return "ASN.1 structure error: " + e.Msg } func (e StructuralError) Error() string { return "ASN.1 structure error: " + e.Msg }
// A SyntaxError suggests that the ASN.1 data is invalid. // A SyntaxError suggests that the ASN.1 data is invalid.
type SyntaxError struct { type SyntaxError struct {
Msg string Msg string
} }
func (e SyntaxError) String() string { return "ASN.1 syntax error: " + e.Msg } func (e SyntaxError) Error() string { return "ASN.1 syntax error: " + e.Msg }
// We start by dealing with each of the primitive types in turn. // We start by dealing with each of the primitive types in turn.
// BOOLEAN // BOOLEAN
func parseBool(bytes []byte) (ret bool, err os.Error) { func parseBool(bytes []byte) (ret bool, err error) {
if len(bytes) != 1 { if len(bytes) != 1 {
err = SyntaxError{"invalid boolean"} err = SyntaxError{"invalid boolean"}
return return
...@@ -59,7 +58,7 @@ func parseBool(bytes []byte) (ret bool, err os.Error) { ...@@ -59,7 +58,7 @@ func parseBool(bytes []byte) (ret bool, err os.Error) {
// parseInt64 treats the given bytes as a big-endian, signed integer and // parseInt64 treats the given bytes as a big-endian, signed integer and
// returns the result. // returns the result.
func parseInt64(bytes []byte) (ret int64, err os.Error) { func parseInt64(bytes []byte) (ret int64, err error) {
if len(bytes) > 8 { if len(bytes) > 8 {
// We'll overflow an int64 in this case. // We'll overflow an int64 in this case.
err = StructuralError{"integer too large"} err = StructuralError{"integer too large"}
...@@ -78,7 +77,7 @@ func parseInt64(bytes []byte) (ret int64, err os.Error) { ...@@ -78,7 +77,7 @@ func parseInt64(bytes []byte) (ret int64, err os.Error) {
// parseInt treats the given bytes as a big-endian, signed integer and returns // parseInt treats the given bytes as a big-endian, signed integer and returns
// the result. // the result.
func parseInt(bytes []byte) (int, os.Error) { func parseInt(bytes []byte) (int, error) {
ret64, err := parseInt64(bytes) ret64, err := parseInt64(bytes)
if err != nil { if err != nil {
return 0, err return 0, err
...@@ -150,7 +149,7 @@ func (b BitString) RightAlign() []byte { ...@@ -150,7 +149,7 @@ func (b BitString) RightAlign() []byte {
} }
// parseBitString parses an ASN.1 bit string from the given byte slice and returns it. // parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
func parseBitString(bytes []byte) (ret BitString, err os.Error) { func parseBitString(bytes []byte) (ret BitString, err error) {
if len(bytes) == 0 { if len(bytes) == 0 {
err = SyntaxError{"zero length BIT STRING"} err = SyntaxError{"zero length BIT STRING"}
return return
...@@ -189,7 +188,7 @@ func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool { ...@@ -189,7 +188,7 @@ func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
// parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
// returns it. An object identifier is a sequence of variable length integers // returns it. An object identifier is a sequence of variable length integers
// that are assigned in a hierarchy. // that are assigned in a hierarchy.
func parseObjectIdentifier(bytes []byte) (s []int, err os.Error) { func parseObjectIdentifier(bytes []byte) (s []int, err error) {
if len(bytes) == 0 { if len(bytes) == 0 {
err = SyntaxError{"zero length OBJECT IDENTIFIER"} err = SyntaxError{"zero length OBJECT IDENTIFIER"}
return return
...@@ -227,7 +226,7 @@ type Flag bool ...@@ -227,7 +226,7 @@ type Flag bool
// parseBase128Int parses a base-128 encoded int from the given offset in the // parseBase128Int parses a base-128 encoded int from the given offset in the
// given byte slice. It returns the value and the new offset. // given byte slice. It returns the value and the new offset.
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Error) { func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
offset = initOffset offset = initOffset
for shifted := 0; offset < len(bytes); shifted++ { for shifted := 0; offset < len(bytes); shifted++ {
if shifted > 4 { if shifted > 4 {
...@@ -248,7 +247,7 @@ func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Erro ...@@ -248,7 +247,7 @@ func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err os.Erro
// UTCTime // UTCTime
func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) { func parseUTCTime(bytes []byte) (ret *time.Time, err error) {
s := string(bytes) s := string(bytes)
ret, err = time.Parse("0601021504Z0700", s) ret, err = time.Parse("0601021504Z0700", s)
if err == nil { if err == nil {
...@@ -260,7 +259,7 @@ func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) { ...@@ -260,7 +259,7 @@ func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
// parseGeneralizedTime parses the GeneralizedTime from the given byte slice // parseGeneralizedTime parses the GeneralizedTime from the given byte slice
// and returns the resulting time. // and returns the resulting time.
func parseGeneralizedTime(bytes []byte) (ret *time.Time, err os.Error) { func parseGeneralizedTime(bytes []byte) (ret *time.Time, err error) {
return time.Parse("20060102150405Z0700", string(bytes)) return time.Parse("20060102150405Z0700", string(bytes))
} }
...@@ -268,7 +267,7 @@ func parseGeneralizedTime(bytes []byte) (ret *time.Time, err os.Error) { ...@@ -268,7 +267,7 @@ func parseGeneralizedTime(bytes []byte) (ret *time.Time, err os.Error) {
// parsePrintableString parses a ASN.1 PrintableString from the given byte // parsePrintableString parses a ASN.1 PrintableString from the given byte
// array and returns it. // array and returns it.
func parsePrintableString(bytes []byte) (ret string, err os.Error) { func parsePrintableString(bytes []byte) (ret string, err error) {
for _, b := range bytes { for _, b := range bytes {
if !isPrintable(b) { if !isPrintable(b) {
err = SyntaxError{"PrintableString contains invalid character"} err = SyntaxError{"PrintableString contains invalid character"}
...@@ -300,7 +299,7 @@ func isPrintable(b byte) bool { ...@@ -300,7 +299,7 @@ func isPrintable(b byte) bool {
// parseIA5String parses a ASN.1 IA5String (ASCII string) from the given // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
// byte slice and returns it. // byte slice and returns it.
func parseIA5String(bytes []byte) (ret string, err os.Error) { func parseIA5String(bytes []byte) (ret string, err error) {
for _, b := range bytes { for _, b := range bytes {
if b >= 0x80 { if b >= 0x80 {
err = SyntaxError{"IA5String contains invalid character"} err = SyntaxError{"IA5String contains invalid character"}
...@@ -315,7 +314,7 @@ func parseIA5String(bytes []byte) (ret string, err os.Error) { ...@@ -315,7 +314,7 @@ func parseIA5String(bytes []byte) (ret string, err os.Error) {
// parseT61String parses a ASN.1 T61String (8-bit clean string) from the given // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
// byte slice and returns it. // byte slice and returns it.
func parseT61String(bytes []byte) (ret string, err os.Error) { func parseT61String(bytes []byte) (ret string, err error) {
return string(bytes), nil return string(bytes), nil
} }
...@@ -323,7 +322,7 @@ func parseT61String(bytes []byte) (ret string, err os.Error) { ...@@ -323,7 +322,7 @@ func parseT61String(bytes []byte) (ret string, err os.Error) {
// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
// array and returns it. // array and returns it.
func parseUTF8String(bytes []byte) (ret string, err os.Error) { func parseUTF8String(bytes []byte) (ret string, err error) {
return string(bytes), nil return string(bytes), nil
} }
...@@ -346,7 +345,7 @@ type RawContent []byte ...@@ -346,7 +345,7 @@ type RawContent []byte
// into a byte slice. It returns the parsed data and the new offset. SET and // into a byte slice. It returns the parsed data and the new offset. SET and
// SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we // 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. // don't distinguish between ordered and unordered objects in this code.
func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err os.Error) { func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
offset = initOffset offset = initOffset
b := bytes[offset] b := bytes[offset]
offset++ offset++
...@@ -402,7 +401,7 @@ func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset i ...@@ -402,7 +401,7 @@ func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset i
// parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
// a number of ASN.1 values from the given byte slice and returns them as a // a number of ASN.1 values from the given byte slice and returns them as a
// slice of Go values of the given type. // slice of Go values of the given type.
func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err os.Error) { func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
expectedTag, compoundType, ok := getUniversalType(elemType) expectedTag, compoundType, ok := getUniversalType(elemType)
if !ok { if !ok {
err = StructuralError{"unknown Go type for slice"} err = StructuralError{"unknown Go type for slice"}
...@@ -466,7 +465,7 @@ func invalidLength(offset, length, sliceLength int) bool { ...@@ -466,7 +465,7 @@ func invalidLength(offset, length, sliceLength int) bool {
// parseField is the main parsing function. Given a byte slice and an offset // parseField is the main parsing function. Given a byte slice and an offset
// into the array, it will try to parse a suitable ASN.1 value out and store it // into the array, it will try to parse a suitable ASN.1 value out and store it
// in the given Value. // in the given Value.
func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err os.Error) { func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
offset = initOffset offset = initOffset
fieldType := v.Type() fieldType := v.Type()
...@@ -649,7 +648,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam ...@@ -649,7 +648,7 @@ func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParam
return return
case timeType: case timeType:
var time *time.Time var time *time.Time
var err1 os.Error var err1 error
if universalTag == tagUTCTime { if universalTag == tagUTCTime {
time, err1 = parseUTCTime(innerBytes) time, err1 = parseUTCTime(innerBytes)
} else { } else {
...@@ -826,13 +825,13 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { ...@@ -826,13 +825,13 @@ func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
// //
// Other ASN.1 types are not supported; if it encounters them, // Other ASN.1 types are not supported; if it encounters them,
// Unmarshal returns a parse error. // Unmarshal returns a parse error.
func Unmarshal(b []byte, val interface{}) (rest []byte, err os.Error) { func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
return UnmarshalWithParams(b, val, "") return UnmarshalWithParams(b, val, "")
} }
// UnmarshalWithParams allows field parameters to be specified for the // UnmarshalWithParams allows field parameters to be specified for the
// top-level element. The form of the params is the same as the field tags. // top-level element. The form of the params is the same as the field tags.
func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err os.Error) { func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
v := reflect.ValueOf(val).Elem() v := reflect.ValueOf(val).Elem()
offset, err := parseField(v, b, 0, parseFieldParameters(params)) offset, err := parseField(v, b, 0, parseFieldParameters(params))
if err != nil { if err != nil {
......
...@@ -9,7 +9,6 @@ import ( ...@@ -9,7 +9,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"os"
"reflect" "reflect"
"time" "time"
) )
...@@ -48,7 +47,7 @@ func (f *forkableWriter) Len() (l int) { ...@@ -48,7 +47,7 @@ func (f *forkableWriter) Len() (l int) {
return return
} }
func (f *forkableWriter) writeTo(out io.Writer) (n int, err os.Error) { func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) {
n, err = out.Write(f.Bytes()) n, err = out.Write(f.Bytes())
if err != nil { if err != nil {
return return
...@@ -71,7 +70,7 @@ func (f *forkableWriter) writeTo(out io.Writer) (n int, err os.Error) { ...@@ -71,7 +70,7 @@ func (f *forkableWriter) writeTo(out io.Writer) (n int, err os.Error) {
return return
} }
func marshalBase128Int(out *forkableWriter, n int64) (err os.Error) { func marshalBase128Int(out *forkableWriter, n int64) (err error) {
if n == 0 { if n == 0 {
err = out.WriteByte(0) err = out.WriteByte(0)
return return
...@@ -97,7 +96,7 @@ func marshalBase128Int(out *forkableWriter, n int64) (err os.Error) { ...@@ -97,7 +96,7 @@ func marshalBase128Int(out *forkableWriter, n int64) (err os.Error) {
return nil return nil
} }
func marshalInt64(out *forkableWriter, i int64) (err os.Error) { func marshalInt64(out *forkableWriter, i int64) (err error) {
n := int64Length(i) n := int64Length(i)
for ; n > 0; n-- { for ; n > 0; n-- {
...@@ -126,7 +125,7 @@ func int64Length(i int64) (numBytes int) { ...@@ -126,7 +125,7 @@ func int64Length(i int64) (numBytes int) {
return return
} }
func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) { func marshalBigInt(out *forkableWriter, n *big.Int) (err error) {
if n.Sign() < 0 { if n.Sign() < 0 {
// A negative number has to be converted to two's-complement // A negative number has to be converted to two's-complement
// form. So we'll subtract 1 and invert. If the // form. So we'll subtract 1 and invert. If the
...@@ -163,7 +162,7 @@ func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) { ...@@ -163,7 +162,7 @@ func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) {
return return
} }
func marshalLength(out *forkableWriter, i int) (err os.Error) { func marshalLength(out *forkableWriter, i int) (err error) {
n := lengthLength(i) n := lengthLength(i)
for ; n > 0; n-- { for ; n > 0; n-- {
...@@ -185,7 +184,7 @@ func lengthLength(i int) (numBytes int) { ...@@ -185,7 +184,7 @@ func lengthLength(i int) (numBytes int) {
return return
} }
func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) { func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) {
b := uint8(t.class) << 6 b := uint8(t.class) << 6
if t.isCompound { if t.isCompound {
b |= 0x20 b |= 0x20
...@@ -228,7 +227,7 @@ func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) { ...@@ -228,7 +227,7 @@ func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) {
return nil return nil
} }
func marshalBitString(out *forkableWriter, b BitString) (err os.Error) { func marshalBitString(out *forkableWriter, b BitString) (err error) {
paddingBits := byte((8 - b.BitLength%8) % 8) paddingBits := byte((8 - b.BitLength%8) % 8)
err = out.WriteByte(paddingBits) err = out.WriteByte(paddingBits)
if err != nil { if err != nil {
...@@ -238,7 +237,7 @@ func marshalBitString(out *forkableWriter, b BitString) (err os.Error) { ...@@ -238,7 +237,7 @@ func marshalBitString(out *forkableWriter, b BitString) (err os.Error) {
return return
} }
func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) { func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) {
if len(oid) < 2 || oid[0] > 6 || oid[1] >= 40 { if len(oid) < 2 || oid[0] > 6 || oid[1] >= 40 {
return StructuralError{"invalid object identifier"} return StructuralError{"invalid object identifier"}
} }
...@@ -257,7 +256,7 @@ func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) { ...@@ -257,7 +256,7 @@ func marshalObjectIdentifier(out *forkableWriter, oid []int) (err os.Error) {
return return
} }
func marshalPrintableString(out *forkableWriter, s string) (err os.Error) { func marshalPrintableString(out *forkableWriter, s string) (err error) {
b := []byte(s) b := []byte(s)
for _, c := range b { for _, c := range b {
if !isPrintable(c) { if !isPrintable(c) {
...@@ -269,7 +268,7 @@ func marshalPrintableString(out *forkableWriter, s string) (err os.Error) { ...@@ -269,7 +268,7 @@ func marshalPrintableString(out *forkableWriter, s string) (err os.Error) {
return return
} }
func marshalIA5String(out *forkableWriter, s string) (err os.Error) { func marshalIA5String(out *forkableWriter, s string) (err error) {
b := []byte(s) b := []byte(s)
for _, c := range b { for _, c := range b {
if c > 127 { if c > 127 {
...@@ -281,7 +280,7 @@ func marshalIA5String(out *forkableWriter, s string) (err os.Error) { ...@@ -281,7 +280,7 @@ func marshalIA5String(out *forkableWriter, s string) (err os.Error) {
return return
} }
func marshalTwoDigits(out *forkableWriter, v int) (err os.Error) { func marshalTwoDigits(out *forkableWriter, v int) (err error) {
err = out.WriteByte(byte('0' + (v/10)%10)) err = out.WriteByte(byte('0' + (v/10)%10))
if err != nil { if err != nil {
return return
...@@ -289,7 +288,7 @@ func marshalTwoDigits(out *forkableWriter, v int) (err os.Error) { ...@@ -289,7 +288,7 @@ func marshalTwoDigits(out *forkableWriter, v int) (err os.Error) {
return out.WriteByte(byte('0' + v%10)) return out.WriteByte(byte('0' + v%10))
} }
func marshalUTCTime(out *forkableWriter, t *time.Time) (err os.Error) { func marshalUTCTime(out *forkableWriter, t *time.Time) (err error) {
switch { switch {
case 1950 <= t.Year && t.Year < 2000: case 1950 <= t.Year && t.Year < 2000:
err = marshalTwoDigits(out, int(t.Year-1900)) err = marshalTwoDigits(out, int(t.Year-1900))
...@@ -364,7 +363,7 @@ func stripTagAndLength(in []byte) []byte { ...@@ -364,7 +363,7 @@ func stripTagAndLength(in []byte) []byte {
return in[offset:] return in[offset:]
} }
func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err os.Error) { func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) {
switch value.Type() { switch value.Type() {
case timeType: case timeType:
return marshalUTCTime(out, value.Interface().(*time.Time)) return marshalUTCTime(out, value.Interface().(*time.Time))
...@@ -452,7 +451,7 @@ func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameter ...@@ -452,7 +451,7 @@ func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameter
return StructuralError{"unknown Go type"} return StructuralError{"unknown Go type"}
} }
func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err os.Error) { func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) {
// If the field is an interface{} then recurse into it. // If the field is an interface{} then recurse into it.
if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 { if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 {
return marshalField(out, v.Elem(), params) return marshalField(out, v.Elem(), params)
...@@ -535,7 +534,7 @@ func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) ...@@ -535,7 +534,7 @@ func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters)
} }
// Marshal returns the ASN.1 encoding of val. // Marshal returns the ASN.1 encoding of val.
func Marshal(val interface{}) ([]byte, os.Error) { func Marshal(val interface{}) ([]byte, error) {
var out bytes.Buffer var out bytes.Buffer
v := reflect.ValueOf(val) v := reflect.ValueOf(val)
f := newForkableWriter() f := newForkableWriter()
......
...@@ -7,9 +7,9 @@ ...@@ -7,9 +7,9 @@
package big package big
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"os"
"rand" "rand"
"strings" "strings"
) )
...@@ -432,7 +432,7 @@ func (x *Int) Format(s fmt.State, ch rune) { ...@@ -432,7 +432,7 @@ func (x *Int) Format(s fmt.State, ch rune) {
// ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
// ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10. // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
// //
func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) { func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, error) {
// determine sign // determine sign
ch, _, err := r.ReadRune() ch, _, err := r.ReadRune()
if err != nil { if err != nil {
...@@ -460,7 +460,7 @@ func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) { ...@@ -460,7 +460,7 @@ func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, os.Error) {
// Scan is a support routine for fmt.Scanner; it sets z to the value of // Scan is a support routine for fmt.Scanner; it sets z to the value of
// the scanned number. It accepts the formats 'b' (binary), 'o' (octal), // the scanned number. It accepts the formats 'b' (binary), 'o' (octal),
// 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). // 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
func (z *Int) Scan(s fmt.ScanState, ch rune) os.Error { func (z *Int) Scan(s fmt.ScanState, ch rune) error {
s.SkipSpace() // skip leading space characters s.SkipSpace() // skip leading space characters
base := 0 base := 0
switch ch { switch ch {
...@@ -475,7 +475,7 @@ func (z *Int) Scan(s fmt.ScanState, ch rune) os.Error { ...@@ -475,7 +475,7 @@ func (z *Int) Scan(s fmt.ScanState, ch rune) os.Error {
case 's', 'v': case 's', 'v':
// let scan determine the base // let scan determine the base
default: default:
return os.NewError("Int.Scan: invalid verb") return errors.New("Int.Scan: invalid verb")
} }
_, _, err := z.scan(s, base) _, _, err := z.scan(s, base)
return err return err
...@@ -513,7 +513,7 @@ func (z *Int) SetString(s string, base int) (*Int, bool) { ...@@ -513,7 +513,7 @@ func (z *Int) SetString(s string, base int) (*Int, bool) {
return nil, false return nil, false
} }
_, _, err = r.ReadRune() _, _, err = r.ReadRune()
if err != os.EOF { if err != io.EOF {
return nil, false return nil, false
} }
return z, true // err == os.EOF => scan consumed all of s return z, true // err == os.EOF => scan consumed all of s
...@@ -847,7 +847,7 @@ func (z *Int) Not(x *Int) *Int { ...@@ -847,7 +847,7 @@ func (z *Int) Not(x *Int) *Int {
const intGobVersion byte = 1 const intGobVersion byte = 1
// GobEncode implements the gob.GobEncoder interface. // GobEncode implements the gob.GobEncoder interface.
func (z *Int) GobEncode() ([]byte, os.Error) { func (z *Int) GobEncode() ([]byte, error) {
buf := make([]byte, 1+len(z.abs)*_S) // extra byte for version and sign bit buf := make([]byte, 1+len(z.abs)*_S) // extra byte for version and sign bit
i := z.abs.bytes(buf) - 1 // i >= 0 i := z.abs.bytes(buf) - 1 // i >= 0
b := intGobVersion << 1 // make space for sign bit b := intGobVersion << 1 // make space for sign bit
...@@ -859,13 +859,13 @@ func (z *Int) GobEncode() ([]byte, os.Error) { ...@@ -859,13 +859,13 @@ func (z *Int) GobEncode() ([]byte, os.Error) {
} }
// GobDecode implements the gob.GobDecoder interface. // GobDecode implements the gob.GobDecoder interface.
func (z *Int) GobDecode(buf []byte) os.Error { func (z *Int) GobDecode(buf []byte) error {
if len(buf) == 0 { if len(buf) == 0 {
return os.NewError("Int.GobDecode: no data") return errors.New("Int.GobDecode: no data")
} }
b := buf[0] b := buf[0]
if b>>1 != intGobVersion { if b>>1 != intGobVersion {
return os.NewError(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1)) return errors.New(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1))
} }
z.neg = b&1 != 0 z.neg = b&1 != 0
z.abs = z.abs.setBytes(buf[1:]) z.abs = z.abs.setBytes(buf[1:])
......
...@@ -19,8 +19,8 @@ package big ...@@ -19,8 +19,8 @@ package big
// and rationals. // and rationals.
import ( import (
"errors"
"io" "io"
"os"
"rand" "rand"
) )
...@@ -613,10 +613,10 @@ func hexValue(ch rune) Word { ...@@ -613,10 +613,10 @@ func hexValue(ch rune) Word {
// ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
// ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10. // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
// //
func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { func (z nat) scan(r io.RuneScanner, base int) (nat, int, error) {
// reject illegal bases // reject illegal bases
if base < 0 || base == 1 || MaxBase < base { if base < 0 || base == 1 || MaxBase < base {
return z, 0, os.NewError("illegal number base") return z, 0, errors.New("illegal number base")
} }
// one char look-ahead // one char look-ahead
...@@ -644,7 +644,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { ...@@ -644,7 +644,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
return z, 0, err return z, 0, err
} }
} }
case os.EOF: case io.EOF:
return z.make(0), 10, nil return z.make(0), 10, nil
default: default:
return z, 10, err return z, 10, err
...@@ -676,7 +676,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { ...@@ -676,7 +676,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
} }
if ch, _, err = r.ReadRune(); err != nil { if ch, _, err = r.ReadRune(); err != nil {
if err != os.EOF { if err != io.EOF {
return z, int(b), err return z, int(b), err
} }
break break
...@@ -693,7 +693,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { ...@@ -693,7 +693,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
return z, 10, nil return z, 10, nil
case base != 0 || b != 8: case base != 0 || b != 8:
// there was neither a mantissa digit nor the octal prefix 0 // there was neither a mantissa digit nor the octal prefix 0
return z, int(b), os.NewError("syntax error scanning number") return z, int(b), errors.New("syntax error scanning number")
} }
return z.norm(), int(b), nil return z.norm(), int(b), nil
......
...@@ -6,7 +6,7 @@ package big ...@@ -6,7 +6,7 @@ package big
import ( import (
"fmt" "fmt"
"os" "io"
"strings" "strings"
"testing" "testing"
) )
...@@ -288,7 +288,7 @@ func TestScanBase(t *testing.T) { ...@@ -288,7 +288,7 @@ func TestScanBase(t *testing.T) {
t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base) t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base)
} }
next, _, err := r.ReadRune() next, _, err := r.ReadRune()
if err == os.EOF { if err == io.EOF {
next = 0 next = 0
err = nil err = nil
} }
......
...@@ -8,8 +8,8 @@ package big ...@@ -8,8 +8,8 @@ package big
import ( import (
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"os"
"strings" "strings"
) )
...@@ -255,16 +255,16 @@ func ratTok(ch rune) bool { ...@@ -255,16 +255,16 @@ func ratTok(ch rune) bool {
// Scan is a support routine for fmt.Scanner. It accepts the formats // Scan is a support routine for fmt.Scanner. It accepts the formats
// 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent. // 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.
func (z *Rat) Scan(s fmt.ScanState, ch rune) os.Error { func (z *Rat) Scan(s fmt.ScanState, ch rune) error {
tok, err := s.Token(true, ratTok) tok, err := s.Token(true, ratTok)
if err != nil { if err != nil {
return err return err
} }
if strings.IndexRune("efgEFGv", ch) < 0 { if strings.IndexRune("efgEFGv", ch) < 0 {
return os.NewError("Rat.Scan: invalid verb") return errors.New("Rat.Scan: invalid verb")
} }
if _, ok := z.SetString(string(tok)); !ok { if _, ok := z.SetString(string(tok)); !ok {
return os.NewError("Rat.Scan: invalid syntax") return errors.New("Rat.Scan: invalid syntax")
} }
return nil return nil
} }
...@@ -285,7 +285,7 @@ func (z *Rat) SetString(s string) (*Rat, bool) { ...@@ -285,7 +285,7 @@ func (z *Rat) SetString(s string) (*Rat, bool) {
return nil, false return nil, false
} }
s = s[sep+1:] s = s[sep+1:]
var err os.Error var err error
if z.b, _, err = z.b.scan(strings.NewReader(s), 10); err != nil { if z.b, _, err = z.b.scan(strings.NewReader(s), 10); err != nil {
return nil, false return nil, false
} }
...@@ -395,14 +395,14 @@ func (z *Rat) FloatString(prec int) string { ...@@ -395,14 +395,14 @@ func (z *Rat) FloatString(prec int) string {
const ratGobVersion byte = 1 const ratGobVersion byte = 1
// GobEncode implements the gob.GobEncoder interface. // GobEncode implements the gob.GobEncoder interface.
func (z *Rat) GobEncode() ([]byte, os.Error) { func (z *Rat) GobEncode() ([]byte, error) {
buf := make([]byte, 1+4+(len(z.a.abs)+len(z.b))*_S) // extra bytes for version and sign bit (1), and numerator length (4) buf := make([]byte, 1+4+(len(z.a.abs)+len(z.b))*_S) // extra bytes for version and sign bit (1), and numerator length (4)
i := z.b.bytes(buf) i := z.b.bytes(buf)
j := z.a.abs.bytes(buf[0:i]) j := z.a.abs.bytes(buf[0:i])
n := i - j n := i - j
if int(uint32(n)) != n { if int(uint32(n)) != n {
// this should never happen // this should never happen
return nil, os.NewError("Rat.GobEncode: numerator too large") return nil, errors.New("Rat.GobEncode: numerator too large")
} }
binary.BigEndian.PutUint32(buf[j-4:j], uint32(n)) binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
j -= 1 + 4 j -= 1 + 4
...@@ -415,13 +415,13 @@ func (z *Rat) GobEncode() ([]byte, os.Error) { ...@@ -415,13 +415,13 @@ func (z *Rat) GobEncode() ([]byte, os.Error) {
} }
// GobDecode implements the gob.GobDecoder interface. // GobDecode implements the gob.GobDecoder interface.
func (z *Rat) GobDecode(buf []byte) os.Error { func (z *Rat) GobDecode(buf []byte) error {
if len(buf) == 0 { if len(buf) == 0 {
return os.NewError("Rat.GobDecode: no data") return errors.New("Rat.GobDecode: no data")
} }
b := buf[0] b := buf[0]
if b>>1 != ratGobVersion { if b>>1 != ratGobVersion {
return os.NewError(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1)) return errors.New(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1))
} }
const j = 1 + 4 const j = 1 + 4
i := j + binary.BigEndian.Uint32(buf[j-4:j]) i := j + binary.BigEndian.Uint32(buf[j-4:j])
......
...@@ -10,7 +10,6 @@ package bufio ...@@ -10,7 +10,6 @@ package bufio
import ( import (
"bytes" "bytes"
"io" "io"
"os"
"strconv" "strconv"
"utf8" "utf8"
) )
...@@ -24,20 +23,20 @@ type Error struct { ...@@ -24,20 +23,20 @@ type Error struct {
ErrorString string ErrorString string
} }
func (err *Error) String() string { return err.ErrorString } func (err *Error) Error() string { return err.ErrorString }
var ( var (
ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"} ErrInvalidUnreadByte error = &Error{"bufio: invalid use of UnreadByte"}
ErrInvalidUnreadRune os.Error = &Error{"bufio: invalid use of UnreadRune"} ErrInvalidUnreadRune error = &Error{"bufio: invalid use of UnreadRune"}
ErrBufferFull os.Error = &Error{"bufio: buffer full"} ErrBufferFull error = &Error{"bufio: buffer full"}
ErrNegativeCount os.Error = &Error{"bufio: negative count"} ErrNegativeCount error = &Error{"bufio: negative count"}
errInternal os.Error = &Error{"bufio: internal error"} errInternal error = &Error{"bufio: internal error"}
) )
// BufSizeError is the error representing an invalid buffer size. // BufSizeError is the error representing an invalid buffer size.
type BufSizeError int type BufSizeError int
func (b BufSizeError) String() string { func (b BufSizeError) Error() string {
return "bufio: bad buffer size " + strconv.Itoa(int(b)) return "bufio: bad buffer size " + strconv.Itoa(int(b))
} }
...@@ -48,7 +47,7 @@ type Reader struct { ...@@ -48,7 +47,7 @@ type Reader struct {
buf []byte buf []byte
rd io.Reader rd io.Reader
r, w int r, w int
err os.Error err error
lastByte int lastByte int
lastRuneSize int lastRuneSize int
} }
...@@ -57,7 +56,7 @@ type Reader struct { ...@@ -57,7 +56,7 @@ type Reader struct {
// which must be greater than one. If the argument io.Reader is already a // which must be greater than one. If the argument io.Reader is already a
// Reader with large enough size, it returns the underlying Reader. // Reader with large enough size, it returns the underlying Reader.
// It returns the Reader and any error. // It returns the Reader and any error.
func NewReaderSize(rd io.Reader, size int) (*Reader, os.Error) { func NewReaderSize(rd io.Reader, size int) (*Reader, error) {
if size <= 1 { if size <= 1 {
return nil, BufSizeError(size) return nil, BufSizeError(size)
} }
...@@ -101,7 +100,7 @@ func (b *Reader) fill() { ...@@ -101,7 +100,7 @@ func (b *Reader) fill() {
} }
} }
func (b *Reader) readErr() os.Error { func (b *Reader) readErr() error {
err := b.err err := b.err
b.err = nil b.err = nil
return err return err
...@@ -111,7 +110,7 @@ func (b *Reader) readErr() os.Error { ...@@ -111,7 +110,7 @@ func (b *Reader) readErr() os.Error {
// being valid at the next read call. If Peek returns fewer than n bytes, it // being valid at the next read call. If Peek returns fewer than n bytes, it
// also returns an error explaining why the read is short. The error is // also returns an error explaining why the read is short. The error is
// ErrBufferFull if n is larger than b's buffer size. // ErrBufferFull if n is larger than b's buffer size.
func (b *Reader) Peek(n int) ([]byte, os.Error) { func (b *Reader) Peek(n int) ([]byte, error) {
if n < 0 { if n < 0 {
return nil, ErrNegativeCount return nil, ErrNegativeCount
} }
...@@ -137,7 +136,7 @@ func (b *Reader) Peek(n int) ([]byte, os.Error) { ...@@ -137,7 +136,7 @@ func (b *Reader) Peek(n int) ([]byte, os.Error) {
// It calls Read at most once on the underlying Reader, // It calls Read at most once on the underlying Reader,
// hence n may be less than len(p). // hence n may be less than len(p).
// At EOF, the count will be zero and err will be os.EOF. // At EOF, the count will be zero and err will be os.EOF.
func (b *Reader) Read(p []byte) (n int, err os.Error) { func (b *Reader) Read(p []byte) (n int, err error) {
n = len(p) n = len(p)
if n == 0 { if n == 0 {
return 0, b.readErr() return 0, b.readErr()
...@@ -174,7 +173,7 @@ func (b *Reader) Read(p []byte) (n int, err os.Error) { ...@@ -174,7 +173,7 @@ func (b *Reader) Read(p []byte) (n int, err os.Error) {
// ReadByte reads and returns a single byte. // ReadByte reads and returns a single byte.
// If no byte is available, returns an error. // If no byte is available, returns an error.
func (b *Reader) ReadByte() (c byte, err os.Error) { func (b *Reader) ReadByte() (c byte, err error) {
b.lastRuneSize = -1 b.lastRuneSize = -1
for b.w == b.r { for b.w == b.r {
if b.err != nil { if b.err != nil {
...@@ -189,7 +188,7 @@ func (b *Reader) ReadByte() (c byte, err os.Error) { ...@@ -189,7 +188,7 @@ func (b *Reader) ReadByte() (c byte, err os.Error) {
} }
// UnreadByte unreads the last byte. Only the most recently read byte can be unread. // UnreadByte unreads the last byte. Only the most recently read byte can be unread.
func (b *Reader) UnreadByte() os.Error { func (b *Reader) UnreadByte() error {
b.lastRuneSize = -1 b.lastRuneSize = -1
if b.r == b.w && b.lastByte >= 0 { if b.r == b.w && b.lastByte >= 0 {
b.w = 1 b.w = 1
...@@ -208,7 +207,7 @@ func (b *Reader) UnreadByte() os.Error { ...@@ -208,7 +207,7 @@ func (b *Reader) UnreadByte() os.Error {
// ReadRune reads a single UTF-8 encoded Unicode character and returns the // ReadRune reads a single UTF-8 encoded Unicode character and returns the
// rune and its size in bytes. // rune and its size in bytes.
func (b *Reader) ReadRune() (r rune, size int, err os.Error) { func (b *Reader) ReadRune() (r rune, size int, err error) {
for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil { for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil {
b.fill() b.fill()
} }
...@@ -230,7 +229,7 @@ func (b *Reader) ReadRune() (r rune, size int, err os.Error) { ...@@ -230,7 +229,7 @@ func (b *Reader) ReadRune() (r rune, size int, err os.Error) {
// the buffer was not a ReadRune, UnreadRune returns an error. (In this // the buffer was not a ReadRune, UnreadRune returns an error. (In this
// regard it is stricter than UnreadByte, which will unread the last byte // regard it is stricter than UnreadByte, which will unread the last byte
// from any read operation.) // from any read operation.)
func (b *Reader) UnreadRune() os.Error { func (b *Reader) UnreadRune() error {
if b.lastRuneSize < 0 || b.r == 0 { if b.lastRuneSize < 0 || b.r == 0 {
return ErrInvalidUnreadRune return ErrInvalidUnreadRune
} }
...@@ -253,7 +252,7 @@ func (b *Reader) Buffered() int { return b.w - b.r } ...@@ -253,7 +252,7 @@ func (b *Reader) Buffered() int { return b.w - b.r }
// by the next I/O operation, most clients should use // by the next I/O operation, most clients should use
// ReadBytes or ReadString instead. // ReadBytes or ReadString instead.
// ReadSlice returns err != nil if and only if line does not end in delim. // ReadSlice returns err != nil if and only if line does not end in delim.
func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) { func (b *Reader) ReadSlice(delim byte) (line []byte, err error) {
// Look in buffer. // Look in buffer.
if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 { if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 {
line1 := b.buf[b.r : b.r+i+1] line1 := b.buf[b.r : b.r+i+1]
...@@ -295,7 +294,7 @@ func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) { ...@@ -295,7 +294,7 @@ func (b *Reader) ReadSlice(delim byte) (line []byte, err os.Error) {
// of the line. The returned buffer is only valid until the next call to // of the line. The returned buffer is only valid until the next call to
// ReadLine. ReadLine either returns a non-nil line or it returns an error, // ReadLine. ReadLine either returns a non-nil line or it returns an error,
// never both. // never both.
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err os.Error) { func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) {
line, err = b.ReadSlice('\n') line, err = b.ReadSlice('\n')
if err == ErrBufferFull { if err == ErrBufferFull {
// Handle the case where "\r\n" straddles the buffer. // Handle the case where "\r\n" straddles the buffer.
...@@ -333,7 +332,7 @@ func (b *Reader) ReadLine() (line []byte, isPrefix bool, err os.Error) { ...@@ -333,7 +332,7 @@ func (b *Reader) ReadLine() (line []byte, isPrefix bool, err os.Error) {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in // ReadBytes returns err != nil if and only if the returned data does not end in
// delim. // delim.
func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) { func (b *Reader) ReadBytes(delim byte) (line []byte, err error) {
// Use ReadSlice to look for array, // Use ReadSlice to look for array,
// accumulating full buffers. // accumulating full buffers.
var frag []byte var frag []byte
...@@ -341,7 +340,7 @@ func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) { ...@@ -341,7 +340,7 @@ func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) {
err = nil err = nil
for { for {
var e os.Error var e error
frag, e = b.ReadSlice(delim) frag, e = b.ReadSlice(delim)
if e == nil { // got final fragment if e == nil { // got final fragment
break break
...@@ -380,7 +379,7 @@ func (b *Reader) ReadBytes(delim byte) (line []byte, err os.Error) { ...@@ -380,7 +379,7 @@ 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). // it returns the data read before the error and the error itself (often os.EOF).
// ReadString returns err != nil if and only if the returned data does not end in // ReadString returns err != nil if and only if the returned data does not end in
// delim. // delim.
func (b *Reader) ReadString(delim byte) (line string, err os.Error) { func (b *Reader) ReadString(delim byte) (line string, err error) {
bytes, e := b.ReadBytes(delim) bytes, e := b.ReadBytes(delim)
return string(bytes), e return string(bytes), e
} }
...@@ -389,7 +388,7 @@ func (b *Reader) ReadString(delim byte) (line string, err os.Error) { ...@@ -389,7 +388,7 @@ func (b *Reader) ReadString(delim byte) (line string, err os.Error) {
// Writer implements buffering for an io.Writer object. // Writer implements buffering for an io.Writer object.
type Writer struct { type Writer struct {
err os.Error err error
buf []byte buf []byte
n int n int
wr io.Writer wr io.Writer
...@@ -399,7 +398,7 @@ type Writer struct { ...@@ -399,7 +398,7 @@ type Writer struct {
// which must be greater than zero. If the argument io.Writer is already a // which must be greater than zero. If the argument io.Writer is already a
// Writer with large enough size, it returns the underlying Writer. // Writer with large enough size, it returns the underlying Writer.
// It returns the Writer and any error. // It returns the Writer and any error.
func NewWriterSize(wr io.Writer, size int) (*Writer, os.Error) { func NewWriterSize(wr io.Writer, size int) (*Writer, error) {
if size <= 0 { if size <= 0 {
return nil, BufSizeError(size) return nil, BufSizeError(size)
} }
...@@ -425,7 +424,7 @@ func NewWriter(wr io.Writer) *Writer { ...@@ -425,7 +424,7 @@ func NewWriter(wr io.Writer) *Writer {
} }
// Flush writes any buffered data to the underlying io.Writer. // Flush writes any buffered data to the underlying io.Writer.
func (b *Writer) Flush() os.Error { func (b *Writer) Flush() error {
if b.err != nil { if b.err != nil {
return b.err return b.err
} }
...@@ -458,7 +457,7 @@ func (b *Writer) Buffered() int { return b.n } ...@@ -458,7 +457,7 @@ func (b *Writer) Buffered() int { return b.n }
// It returns the number of bytes written. // It returns the number of bytes written.
// If nn < len(p), it also returns an error explaining // If nn < len(p), it also returns an error explaining
// why the write is short. // why the write is short.
func (b *Writer) Write(p []byte) (nn int, err os.Error) { func (b *Writer) Write(p []byte) (nn int, err error) {
for len(p) > b.Available() && b.err == nil { for len(p) > b.Available() && b.err == nil {
var n int var n int
if b.Buffered() == 0 { if b.Buffered() == 0 {
...@@ -483,7 +482,7 @@ func (b *Writer) Write(p []byte) (nn int, err os.Error) { ...@@ -483,7 +482,7 @@ func (b *Writer) Write(p []byte) (nn int, err os.Error) {
} }
// WriteByte writes a single byte. // WriteByte writes a single byte.
func (b *Writer) WriteByte(c byte) os.Error { func (b *Writer) WriteByte(c byte) error {
if b.err != nil { if b.err != nil {
return b.err return b.err
} }
...@@ -497,7 +496,7 @@ func (b *Writer) WriteByte(c byte) os.Error { ...@@ -497,7 +496,7 @@ func (b *Writer) WriteByte(c byte) os.Error {
// WriteRune writes a single Unicode code point, returning // WriteRune writes a single Unicode code point, returning
// the number of bytes written and any error. // the number of bytes written and any error.
func (b *Writer) WriteRune(r rune) (size int, err os.Error) { func (b *Writer) WriteRune(r rune) (size int, err error) {
if r < utf8.RuneSelf { if r < utf8.RuneSelf {
err = b.WriteByte(byte(r)) err = b.WriteByte(byte(r))
if err != nil { if err != nil {
...@@ -528,7 +527,7 @@ func (b *Writer) WriteRune(r rune) (size int, err os.Error) { ...@@ -528,7 +527,7 @@ func (b *Writer) WriteRune(r rune) (size int, err os.Error) {
// It returns the number of bytes written. // It returns the number of bytes written.
// If the count is less than len(s), it also returns an error explaining // If the count is less than len(s), it also returns an error explaining
// why the write is short. // why the write is short.
func (b *Writer) WriteString(s string) (int, os.Error) { func (b *Writer) WriteString(s string) (int, error) {
nn := 0 nn := 0
for len(s) > b.Available() && b.err == nil { for len(s) > b.Available() && b.err == nil {
n := copy(b.buf[b.n:], s) n := copy(b.buf[b.n:], s)
......
...@@ -28,7 +28,7 @@ func newRot13Reader(r io.Reader) *rot13Reader { ...@@ -28,7 +28,7 @@ func newRot13Reader(r io.Reader) *rot13Reader {
return r13 return r13
} }
func (r13 *rot13Reader) Read(p []byte) (int, os.Error) { func (r13 *rot13Reader) Read(p []byte) (int, error) {
n, e := r13.r.Read(p) n, e := r13.r.Read(p)
if e != nil { if e != nil {
return n, e return n, e
...@@ -50,14 +50,14 @@ func readBytes(buf *Reader) string { ...@@ -50,14 +50,14 @@ func readBytes(buf *Reader) string {
nb := 0 nb := 0
for { for {
c, e := buf.ReadByte() c, e := buf.ReadByte()
if e == os.EOF { if e == io.EOF {
break break
} }
if e == nil { if e == nil {
b[nb] = c b[nb] = c
nb++ nb++
} else if e != iotest.ErrTimeout { } else if e != iotest.ErrTimeout {
panic("Data: " + e.String()) panic("Data: " + e.Error())
} }
} }
return string(b[0:nb]) return string(b[0:nb])
...@@ -95,11 +95,11 @@ func readLines(b *Reader) string { ...@@ -95,11 +95,11 @@ func readLines(b *Reader) string {
s := "" s := ""
for { for {
s1, e := b.ReadString('\n') s1, e := b.ReadString('\n')
if e == os.EOF { if e == io.EOF {
break break
} }
if e != nil && e != iotest.ErrTimeout { if e != nil && e != iotest.ErrTimeout {
panic("GetLines: " + e.String()) panic("GetLines: " + e.Error())
} }
s += s1 s += s1
} }
...@@ -113,7 +113,7 @@ func reads(buf *Reader, m int) string { ...@@ -113,7 +113,7 @@ func reads(buf *Reader, m int) string {
for { for {
n, e := buf.Read(b[nb : nb+m]) n, e := buf.Read(b[nb : nb+m])
nb += n nb += n
if e == os.EOF { if e == io.EOF {
break break
} }
} }
...@@ -179,13 +179,13 @@ type StringReader struct { ...@@ -179,13 +179,13 @@ type StringReader struct {
step int step int
} }
func (r *StringReader) Read(p []byte) (n int, err os.Error) { func (r *StringReader) Read(p []byte) (n int, err error) {
if r.step < len(r.data) { if r.step < len(r.data) {
s := r.data[r.step] s := r.data[r.step]
n = copy(p, s) n = copy(p, s)
r.step++ r.step++
} else { } else {
err = os.EOF err = io.EOF
} }
return return
} }
...@@ -197,7 +197,7 @@ func readRuneSegments(t *testing.T, segments []string) { ...@@ -197,7 +197,7 @@ func readRuneSegments(t *testing.T, segments []string) {
for { for {
r, _, err := r.ReadRune() r, _, err := r.ReadRune()
if err != nil { if err != nil {
if err != os.EOF { if err != io.EOF {
return return
} }
break break
...@@ -235,7 +235,7 @@ func TestUnreadRune(t *testing.T) { ...@@ -235,7 +235,7 @@ func TestUnreadRune(t *testing.T) {
for { for {
r1, _, err := r.ReadRune() r1, _, err := r.ReadRune()
if err != nil { if err != nil {
if err != os.EOF { if err != io.EOF {
t.Error("unexpected EOF") t.Error("unexpected EOF")
} }
break break
...@@ -328,7 +328,7 @@ func TestUnreadRuneAtEOF(t *testing.T) { ...@@ -328,7 +328,7 @@ func TestUnreadRuneAtEOF(t *testing.T) {
_, _, err := r.ReadRune() _, _, err := r.ReadRune()
if err == nil { if err == nil {
t.Error("expected error at EOF") t.Error("expected error at EOF")
} else if err != os.EOF { } else if err != io.EOF {
t.Error("expected EOF; got", err) t.Error("expected EOF; got", err)
} }
} }
...@@ -413,11 +413,11 @@ func TestWriter(t *testing.T) { ...@@ -413,11 +413,11 @@ func TestWriter(t *testing.T) {
type errorWriterTest struct { type errorWriterTest struct {
n, m int n, m int
err os.Error err error
expect os.Error expect error
} }
func (w errorWriterTest) Write(p []byte) (int, os.Error) { func (w errorWriterTest) Write(p []byte) (int, error) {
return len(p) * w.n / w.m, w.err return len(p) * w.n / w.m, w.err
} }
...@@ -559,7 +559,7 @@ func TestPeek(t *testing.T) { ...@@ -559,7 +559,7 @@ func TestPeek(t *testing.T) {
if s, err := buf.Peek(0); string(s) != "" || err != nil { if s, err := buf.Peek(0); string(s) != "" || err != nil {
t.Fatalf("want %q got %q, err=%v", "", string(s), err) t.Fatalf("want %q got %q, err=%v", "", string(s), err)
} }
if _, err := buf.Peek(1); err != os.EOF { if _, err := buf.Peek(1); err != io.EOF {
t.Fatalf("want EOF got %v", err) t.Fatalf("want EOF got %v", err)
} }
} }
...@@ -583,7 +583,7 @@ type testReader struct { ...@@ -583,7 +583,7 @@ type testReader struct {
stride int stride int
} }
func (t *testReader) Read(buf []byte) (n int, err os.Error) { func (t *testReader) Read(buf []byte) (n int, err error) {
n = t.stride n = t.stride
if n > len(t.data) { if n > len(t.data) {
n = len(t.data) n = len(t.data)
...@@ -594,7 +594,7 @@ func (t *testReader) Read(buf []byte) (n int, err os.Error) { ...@@ -594,7 +594,7 @@ func (t *testReader) Read(buf []byte) (n int, err os.Error) {
copy(buf, t.data) copy(buf, t.data)
t.data = t.data[n:] t.data = t.data[n:]
if len(t.data) == 0 { if len(t.data) == 0 {
err = os.EOF err = io.EOF
} }
return return
} }
...@@ -614,7 +614,7 @@ func testReadLine(t *testing.T, input []byte) { ...@@ -614,7 +614,7 @@ func testReadLine(t *testing.T, input []byte) {
t.Errorf("ReadLine returned prefix") t.Errorf("ReadLine returned prefix")
} }
if err != nil { if err != nil {
if err != os.EOF { if err != io.EOF {
t.Fatalf("Got unknown error: %s", err) t.Fatalf("Got unknown error: %s", err)
} }
break break
...@@ -679,7 +679,7 @@ func TestReadAfterLines(t *testing.T) { ...@@ -679,7 +679,7 @@ func TestReadAfterLines(t *testing.T) {
func TestReadEmptyBuffer(t *testing.T) { func TestReadEmptyBuffer(t *testing.T) {
l, _ := NewReaderSize(bytes.NewBuffer(nil), 10) l, _ := NewReaderSize(bytes.NewBuffer(nil), 10)
line, isPrefix, err := l.ReadLine() line, isPrefix, err := l.ReadLine()
if err != os.EOF { if err != io.EOF {
t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
} }
} }
...@@ -693,7 +693,7 @@ func TestLinesAfterRead(t *testing.T) { ...@@ -693,7 +693,7 @@ func TestLinesAfterRead(t *testing.T) {
} }
line, isPrefix, err := l.ReadLine() line, isPrefix, err := l.ReadLine()
if err != os.EOF { if err != io.EOF {
t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
} }
} }
...@@ -701,7 +701,7 @@ func TestLinesAfterRead(t *testing.T) { ...@@ -701,7 +701,7 @@ func TestLinesAfterRead(t *testing.T) {
type readLineResult struct { type readLineResult struct {
line []byte line []byte
isPrefix bool isPrefix bool
err os.Error err error
} }
var readLineNewlinesTests = []struct { var readLineNewlinesTests = []struct {
...@@ -714,27 +714,27 @@ var readLineNewlinesTests = []struct { ...@@ -714,27 +714,27 @@ var readLineNewlinesTests = []struct {
{nil, false, nil}, {nil, false, nil},
{[]byte("b"), true, nil}, {[]byte("b"), true, nil},
{nil, false, nil}, {nil, false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
{"hello\r\nworld\r\n", 6, []readLineResult{ {"hello\r\nworld\r\n", 6, []readLineResult{
{[]byte("hello"), true, nil}, {[]byte("hello"), true, nil},
{nil, false, nil}, {nil, false, nil},
{[]byte("world"), true, nil}, {[]byte("world"), true, nil},
{nil, false, nil}, {nil, false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
{"hello\rworld\r", 6, []readLineResult{ {"hello\rworld\r", 6, []readLineResult{
{[]byte("hello"), true, nil}, {[]byte("hello"), true, nil},
{[]byte("\rworld"), true, nil}, {[]byte("\rworld"), true, nil},
{[]byte("\r"), false, nil}, {[]byte("\r"), false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
{"h\ri\r\n\r", 2, []readLineResult{ {"h\ri\r\n\r", 2, []readLineResult{
{[]byte("h"), true, nil}, {[]byte("h"), true, nil},
{[]byte("\ri"), true, nil}, {[]byte("\ri"), true, nil},
{nil, false, nil}, {nil, false, nil},
{[]byte("\r"), false, nil}, {[]byte("\r"), false, nil},
{nil, false, os.EOF}, {nil, false, io.EOF},
}}, }},
} }
......
...@@ -7,8 +7,8 @@ package bytes ...@@ -7,8 +7,8 @@ package bytes
// Simple byte buffer for marshaling data. // Simple byte buffer for marshaling data.
import ( import (
"errors"
"io" "io"
"os"
"utf8" "utf8"
) )
...@@ -94,7 +94,7 @@ func (b *Buffer) grow(n int) int { ...@@ -94,7 +94,7 @@ func (b *Buffer) grow(n int) int {
// Write appends the contents of p to the buffer. The return // Write appends the contents of p to the buffer. The return
// value n is the length of p; err is always nil. // value n is the length of p; err is always nil.
func (b *Buffer) Write(p []byte) (n int, err os.Error) { func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
m := b.grow(len(p)) m := b.grow(len(p))
copy(b.buf[m:], p) copy(b.buf[m:], p)
...@@ -103,7 +103,7 @@ func (b *Buffer) Write(p []byte) (n int, err os.Error) { ...@@ -103,7 +103,7 @@ func (b *Buffer) Write(p []byte) (n int, err os.Error) {
// WriteString appends the contents of s to the buffer. The return // WriteString appends the contents of s to the buffer. The return
// value n is the length of s; err is always nil. // value n is the length of s; err is always nil.
func (b *Buffer) WriteString(s string) (n int, err os.Error) { func (b *Buffer) WriteString(s string) (n int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
m := b.grow(len(s)) m := b.grow(len(s))
return copy(b.buf[m:], s), nil return copy(b.buf[m:], s), nil
...@@ -119,7 +119,7 @@ const MinRead = 512 ...@@ -119,7 +119,7 @@ const MinRead = 512
// The return value n is the number of bytes read. // The return value n is the number of bytes read.
// Any error except os.EOF encountered during the read // Any error except os.EOF encountered during the read
// is also returned. // is also returned.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) { func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
// If buffer is empty, reset to recover space. // If buffer is empty, reset to recover space.
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
...@@ -143,7 +143,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) { ...@@ -143,7 +143,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]) m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
b.buf = b.buf[0 : len(b.buf)+m] b.buf = b.buf[0 : len(b.buf)+m]
n += int64(m) n += int64(m)
if e == os.EOF { if e == io.EOF {
break break
} }
if e != nil { if e != nil {
...@@ -157,7 +157,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) { ...@@ -157,7 +157,7 @@ func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) {
// occurs. The return value n is the number of bytes written; it always // occurs. The return value n is the number of bytes written; it always
// fits into an int, but it is int64 to match the io.WriterTo interface. // fits into an int, but it is int64 to match the io.WriterTo interface.
// Any error encountered during the write is also returned. // Any error encountered during the write is also returned.
func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) { func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off < len(b.buf) { if b.off < len(b.buf) {
m, e := w.Write(b.buf[b.off:]) m, e := w.Write(b.buf[b.off:])
...@@ -177,7 +177,7 @@ func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) { ...@@ -177,7 +177,7 @@ func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.Error) {
// WriteByte appends the byte c to the buffer. // WriteByte appends the byte c to the buffer.
// The returned error is always nil, but is included // The returned error is always nil, but is included
// to match bufio.Writer's WriteByte. // to match bufio.Writer's WriteByte.
func (b *Buffer) WriteByte(c byte) os.Error { func (b *Buffer) WriteByte(c byte) error {
b.lastRead = opInvalid b.lastRead = opInvalid
m := b.grow(1) m := b.grow(1)
b.buf[m] = c b.buf[m] = c
...@@ -188,7 +188,7 @@ func (b *Buffer) WriteByte(c byte) os.Error { ...@@ -188,7 +188,7 @@ func (b *Buffer) WriteByte(c byte) os.Error {
// code point r to the buffer, returning its length and // code point r to the buffer, returning its length and
// an error, which is always nil but is included // an error, which is always nil but is included
// to match bufio.Writer's WriteRune. // to match bufio.Writer's WriteRune.
func (b *Buffer) WriteRune(r rune) (n int, err os.Error) { func (b *Buffer) WriteRune(r rune) (n int, err error) {
if r < utf8.RuneSelf { if r < utf8.RuneSelf {
b.WriteByte(byte(r)) b.WriteByte(byte(r))
return 1, nil return 1, nil
...@@ -202,12 +202,12 @@ func (b *Buffer) WriteRune(r rune) (n int, err os.Error) { ...@@ -202,12 +202,12 @@ func (b *Buffer) WriteRune(r rune) (n int, err os.Error) {
// is drained. The return value n is the number of bytes read. If the // is drained. The return value n is the number of bytes read. If the
// buffer has no data to return, err is os.EOF even if len(p) is zero; // buffer has no data to return, err is os.EOF even if len(p) is zero;
// otherwise it is nil. // otherwise it is nil.
func (b *Buffer) Read(p []byte) (n int, err os.Error) { func (b *Buffer) Read(p []byte) (n int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space. // Buffer is empty, reset to recover space.
b.Truncate(0) b.Truncate(0)
return 0, os.EOF return 0, io.EOF
} }
n = copy(p, b.buf[b.off:]) n = copy(p, b.buf[b.off:])
b.off += n b.off += n
...@@ -237,12 +237,12 @@ func (b *Buffer) Next(n int) []byte { ...@@ -237,12 +237,12 @@ func (b *Buffer) Next(n int) []byte {
// ReadByte reads and returns the next byte from the buffer. // ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns error os.EOF. // If no byte is available, it returns error os.EOF.
func (b *Buffer) ReadByte() (c byte, err os.Error) { func (b *Buffer) ReadByte() (c byte, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space. // Buffer is empty, reset to recover space.
b.Truncate(0) b.Truncate(0)
return 0, os.EOF return 0, io.EOF
} }
c = b.buf[b.off] c = b.buf[b.off]
b.off++ b.off++
...@@ -255,12 +255,12 @@ func (b *Buffer) ReadByte() (c byte, err os.Error) { ...@@ -255,12 +255,12 @@ func (b *Buffer) ReadByte() (c byte, err os.Error) {
// If no bytes are available, the error returned is os.EOF. // If no bytes are available, the error returned is os.EOF.
// If the bytes are an erroneous UTF-8 encoding, it // If the bytes are an erroneous UTF-8 encoding, it
// consumes one byte and returns U+FFFD, 1. // consumes one byte and returns U+FFFD, 1.
func (b *Buffer) ReadRune() (r rune, size int, err os.Error) { func (b *Buffer) ReadRune() (r rune, size int, err error) {
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off >= len(b.buf) { if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space. // Buffer is empty, reset to recover space.
b.Truncate(0) b.Truncate(0)
return 0, 0, os.EOF return 0, 0, io.EOF
} }
b.lastRead = opReadRune b.lastRead = opReadRune
c := b.buf[b.off] c := b.buf[b.off]
...@@ -278,9 +278,9 @@ func (b *Buffer) ReadRune() (r rune, size int, err os.Error) { ...@@ -278,9 +278,9 @@ func (b *Buffer) ReadRune() (r rune, size int, err os.Error) {
// not a ReadRune, UnreadRune returns an error. (In this regard // not a ReadRune, UnreadRune returns an error. (In this regard
// it is stricter than UnreadByte, which will unread the last byte // it is stricter than UnreadByte, which will unread the last byte
// from any read operation.) // from any read operation.)
func (b *Buffer) UnreadRune() os.Error { func (b *Buffer) UnreadRune() error {
if b.lastRead != opReadRune { if b.lastRead != opReadRune {
return os.NewError("bytes.Buffer: UnreadRune: previous operation was not ReadRune") return errors.New("bytes.Buffer: UnreadRune: previous operation was not ReadRune")
} }
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off > 0 { if b.off > 0 {
...@@ -293,9 +293,9 @@ func (b *Buffer) UnreadRune() os.Error { ...@@ -293,9 +293,9 @@ func (b *Buffer) UnreadRune() os.Error {
// UnreadByte unreads the last byte returned by the most recent // UnreadByte unreads the last byte returned by the most recent
// read operation. If write has happened since the last read, UnreadByte // read operation. If write has happened since the last read, UnreadByte
// returns an error. // returns an error.
func (b *Buffer) UnreadByte() os.Error { func (b *Buffer) UnreadByte() error {
if b.lastRead != opReadRune && b.lastRead != opRead { if b.lastRead != opReadRune && b.lastRead != opRead {
return os.NewError("bytes.Buffer: UnreadByte: previous operation was not a read") return errors.New("bytes.Buffer: UnreadByte: previous operation was not a read")
} }
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off > 0 { if b.off > 0 {
...@@ -310,12 +310,12 @@ func (b *Buffer) UnreadByte() os.Error { ...@@ -310,12 +310,12 @@ func (b *Buffer) UnreadByte() os.Error {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadBytes returns err != nil if and only if the returned data does not end in // ReadBytes returns err != nil if and only if the returned data does not end in
// delim. // delim.
func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) { func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) {
i := IndexByte(b.buf[b.off:], delim) i := IndexByte(b.buf[b.off:], delim)
size := i + 1 size := i + 1
if i < 0 { if i < 0 {
size = len(b.buf) - b.off size = len(b.buf) - b.off
err = os.EOF err = io.EOF
} }
line = make([]byte, size) line = make([]byte, size)
copy(line, b.buf[b.off:]) copy(line, b.buf[b.off:])
...@@ -329,7 +329,7 @@ func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) { ...@@ -329,7 +329,7 @@ func (b *Buffer) ReadBytes(delim byte) (line []byte, err os.Error) {
// it returns the data read before the error and the error itself (often os.EOF). // it returns the data read before the error and the error itself (often os.EOF).
// ReadString returns err != nil if and only if the returned data does not end // ReadString returns err != nil if and only if the returned data does not end
// in delim. // in delim.
func (b *Buffer) ReadString(delim byte) (line string, err os.Error) { func (b *Buffer) ReadString(delim byte) (line string, err error) {
bytes, err := b.ReadBytes(delim) bytes, err := b.ReadBytes(delim)
return string(bytes), err return string(bytes), err
} }
......
...@@ -6,7 +6,7 @@ package bytes_test ...@@ -6,7 +6,7 @@ package bytes_test
import ( import (
. "bytes" . "bytes"
"os" "io"
"rand" "rand"
"testing" "testing"
"utf8" "utf8"
...@@ -344,21 +344,21 @@ var readBytesTests = []struct { ...@@ -344,21 +344,21 @@ var readBytesTests = []struct {
buffer string buffer string
delim byte delim byte
expected []string expected []string
err os.Error err error
}{ }{
{"", 0, []string{""}, os.EOF}, {"", 0, []string{""}, io.EOF},
{"a\x00", 0, []string{"a\x00"}, nil}, {"a\x00", 0, []string{"a\x00"}, nil},
{"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil}, {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil},
{"hello\x01world", 1, []string{"hello\x01"}, nil}, {"hello\x01world", 1, []string{"hello\x01"}, nil},
{"foo\nbar", 0, []string{"foo\nbar"}, os.EOF}, {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF},
{"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil}, {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil},
{"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, os.EOF}, {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF},
} }
func TestReadBytes(t *testing.T) { func TestReadBytes(t *testing.T) {
for _, test := range readBytesTests { for _, test := range readBytesTests {
buf := NewBufferString(test.buffer) buf := NewBufferString(test.buffer)
var err os.Error var err error
for _, expected := range test.expected { for _, expected := range test.expected {
var bytes []byte var bytes []byte
bytes, err = buf.ReadBytes(test.delim) bytes, err = buf.ReadBytes(test.delim)
......
...@@ -7,25 +7,24 @@ package bzip2 ...@@ -7,25 +7,24 @@ package bzip2
import ( import (
"bufio" "bufio"
"io" "io"
"os"
) )
// bitReader wraps an io.Reader and provides the ability to read values, // bitReader wraps an io.Reader and provides the ability to read values,
// bit-by-bit, from it. Its Read* methods don't return the usual os.Error // bit-by-bit, from it. Its Read* methods don't return the usual error
// because the error handling was verbose. Instead, any error is kept and can // because the error handling was verbose. Instead, any error is kept and can
// be checked afterwards. // be checked afterwards.
type bitReader struct { type bitReader struct {
r byteReader r byteReader
n uint64 n uint64
bits uint bits uint
err os.Error err error
} }
// bitReader needs to read bytes from an io.Reader. We attempt to cast the // bitReader needs to read bytes from an io.Reader. We attempt to cast the
// given io.Reader to this interface and, if it doesn't already fit, we wrap in // given io.Reader to this interface and, if it doesn't already fit, we wrap in
// a bufio.Reader. // a bufio.Reader.
type byteReader interface { type byteReader interface {
ReadByte() (byte, os.Error) ReadByte() (byte, error)
} }
func newBitReader(r io.Reader) bitReader { func newBitReader(r io.Reader) bitReader {
...@@ -42,7 +41,7 @@ func newBitReader(r io.Reader) bitReader { ...@@ -42,7 +41,7 @@ func newBitReader(r io.Reader) bitReader {
func (br *bitReader) ReadBits64(bits uint) (n uint64) { func (br *bitReader) ReadBits64(bits uint) (n uint64) {
for bits > br.bits { for bits > br.bits {
b, err := br.r.ReadByte() b, err := br.r.ReadByte()
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
if err != nil { if err != nil {
...@@ -83,6 +82,6 @@ func (br *bitReader) ReadBit() bool { ...@@ -83,6 +82,6 @@ func (br *bitReader) ReadBit() bool {
return n != 0 return n != 0
} }
func (br *bitReader) Error() os.Error { func (br *bitReader) Error() error {
return br.err return br.err
} }
...@@ -5,10 +5,7 @@ ...@@ -5,10 +5,7 @@
// Package bzip2 implements bzip2 decompression. // Package bzip2 implements bzip2 decompression.
package bzip2 package bzip2
import ( import "io"
"io"
"os"
)
// There's no RFC for bzip2. I used the Wikipedia page for reference and a lot // There's no RFC for bzip2. I used the Wikipedia page for reference and a lot
// of guessing: http://en.wikipedia.org/wiki/Bzip2 // of guessing: http://en.wikipedia.org/wiki/Bzip2
...@@ -19,7 +16,7 @@ import ( ...@@ -19,7 +16,7 @@ import (
// syntactically invalid. // syntactically invalid.
type StructuralError string type StructuralError string
func (s StructuralError) String() string { func (s StructuralError) Error() string {
return "bzip2 data invalid: " + string(s) return "bzip2 data invalid: " + string(s)
} }
...@@ -53,7 +50,7 @@ const bzip2BlockMagic = 0x314159265359 ...@@ -53,7 +50,7 @@ const bzip2BlockMagic = 0x314159265359
const bzip2FinalMagic = 0x177245385090 const bzip2FinalMagic = 0x177245385090
// setup parses the bzip2 header. // setup parses the bzip2 header.
func (bz2 *reader) setup() os.Error { func (bz2 *reader) setup() error {
br := &bz2.br br := &bz2.br
magic := br.ReadBits(16) magic := br.ReadBits(16)
...@@ -76,9 +73,9 @@ func (bz2 *reader) setup() os.Error { ...@@ -76,9 +73,9 @@ func (bz2 *reader) setup() os.Error {
return nil return nil
} }
func (bz2 *reader) Read(buf []byte) (n int, err os.Error) { func (bz2 *reader) Read(buf []byte) (n int, err error) {
if bz2.eof { if bz2.eof {
return 0, os.EOF return 0, io.EOF
} }
if !bz2.setupDone { if !bz2.setupDone {
...@@ -101,7 +98,7 @@ func (bz2 *reader) Read(buf []byte) (n int, err os.Error) { ...@@ -101,7 +98,7 @@ func (bz2 *reader) Read(buf []byte) (n int, err os.Error) {
return return
} }
func (bz2 *reader) read(buf []byte) (n int, err os.Error) { func (bz2 *reader) read(buf []byte) (n int, err error) {
// bzip2 is a block based compressor, except that it has a run-length // bzip2 is a block based compressor, except that it has a run-length
// preprocessing step. The block based nature means that we can // preprocessing step. The block based nature means that we can
// preallocate fixed-size buffers and reuse them. However, the RLE // preallocate fixed-size buffers and reuse them. However, the RLE
...@@ -162,7 +159,7 @@ func (bz2 *reader) read(buf []byte) (n int, err os.Error) { ...@@ -162,7 +159,7 @@ func (bz2 *reader) read(buf []byte) (n int, err os.Error) {
if magic == bzip2FinalMagic { if magic == bzip2FinalMagic {
br.ReadBits64(32) // ignored CRC br.ReadBits64(32) // ignored CRC
bz2.eof = true bz2.eof = true
return 0, os.EOF return 0, io.EOF
} else if magic != bzip2BlockMagic { } else if magic != bzip2BlockMagic {
return 0, StructuralError("bad magic value found") return 0, StructuralError("bad magic value found")
} }
...@@ -176,7 +173,7 @@ func (bz2 *reader) read(buf []byte) (n int, err os.Error) { ...@@ -176,7 +173,7 @@ func (bz2 *reader) read(buf []byte) (n int, err os.Error) {
} }
// readBlock reads a bzip2 block. The magic number should already have been consumed. // readBlock reads a bzip2 block. The magic number should already have been consumed.
func (bz2 *reader) readBlock() (err os.Error) { func (bz2 *reader) readBlock() (err error) {
br := &bz2.br br := &bz2.br
br.ReadBits64(32) // skip checksum. TODO: check it if we can figure out what it is. br.ReadBits64(32) // skip checksum. TODO: check it if we can figure out what it is.
randomized := br.ReadBits(1) randomized := br.ReadBits(1)
......
...@@ -9,7 +9,6 @@ import ( ...@@ -9,7 +9,6 @@ import (
"encoding/hex" "encoding/hex"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
...@@ -46,7 +45,7 @@ func readerFromHex(s string) io.Reader { ...@@ -46,7 +45,7 @@ func readerFromHex(s string) io.Reader {
return bytes.NewBuffer(data) return bytes.NewBuffer(data)
} }
func decompressHex(s string) (out []byte, err os.Error) { func decompressHex(s string) (out []byte, err error) {
r := NewReader(readerFromHex(s)) r := NewReader(readerFromHex(s))
return ioutil.ReadAll(r) return ioutil.ReadAll(r)
} }
......
...@@ -4,10 +4,7 @@ ...@@ -4,10 +4,7 @@
package bzip2 package bzip2
import ( import "sort"
"os"
"sort"
)
// A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a // A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a
// symbol. // symbol.
...@@ -63,7 +60,7 @@ func (t huffmanTree) Decode(br *bitReader) (v uint16) { ...@@ -63,7 +60,7 @@ func (t huffmanTree) Decode(br *bitReader) (v uint16) {
// newHuffmanTree builds a Huffman tree from a slice containing the code // newHuffmanTree builds a Huffman tree from a slice containing the code
// lengths of each symbol. The maximum code length is 32 bits. // lengths of each symbol. The maximum code length is 32 bits.
func newHuffmanTree(lengths []uint8) (huffmanTree, os.Error) { func newHuffmanTree(lengths []uint8) (huffmanTree, error) {
// There are many possible trees that assign the same code length to // There are many possible trees that assign the same code length to
// each symbol (consider reflecting a tree down the middle, for // each symbol (consider reflecting a tree down the middle, for
// example). Since the code length assignments determine the // example). Since the code length assignments determine the
...@@ -176,7 +173,7 @@ func (n huffmanCodes) Swap(i, j int) { ...@@ -176,7 +173,7 @@ func (n huffmanCodes) Swap(i, j int) {
// buildHuffmanNode takes a slice of sorted huffmanCodes and builds a node in // buildHuffmanNode takes a slice of sorted huffmanCodes and builds a node in
// the Huffman tree at the given level. It returns the index of the newly // the Huffman tree at the given level. It returns the index of the newly
// constructed node. // constructed node.
func buildHuffmanNode(t *huffmanTree, codes []huffmanCode, level uint32) (nodeIndex uint16, err os.Error) { func buildHuffmanNode(t *huffmanTree, codes []huffmanCode, level uint32) (nodeIndex uint16, err error) {
test := uint32(1) << (31 - level) test := uint32(1) << (31 - level)
// We have to search the list of codes to find the divide between the left and right sides. // We have to search the list of codes to find the divide between the left and right sides.
......
...@@ -7,7 +7,6 @@ package flate ...@@ -7,7 +7,6 @@ package flate
import ( import (
"io" "io"
"math" "math"
"os"
) )
const ( const (
...@@ -89,7 +88,7 @@ type compressor struct { ...@@ -89,7 +88,7 @@ type compressor struct {
offset int offset int
hash int hash int
maxInsertIndex int maxInsertIndex int
err os.Error err error
} }
func (d *compressor) fillDeflate(b []byte) int { func (d *compressor) fillDeflate(b []byte) int {
...@@ -123,7 +122,7 @@ func (d *compressor) fillDeflate(b []byte) int { ...@@ -123,7 +122,7 @@ func (d *compressor) fillDeflate(b []byte) int {
return n return n
} }
func (d *compressor) writeBlock(tokens []token, index int, eof bool) os.Error { func (d *compressor) writeBlock(tokens []token, index int, eof bool) error {
if index > 0 || eof { if index > 0 || eof {
var window []byte var window []byte
if d.blockStart <= index { if d.blockStart <= index {
...@@ -194,7 +193,7 @@ func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead ...@@ -194,7 +193,7 @@ func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead
return return
} }
func (d *compressor) writeStoredBlock(buf []byte) os.Error { func (d *compressor) writeStoredBlock(buf []byte) error {
if d.w.writeStoredHeader(len(buf), false); d.w.err != nil { if d.w.writeStoredHeader(len(buf), false); d.w.err != nil {
return d.w.err return d.w.err
} }
...@@ -365,7 +364,7 @@ func (d *compressor) store() { ...@@ -365,7 +364,7 @@ func (d *compressor) store() {
d.windowEnd = 0 d.windowEnd = 0
} }
func (d *compressor) write(b []byte) (n int, err os.Error) { func (d *compressor) write(b []byte) (n int, err error) {
n = len(b) n = len(b)
b = b[d.fill(d, b):] b = b[d.fill(d, b):]
for len(b) > 0 { for len(b) > 0 {
...@@ -375,7 +374,7 @@ func (d *compressor) write(b []byte) (n int, err os.Error) { ...@@ -375,7 +374,7 @@ func (d *compressor) write(b []byte) (n int, err os.Error) {
return n, d.err return n, d.err
} }
func (d *compressor) syncFlush() os.Error { func (d *compressor) syncFlush() error {
d.sync = true d.sync = true
d.step(d) d.step(d)
if d.err == nil { if d.err == nil {
...@@ -387,7 +386,7 @@ func (d *compressor) syncFlush() os.Error { ...@@ -387,7 +386,7 @@ func (d *compressor) syncFlush() os.Error {
return d.err return d.err
} }
func (d *compressor) init(w io.Writer, level int) (err os.Error) { func (d *compressor) init(w io.Writer, level int) (err error) {
d.w = newHuffmanBitWriter(w) d.w = newHuffmanBitWriter(w)
switch { switch {
...@@ -409,7 +408,7 @@ func (d *compressor) init(w io.Writer, level int) (err os.Error) { ...@@ -409,7 +408,7 @@ func (d *compressor) init(w io.Writer, level int) (err os.Error) {
return nil return nil
} }
func (d *compressor) close() os.Error { func (d *compressor) close() error {
d.sync = true d.sync = true
d.step(d) d.step(d)
if d.err != nil { if d.err != nil {
...@@ -455,7 +454,7 @@ type dictWriter struct { ...@@ -455,7 +454,7 @@ type dictWriter struct {
enabled bool enabled bool
} }
func (w *dictWriter) Write(b []byte) (n int, err os.Error) { func (w *dictWriter) Write(b []byte) (n int, err error) {
if w.enabled { if w.enabled {
return w.w.Write(b) return w.w.Write(b)
} }
...@@ -470,7 +469,7 @@ type Writer struct { ...@@ -470,7 +469,7 @@ type Writer struct {
// Write writes data to w, which will eventually write the // Write writes data to w, which will eventually write the
// compressed form of data to its underlying writer. // compressed form of data to its underlying writer.
func (w *Writer) Write(data []byte) (n int, err os.Error) { func (w *Writer) Write(data []byte) (n int, err error) {
return w.d.write(data) return w.d.write(data)
} }
...@@ -481,13 +480,13 @@ func (w *Writer) Write(data []byte) (n int, err os.Error) { ...@@ -481,13 +480,13 @@ func (w *Writer) Write(data []byte) (n int, err os.Error) {
// If the underlying writer returns an error, Flush returns that error. // If the underlying writer returns an error, Flush returns that error.
// //
// In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH. // In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
func (w *Writer) Flush() os.Error { func (w *Writer) Flush() error {
// For more about flushing: // For more about flushing:
// http://www.bolet.org/~pornin/deflate-flush.html // http://www.bolet.org/~pornin/deflate-flush.html
return w.d.syncFlush() return w.d.syncFlush()
} }
// Close flushes and closes the writer. // Close flushes and closes the writer.
func (w *Writer) Close() os.Error { func (w *Writer) Close() error {
return w.d.close() return w.d.close()
} }
...@@ -9,7 +9,6 @@ import ( ...@@ -9,7 +9,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"sync" "sync"
"testing" "testing"
) )
...@@ -102,7 +101,7 @@ func newSyncBuffer() *syncBuffer { ...@@ -102,7 +101,7 @@ func newSyncBuffer() *syncBuffer {
return &syncBuffer{ready: make(chan bool, 1)} return &syncBuffer{ready: make(chan bool, 1)}
} }
func (b *syncBuffer) Read(p []byte) (n int, err os.Error) { func (b *syncBuffer) Read(p []byte) (n int, err error) {
for { for {
b.mu.RLock() b.mu.RLock()
n, err = b.buf.Read(p) n, err = b.buf.Read(p)
...@@ -122,7 +121,7 @@ func (b *syncBuffer) signal() { ...@@ -122,7 +121,7 @@ func (b *syncBuffer) signal() {
} }
} }
func (b *syncBuffer) Write(p []byte) (n int, err os.Error) { func (b *syncBuffer) Write(p []byte) (n int, err error) {
n, err = b.buf.Write(p) n, err = b.buf.Write(p)
b.signal() b.signal()
return return
...@@ -137,7 +136,7 @@ func (b *syncBuffer) ReadMode() { ...@@ -137,7 +136,7 @@ func (b *syncBuffer) ReadMode() {
b.signal() b.signal()
} }
func (b *syncBuffer) Close() os.Error { func (b *syncBuffer) Close() error {
b.closed = true b.closed = true
b.signal() b.signal()
return nil return nil
...@@ -204,7 +203,7 @@ func testSync(t *testing.T, level int, input []byte, name string) { ...@@ -204,7 +203,7 @@ func testSync(t *testing.T, level int, input []byte, name string) {
} }
buf.ReadMode() buf.ReadMode()
out := make([]byte, 10) out := make([]byte, 10)
if n, err := r.Read(out); n > 0 || err != os.EOF { if n, err := r.Read(out); n > 0 || err != io.EOF {
t.Errorf("testSync (%d, %d, %s): final Read: %d, %v (hex: %x)", level, len(input), name, n, err, out[0:n]) t.Errorf("testSync (%d, %d, %s): final Read: %d, %v (hex: %x)", level, len(input), name, n, err, out[0:n])
} }
if buf.buf.Len() != 0 { if buf.buf.Len() != 0 {
...@@ -225,7 +224,7 @@ func testSync(t *testing.T, level int, input []byte, name string) { ...@@ -225,7 +224,7 @@ func testSync(t *testing.T, level int, input []byte, name string) {
} }
} }
func testToFromWithLevel(t *testing.T, level int, input []byte, name string) os.Error { func testToFromWithLevel(t *testing.T, level int, input []byte, name string) error {
buffer := bytes.NewBuffer(nil) buffer := bytes.NewBuffer(nil)
w := NewWriter(buffer, level) w := NewWriter(buffer, level)
w.Write(input) w.Write(input)
......
...@@ -7,7 +7,6 @@ package flate ...@@ -7,7 +7,6 @@ package flate
import ( import (
"io" "io"
"math" "math"
"os"
"strconv" "strconv"
) )
...@@ -83,7 +82,7 @@ type huffmanBitWriter struct { ...@@ -83,7 +82,7 @@ type huffmanBitWriter struct {
literalEncoding *huffmanEncoder literalEncoding *huffmanEncoder
offsetEncoding *huffmanEncoder offsetEncoding *huffmanEncoder
codegenEncoding *huffmanEncoder codegenEncoding *huffmanEncoder
err os.Error err error
} }
type WrongValueError struct { type WrongValueError struct {
...@@ -106,7 +105,7 @@ func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter { ...@@ -106,7 +105,7 @@ func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
} }
} }
func (err WrongValueError) String() string { func (err WrongValueError) Error() string {
return "huffmanBitWriter: " + err.name + " should belong to [" + strconv.Itoa64(int64(err.from)) + ";" + return "huffmanBitWriter: " + err.name + " should belong to [" + strconv.Itoa64(int64(err.from)) + ";" +
strconv.Itoa64(int64(err.to)) + "] but actual value is " + strconv.Itoa64(int64(err.value)) strconv.Itoa64(int64(err.to)) + "] but actual value is " + strconv.Itoa64(int64(err.value))
} }
......
...@@ -10,7 +10,6 @@ package flate ...@@ -10,7 +10,6 @@ package flate
import ( import (
"bufio" "bufio"
"io" "io"
"os"
"strconv" "strconv"
) )
...@@ -25,33 +24,33 @@ const ( ...@@ -25,33 +24,33 @@ const (
// A CorruptInputError reports the presence of corrupt input at a given offset. // A CorruptInputError reports the presence of corrupt input at a given offset.
type CorruptInputError int64 type CorruptInputError int64
func (e CorruptInputError) String() string { func (e CorruptInputError) Error() string {
return "flate: corrupt input before offset " + strconv.Itoa64(int64(e)) return "flate: corrupt input before offset " + strconv.Itoa64(int64(e))
} }
// An InternalError reports an error in the flate code itself. // An InternalError reports an error in the flate code itself.
type InternalError string type InternalError string
func (e InternalError) String() string { return "flate: internal error: " + string(e) } func (e InternalError) Error() string { return "flate: internal error: " + string(e) }
// A ReadError reports an error encountered while reading input. // A ReadError reports an error encountered while reading input.
type ReadError struct { type ReadError struct {
Offset int64 // byte offset where error occurred Offset int64 // byte offset where error occurred
Error os.Error // error returned by underlying Read Err error // error returned by underlying Read
} }
func (e *ReadError) String() string { func (e *ReadError) Error() string {
return "flate: read error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Error.String() return "flate: read error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Err.Error()
} }
// A WriteError reports an error encountered while writing output. // A WriteError reports an error encountered while writing output.
type WriteError struct { type WriteError struct {
Offset int64 // byte offset where error occurred Offset int64 // byte offset where error occurred
Error os.Error // error returned by underlying Write Err error // error returned by underlying Write
} }
func (e *WriteError) String() string { func (e *WriteError) Error() string {
return "flate: write error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Error.String() return "flate: write error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Err.Error()
} }
// Huffman decoder is based on // Huffman decoder is based on
...@@ -190,7 +189,7 @@ var fixedHuffmanDecoder = huffmanDecoder{ ...@@ -190,7 +189,7 @@ var fixedHuffmanDecoder = huffmanDecoder{
// the NewReader will introduce its own buffering. // the NewReader will introduce its own buffering.
type Reader interface { type Reader interface {
io.Reader io.Reader
ReadByte() (c byte, err os.Error) ReadByte() (c byte, err error)
} }
// Decompress state. // Decompress state.
...@@ -224,7 +223,7 @@ type decompressor struct { ...@@ -224,7 +223,7 @@ type decompressor struct {
// and decompression state. // and decompression state.
step func(*decompressor) step func(*decompressor)
final bool final bool
err os.Error err error
toRead []byte toRead []byte
hl, hd *huffmanDecoder hl, hd *huffmanDecoder
copyLen int copyLen int
...@@ -237,7 +236,7 @@ func (f *decompressor) nextBlock() { ...@@ -237,7 +236,7 @@ func (f *decompressor) nextBlock() {
f.flush((*decompressor).nextBlock) f.flush((*decompressor).nextBlock)
return return
} }
f.err = os.EOF f.err = io.EOF
return return
} }
for f.nb < 1+2 { for f.nb < 1+2 {
...@@ -272,7 +271,7 @@ func (f *decompressor) nextBlock() { ...@@ -272,7 +271,7 @@ func (f *decompressor) nextBlock() {
} }
} }
func (f *decompressor) Read(b []byte) (int, os.Error) { func (f *decompressor) Read(b []byte) (int, error) {
for { for {
if len(f.toRead) > 0 { if len(f.toRead) > 0 {
n := copy(b, f.toRead) n := copy(b, f.toRead)
...@@ -287,8 +286,8 @@ func (f *decompressor) Read(b []byte) (int, os.Error) { ...@@ -287,8 +286,8 @@ func (f *decompressor) Read(b []byte) (int, os.Error) {
panic("unreachable") panic("unreachable")
} }
func (f *decompressor) Close() os.Error { func (f *decompressor) Close() error {
if f.err == os.EOF { if f.err == io.EOF {
return nil return nil
} }
return f.err return f.err
...@@ -299,7 +298,7 @@ func (f *decompressor) Close() os.Error { ...@@ -299,7 +298,7 @@ func (f *decompressor) Close() os.Error {
var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
func (f *decompressor) readHuffman() os.Error { func (f *decompressor) readHuffman() error {
// HLIT[5], HDIST[5], HCLEN[4]. // HLIT[5], HDIST[5], HCLEN[4].
for f.nb < 5+5+4 { for f.nb < 5+5+4 {
if err := f.moreBits(); err != nil { if err := f.moreBits(); err != nil {
...@@ -625,10 +624,10 @@ func (f *decompressor) setDict(dict []byte) { ...@@ -625,10 +624,10 @@ func (f *decompressor) setDict(dict []byte) {
f.hw = f.hp f.hw = f.hp
} }
func (f *decompressor) moreBits() os.Error { func (f *decompressor) moreBits() error {
c, err := f.r.ReadByte() c, err := f.r.ReadByte()
if err != nil { if err != nil {
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return err return err
...@@ -640,7 +639,7 @@ func (f *decompressor) moreBits() os.Error { ...@@ -640,7 +639,7 @@ func (f *decompressor) moreBits() os.Error {
} }
// Read the next Huffman-encoded symbol from f according to h. // Read the next Huffman-encoded symbol from f according to h.
func (f *decompressor) huffSym(h *huffmanDecoder) (int, os.Error) { func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) {
for n := uint(h.min); n <= uint(h.max); n++ { for n := uint(h.min); n <= uint(h.max); n++ {
lim := h.limit[n] lim := h.limit[n]
if lim == -1 { if lim == -1 {
......
...@@ -9,10 +9,10 @@ package gzip ...@@ -9,10 +9,10 @@ package gzip
import ( import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"io" "io"
"os"
) )
// BUG(nigeltao): Comments and Names don't properly map UTF-8 character codes outside of // BUG(nigeltao): Comments and Names don't properly map UTF-8 character codes outside of
...@@ -36,8 +36,8 @@ func makeReader(r io.Reader) flate.Reader { ...@@ -36,8 +36,8 @@ func makeReader(r io.Reader) flate.Reader {
return bufio.NewReader(r) return bufio.NewReader(r)
} }
var HeaderError = os.NewError("invalid gzip header") var HeaderError = errors.New("invalid gzip header")
var ChecksumError = os.NewError("gzip checksum error") var ChecksumError = errors.New("gzip checksum error")
// The gzip file stores a header giving metadata about the compressed file. // The gzip file stores a header giving metadata about the compressed file.
// That header is exposed as the fields of the Compressor and Decompressor structs. // That header is exposed as the fields of the Compressor and Decompressor structs.
...@@ -71,13 +71,13 @@ type Decompressor struct { ...@@ -71,13 +71,13 @@ type Decompressor struct {
size uint32 size uint32
flg byte flg byte
buf [512]byte buf [512]byte
err os.Error err error
} }
// NewReader creates a new Decompressor reading the given reader. // NewReader creates a new Decompressor reading the given reader.
// The implementation buffers input and may read more data than necessary 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 Decompressor when done. // It is the caller's responsibility to call Close on the Decompressor when done.
func NewReader(r io.Reader) (*Decompressor, os.Error) { func NewReader(r io.Reader) (*Decompressor, error) {
z := new(Decompressor) z := new(Decompressor)
z.r = makeReader(r) z.r = makeReader(r)
z.digest = crc32.NewIEEE() z.digest = crc32.NewIEEE()
...@@ -93,8 +93,8 @@ func get4(p []byte) uint32 { ...@@ -93,8 +93,8 @@ func get4(p []byte) uint32 {
return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24 return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
} }
func (z *Decompressor) readString() (string, os.Error) { func (z *Decompressor) readString() (string, error) {
var err os.Error var err error
for i := 0; ; i++ { for i := 0; ; i++ {
if i >= len(z.buf) { if i >= len(z.buf) {
return "", HeaderError return "", HeaderError
...@@ -112,7 +112,7 @@ func (z *Decompressor) readString() (string, os.Error) { ...@@ -112,7 +112,7 @@ func (z *Decompressor) readString() (string, os.Error) {
panic("not reached") panic("not reached")
} }
func (z *Decompressor) read2() (uint32, os.Error) { func (z *Decompressor) read2() (uint32, error) {
_, err := io.ReadFull(z.r, z.buf[0:2]) _, err := io.ReadFull(z.r, z.buf[0:2])
if err != nil { if err != nil {
return 0, err return 0, err
...@@ -120,7 +120,7 @@ func (z *Decompressor) read2() (uint32, os.Error) { ...@@ -120,7 +120,7 @@ func (z *Decompressor) read2() (uint32, os.Error) {
return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil
} }
func (z *Decompressor) readHeader(save bool) os.Error { func (z *Decompressor) readHeader(save bool) error {
_, err := io.ReadFull(z.r, z.buf[0:10]) _, err := io.ReadFull(z.r, z.buf[0:10])
if err != nil { if err != nil {
return err return err
...@@ -186,7 +186,7 @@ func (z *Decompressor) readHeader(save bool) os.Error { ...@@ -186,7 +186,7 @@ func (z *Decompressor) readHeader(save bool) os.Error {
return nil return nil
} }
func (z *Decompressor) Read(p []byte) (n int, err os.Error) { func (z *Decompressor) Read(p []byte) (n int, err error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
...@@ -197,7 +197,7 @@ func (z *Decompressor) Read(p []byte) (n int, err os.Error) { ...@@ -197,7 +197,7 @@ func (z *Decompressor) Read(p []byte) (n int, err os.Error) {
n, err = z.decompressor.Read(p) n, err = z.decompressor.Read(p)
z.digest.Write(p[0:n]) z.digest.Write(p[0:n])
z.size += uint32(n) z.size += uint32(n)
if n != 0 || err != os.EOF { if n != 0 || err != io.EOF {
z.err = err z.err = err
return return
} }
...@@ -227,4 +227,4 @@ func (z *Decompressor) Read(p []byte) (n int, err os.Error) { ...@@ -227,4 +227,4 @@ func (z *Decompressor) Read(p []byte) (n int, err os.Error) {
} }
// Calling Close does not close the wrapped io.Reader originally passed to NewReader. // Calling Close does not close the wrapped io.Reader originally passed to NewReader.
func (z *Decompressor) Close() os.Error { return z.decompressor.Close() } func (z *Decompressor) Close() error { return z.decompressor.Close() }
...@@ -7,7 +7,6 @@ package gzip ...@@ -7,7 +7,6 @@ package gzip
import ( import (
"bytes" "bytes"
"io" "io"
"os"
"testing" "testing"
) )
...@@ -16,7 +15,7 @@ type gunzipTest struct { ...@@ -16,7 +15,7 @@ type gunzipTest struct {
desc string desc string
raw string raw string
gzip []byte gzip []byte
err os.Error err error
} }
var gunzipTests = []gunzipTest{ var gunzipTests = []gunzipTest{
......
...@@ -6,10 +6,10 @@ package gzip ...@@ -6,10 +6,10 @@ package gzip
import ( import (
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/crc32" "hash/crc32"
"io" "io"
"os"
) )
// These constants are copied from the flate package, so that code that imports // These constants are copied from the flate package, so that code that imports
...@@ -32,11 +32,11 @@ type Compressor struct { ...@@ -32,11 +32,11 @@ type Compressor struct {
size uint32 size uint32
closed bool closed bool
buf [10]byte buf [10]byte
err os.Error err error
} }
// NewWriter calls NewWriterLevel with the default compression level. // NewWriter calls NewWriterLevel with the default compression level.
func NewWriter(w io.Writer) (*Compressor, os.Error) { func NewWriter(w io.Writer) (*Compressor, error) {
return NewWriterLevel(w, DefaultCompression) return NewWriterLevel(w, DefaultCompression)
} }
...@@ -47,7 +47,7 @@ func NewWriter(w io.Writer) (*Compressor, os.Error) { ...@@ -47,7 +47,7 @@ func NewWriter(w io.Writer) (*Compressor, os.Error) {
// It is the caller's responsibility to call Close on the WriteCloser when done. // It is the caller's responsibility to call Close on the WriteCloser when done.
// level is the compression level, which can be DefaultCompression, NoCompression, // level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive). // or any integer value between BestSpeed and BestCompression (inclusive).
func NewWriterLevel(w io.Writer, level int) (*Compressor, os.Error) { func NewWriterLevel(w io.Writer, level int) (*Compressor, error) {
z := new(Compressor) z := new(Compressor)
z.OS = 255 // unknown z.OS = 255 // unknown
z.w = w z.w = w
...@@ -70,9 +70,9 @@ func put4(p []byte, v uint32) { ...@@ -70,9 +70,9 @@ func put4(p []byte, v uint32) {
} }
// writeBytes writes a length-prefixed byte slice to z.w. // writeBytes writes a length-prefixed byte slice to z.w.
func (z *Compressor) writeBytes(b []byte) os.Error { func (z *Compressor) writeBytes(b []byte) error {
if len(b) > 0xffff { if len(b) > 0xffff {
return os.NewError("gzip.Write: Extra data is too large") return errors.New("gzip.Write: Extra data is too large")
} }
put2(z.buf[0:2], uint16(len(b))) put2(z.buf[0:2], uint16(len(b)))
_, err := z.w.Write(z.buf[0:2]) _, err := z.w.Write(z.buf[0:2])
...@@ -84,12 +84,12 @@ func (z *Compressor) writeBytes(b []byte) os.Error { ...@@ -84,12 +84,12 @@ func (z *Compressor) writeBytes(b []byte) os.Error {
} }
// writeString writes a string (in ISO 8859-1 (Latin-1) format) to z.w. // writeString writes a string (in ISO 8859-1 (Latin-1) format) to z.w.
func (z *Compressor) writeString(s string) os.Error { func (z *Compressor) writeString(s string) error {
// GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1). // GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1).
// TODO(nigeltao): Convert from UTF-8 to ISO 8859-1 (Latin-1). // TODO(nigeltao): Convert from UTF-8 to ISO 8859-1 (Latin-1).
for _, v := range s { for _, v := range s {
if v == 0 || v > 0x7f { if v == 0 || v > 0x7f {
return os.NewError("gzip.Write: non-ASCII header string") return errors.New("gzip.Write: non-ASCII header string")
} }
} }
_, err := io.WriteString(z.w, s) _, err := io.WriteString(z.w, s)
...@@ -102,7 +102,7 @@ func (z *Compressor) writeString(s string) os.Error { ...@@ -102,7 +102,7 @@ func (z *Compressor) writeString(s string) os.Error {
return err return err
} }
func (z *Compressor) Write(p []byte) (int, os.Error) { func (z *Compressor) Write(p []byte) (int, error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
...@@ -162,7 +162,7 @@ func (z *Compressor) Write(p []byte) (int, os.Error) { ...@@ -162,7 +162,7 @@ func (z *Compressor) Write(p []byte) (int, os.Error) {
} }
// Calling Close does not close the wrapped io.Writer originally passed to NewWriter. // Calling Close does not close the wrapped io.Writer originally passed to NewWriter.
func (z *Compressor) Close() os.Error { func (z *Compressor) Close() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }
......
...@@ -16,6 +16,7 @@ package lzw ...@@ -16,6 +16,7 @@ package lzw
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
...@@ -45,9 +46,9 @@ type decoder struct { ...@@ -45,9 +46,9 @@ type decoder struct {
bits uint32 bits uint32
nBits uint nBits uint
width uint width uint
read func(*decoder) (uint16, os.Error) // readLSB or readMSB read func(*decoder) (uint16, error) // readLSB or readMSB
litWidth int // width in bits of literal codes litWidth int // width in bits of literal codes
err os.Error err error
// The first 1<<litWidth codes are literal codes. // The first 1<<litWidth codes are literal codes.
// The next two codes mean clear and EOF. // The next two codes mean clear and EOF.
...@@ -78,7 +79,7 @@ type decoder struct { ...@@ -78,7 +79,7 @@ type decoder struct {
} }
// readLSB returns the next code for "Least Significant Bits first" data. // readLSB returns the next code for "Least Significant Bits first" data.
func (d *decoder) readLSB() (uint16, os.Error) { func (d *decoder) readLSB() (uint16, error) {
for d.nBits < d.width { for d.nBits < d.width {
x, err := d.r.ReadByte() x, err := d.r.ReadByte()
if err != nil { if err != nil {
...@@ -94,7 +95,7 @@ func (d *decoder) readLSB() (uint16, os.Error) { ...@@ -94,7 +95,7 @@ func (d *decoder) readLSB() (uint16, os.Error) {
} }
// readMSB returns the next code for "Most Significant Bits first" data. // readMSB returns the next code for "Most Significant Bits first" data.
func (d *decoder) readMSB() (uint16, os.Error) { func (d *decoder) readMSB() (uint16, error) {
for d.nBits < d.width { for d.nBits < d.width {
x, err := d.r.ReadByte() x, err := d.r.ReadByte()
if err != nil { if err != nil {
...@@ -109,7 +110,7 @@ func (d *decoder) readMSB() (uint16, os.Error) { ...@@ -109,7 +110,7 @@ func (d *decoder) readMSB() (uint16, os.Error) {
return code, nil return code, nil
} }
func (d *decoder) Read(b []byte) (int, os.Error) { func (d *decoder) Read(b []byte) (int, error) {
for { for {
if len(d.toRead) > 0 { if len(d.toRead) > 0 {
n := copy(b, d.toRead) n := copy(b, d.toRead)
...@@ -132,7 +133,7 @@ func (d *decoder) decode() { ...@@ -132,7 +133,7 @@ func (d *decoder) decode() {
for { for {
code, err := d.read(d) code, err := d.read(d)
if err != nil { if err != nil {
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
d.err = err d.err = err
...@@ -156,7 +157,7 @@ func (d *decoder) decode() { ...@@ -156,7 +157,7 @@ func (d *decoder) decode() {
continue continue
case code == d.eof: case code == d.eof:
d.flush() d.flush()
d.err = os.EOF d.err = io.EOF
return return
case code <= d.hi: case code <= d.hi:
c, i := code, len(d.output)-1 c, i := code, len(d.output)-1
...@@ -186,7 +187,7 @@ func (d *decoder) decode() { ...@@ -186,7 +187,7 @@ func (d *decoder) decode() {
d.prefix[d.hi] = d.last d.prefix[d.hi] = d.last
} }
default: default:
d.err = os.NewError("lzw: invalid code") d.err = errors.New("lzw: invalid code")
return return
} }
d.last, d.hi = code, d.hi+1 d.last, d.hi = code, d.hi+1
...@@ -211,7 +212,7 @@ func (d *decoder) flush() { ...@@ -211,7 +212,7 @@ func (d *decoder) flush() {
d.o = 0 d.o = 0
} }
func (d *decoder) Close() os.Error { func (d *decoder) Close() error {
d.err = os.EINVAL // in case any Reads come along d.err = os.EINVAL // in case any Reads come along
return nil return nil
} }
...@@ -230,7 +231,7 @@ func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser { ...@@ -230,7 +231,7 @@ func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser {
case MSB: case MSB:
d.read = (*decoder).readMSB d.read = (*decoder).readMSB
default: default:
d.err = os.NewError("lzw: unknown order") d.err = errors.New("lzw: unknown order")
return d return d
} }
if litWidth < 2 || 8 < litWidth { if litWidth < 2 || 8 < litWidth {
......
...@@ -8,7 +8,6 @@ import ( ...@@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
...@@ -19,7 +18,7 @@ type lzwTest struct { ...@@ -19,7 +18,7 @@ type lzwTest struct {
desc string desc string
raw string raw string
compressed string compressed string
err os.Error err error
} }
var lzwTests = []lzwTest{ var lzwTests = []lzwTest{
......
...@@ -6,6 +6,7 @@ package lzw ...@@ -6,6 +6,7 @@ package lzw
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
...@@ -13,20 +14,20 @@ import ( ...@@ -13,20 +14,20 @@ import (
// A writer is a buffered, flushable writer. // A writer is a buffered, flushable writer.
type writer interface { type writer interface {
WriteByte(byte) os.Error WriteByte(byte) error
Flush() os.Error Flush() error
} }
// An errWriteCloser is an io.WriteCloser that always returns a given error. // An errWriteCloser is an io.WriteCloser that always returns a given error.
type errWriteCloser struct { type errWriteCloser struct {
err os.Error err error
} }
func (e *errWriteCloser) Write([]byte) (int, os.Error) { func (e *errWriteCloser) Write([]byte) (int, error) {
return 0, e.err return 0, e.err
} }
func (e *errWriteCloser) Close() os.Error { func (e *errWriteCloser) Close() error {
return e.err return e.err
} }
...@@ -50,7 +51,7 @@ type encoder struct { ...@@ -50,7 +51,7 @@ type encoder struct {
w writer w writer
// write, bits, nBits and width are the state for converting a code stream // write, bits, nBits and width are the state for converting a code stream
// into a byte stream. // into a byte stream.
write func(*encoder, uint32) os.Error write func(*encoder, uint32) error
bits uint32 bits uint32
nBits uint nBits uint
width uint width uint
...@@ -64,7 +65,7 @@ type encoder struct { ...@@ -64,7 +65,7 @@ type encoder struct {
savedCode uint32 savedCode uint32
// err is the first error encountered during writing. Closing the encoder // err is the first error encountered during writing. Closing the encoder
// will make any future Write calls return os.EINVAL. // will make any future Write calls return os.EINVAL.
err os.Error err error
// table is the hash table from 20-bit keys to 12-bit values. Each table // table is the hash table from 20-bit keys to 12-bit values. Each table
// entry contains key<<12|val and collisions resolve by linear probing. // entry contains key<<12|val and collisions resolve by linear probing.
// The keys consist of a 12-bit code prefix and an 8-bit byte suffix. // The keys consist of a 12-bit code prefix and an 8-bit byte suffix.
...@@ -73,7 +74,7 @@ type encoder struct { ...@@ -73,7 +74,7 @@ type encoder struct {
} }
// writeLSB writes the code c for "Least Significant Bits first" data. // writeLSB writes the code c for "Least Significant Bits first" data.
func (e *encoder) writeLSB(c uint32) os.Error { func (e *encoder) writeLSB(c uint32) error {
e.bits |= c << e.nBits e.bits |= c << e.nBits
e.nBits += e.width e.nBits += e.width
for e.nBits >= 8 { for e.nBits >= 8 {
...@@ -87,7 +88,7 @@ func (e *encoder) writeLSB(c uint32) os.Error { ...@@ -87,7 +88,7 @@ func (e *encoder) writeLSB(c uint32) os.Error {
} }
// writeMSB writes the code c for "Most Significant Bits first" data. // writeMSB writes the code c for "Most Significant Bits first" data.
func (e *encoder) writeMSB(c uint32) os.Error { func (e *encoder) writeMSB(c uint32) error {
e.bits |= c << (32 - e.width - e.nBits) e.bits |= c << (32 - e.width - e.nBits)
e.nBits += e.width e.nBits += e.width
for e.nBits >= 8 { for e.nBits >= 8 {
...@@ -102,12 +103,12 @@ func (e *encoder) writeMSB(c uint32) os.Error { ...@@ -102,12 +103,12 @@ func (e *encoder) writeMSB(c uint32) os.Error {
// errOutOfCodes is an internal error that means that the encoder has run out // errOutOfCodes is an internal error that means that the encoder has run out
// of unused codes and a clear code needs to be sent next. // of unused codes and a clear code needs to be sent next.
var errOutOfCodes = os.NewError("lzw: out of codes") var errOutOfCodes = errors.New("lzw: out of codes")
// incHi increments e.hi and checks for both overflow and running out of // incHi increments e.hi and checks for both overflow and running out of
// unused codes. In the latter case, incHi sends a clear code, resets the // unused codes. In the latter case, incHi sends a clear code, resets the
// encoder state and returns errOutOfCodes. // encoder state and returns errOutOfCodes.
func (e *encoder) incHi() os.Error { func (e *encoder) incHi() error {
e.hi++ e.hi++
if e.hi == e.overflow { if e.hi == e.overflow {
e.width++ e.width++
...@@ -130,7 +131,7 @@ func (e *encoder) incHi() os.Error { ...@@ -130,7 +131,7 @@ func (e *encoder) incHi() os.Error {
} }
// Write writes a compressed representation of p to e's underlying writer. // Write writes a compressed representation of p to e's underlying writer.
func (e *encoder) Write(p []byte) (int, os.Error) { func (e *encoder) Write(p []byte) (int, error) {
if e.err != nil { if e.err != nil {
return 0, e.err return 0, e.err
} }
...@@ -188,7 +189,7 @@ loop: ...@@ -188,7 +189,7 @@ loop:
// Close closes the encoder, flushing any pending output. It does not close or // Close closes the encoder, flushing any pending output. It does not close or
// flush e's underlying writer. // flush e's underlying writer.
func (e *encoder) Close() os.Error { func (e *encoder) Close() error {
if e.err != nil { if e.err != nil {
if e.err == os.EINVAL { if e.err == os.EINVAL {
return nil return nil
...@@ -230,14 +231,14 @@ func (e *encoder) Close() os.Error { ...@@ -230,14 +231,14 @@ func (e *encoder) Close() os.Error {
// The number of bits to use for literal codes, litWidth, must be in the // The number of bits to use for literal codes, litWidth, must be in the
// range [2,8] and is typically 8. // range [2,8] and is typically 8.
func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser { func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser {
var write func(*encoder, uint32) os.Error var write func(*encoder, uint32) error
switch order { switch order {
case LSB: case LSB:
write = (*encoder).writeLSB write = (*encoder).writeLSB
case MSB: case MSB:
write = (*encoder).writeMSB write = (*encoder).writeMSB
default: default:
return &errWriteCloser{os.NewError("lzw: unknown order")} return &errWriteCloser{errors.New("lzw: unknown order")}
} }
if litWidth < 2 || 8 < litWidth { if litWidth < 2 || 8 < litWidth {
return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)} return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)}
......
...@@ -45,7 +45,7 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) { ...@@ -45,7 +45,7 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) {
var b [4096]byte var b [4096]byte
for { for {
n, err0 := raw.Read(b[:]) n, err0 := raw.Read(b[:])
if err0 != nil && err0 != os.EOF { if err0 != nil && err0 != io.EOF {
t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0) t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err0)
return return
} }
...@@ -58,7 +58,7 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) { ...@@ -58,7 +58,7 @@ func testFile(t *testing.T, fn string, order Order, litWidth int) {
t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1) t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1)
return return
} }
if err0 == os.EOF { if err0 == io.EOF {
break break
} }
} }
......
...@@ -26,36 +26,36 @@ package zlib ...@@ -26,36 +26,36 @@ package zlib
import ( import (
"bufio" "bufio"
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/adler32" "hash/adler32"
"io" "io"
"os"
) )
const zlibDeflate = 8 const zlibDeflate = 8
var ChecksumError = os.NewError("zlib checksum error") var ChecksumError = errors.New("zlib checksum error")
var HeaderError = os.NewError("invalid zlib header") var HeaderError = errors.New("invalid zlib header")
var DictionaryError = os.NewError("invalid zlib dictionary") var DictionaryError = errors.New("invalid zlib dictionary")
type reader struct { type reader struct {
r flate.Reader r flate.Reader
decompressor io.ReadCloser decompressor io.ReadCloser
digest hash.Hash32 digest hash.Hash32
err os.Error err error
scratch [4]byte scratch [4]byte
} }
// NewReader creates a new io.ReadCloser that satisfies reads by decompressing data read from r. // NewReader 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. // 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. // It is the caller's responsibility to call Close on the ReadCloser when done.
func NewReader(r io.Reader) (io.ReadCloser, os.Error) { func NewReader(r io.Reader) (io.ReadCloser, error) {
return NewReaderDict(r, nil) return NewReaderDict(r, nil)
} }
// NewReaderDict is like NewReader but uses a preset dictionary. // NewReaderDict is like NewReader but uses a preset dictionary.
// NewReaderDict ignores the dictionary if the compressed data does not refer to it. // NewReaderDict ignores the dictionary if the compressed data does not refer to it.
func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, os.Error) { func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error) {
z := new(reader) z := new(reader)
if fr, ok := r.(flate.Reader); ok { if fr, ok := r.(flate.Reader); ok {
z.r = fr z.r = fr
...@@ -87,7 +87,7 @@ func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, os.Error) { ...@@ -87,7 +87,7 @@ func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, os.Error) {
return z, nil return z, nil
} }
func (z *reader) Read(p []byte) (n int, err os.Error) { func (z *reader) Read(p []byte) (n int, err error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
...@@ -97,7 +97,7 @@ func (z *reader) Read(p []byte) (n int, err os.Error) { ...@@ -97,7 +97,7 @@ func (z *reader) Read(p []byte) (n int, err os.Error) {
n, err = z.decompressor.Read(p) n, err = z.decompressor.Read(p)
z.digest.Write(p[0:n]) z.digest.Write(p[0:n])
if n != 0 || err != os.EOF { if n != 0 || err != io.EOF {
z.err = err z.err = err
return return
} }
...@@ -117,7 +117,7 @@ func (z *reader) Read(p []byte) (n int, err os.Error) { ...@@ -117,7 +117,7 @@ func (z *reader) Read(p []byte) (n int, err os.Error) {
} }
// Calling Close does not close the wrapped io.Reader originally passed to NewReader. // Calling Close does not close the wrapped io.Reader originally passed to NewReader.
func (z *reader) Close() os.Error { func (z *reader) Close() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }
......
...@@ -7,7 +7,6 @@ package zlib ...@@ -7,7 +7,6 @@ package zlib
import ( import (
"bytes" "bytes"
"io" "io"
"os"
"testing" "testing"
) )
...@@ -16,7 +15,7 @@ type zlibTest struct { ...@@ -16,7 +15,7 @@ type zlibTest struct {
raw string raw string
compressed []byte compressed []byte
dict []byte dict []byte
err os.Error err error
} }
// Compare-to-golden test data was generated by the ZLIB example program at // Compare-to-golden test data was generated by the ZLIB example program at
......
...@@ -6,10 +6,10 @@ package zlib ...@@ -6,10 +6,10 @@ package zlib
import ( import (
"compress/flate" "compress/flate"
"errors"
"hash" "hash"
"hash/adler32" "hash/adler32"
"io" "io"
"os"
) )
// These constants are copied from the flate package, so that code that imports // These constants are copied from the flate package, so that code that imports
...@@ -27,17 +27,17 @@ type Writer struct { ...@@ -27,17 +27,17 @@ type Writer struct {
w io.Writer w io.Writer
compressor *flate.Writer compressor *flate.Writer
digest hash.Hash32 digest hash.Hash32
err os.Error err error
scratch [4]byte scratch [4]byte
} }
// NewWriter calls NewWriterLevel with the default compression level. // NewWriter calls NewWriterLevel with the default compression level.
func NewWriter(w io.Writer) (*Writer, os.Error) { func NewWriter(w io.Writer) (*Writer, error) {
return NewWriterLevel(w, DefaultCompression) return NewWriterLevel(w, DefaultCompression)
} }
// NewWriterLevel calls NewWriterDict with no dictionary. // NewWriterLevel calls NewWriterDict with no dictionary.
func NewWriterLevel(w io.Writer, level int) (*Writer, os.Error) { func NewWriterLevel(w io.Writer, level int) (*Writer, error) {
return NewWriterDict(w, level, nil) return NewWriterDict(w, level, nil)
} }
...@@ -46,7 +46,7 @@ func NewWriterLevel(w io.Writer, level int) (*Writer, os.Error) { ...@@ -46,7 +46,7 @@ func NewWriterLevel(w io.Writer, level int) (*Writer, os.Error) {
// level is the compression level, which can be DefaultCompression, NoCompression, // level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive). // or any integer value between BestSpeed and BestCompression (inclusive).
// dict is the preset dictionary to compress with, or nil to use no dictionary. // dict is the preset dictionary to compress with, or nil to use no dictionary.
func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) { func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) {
z := new(Writer) z := new(Writer)
// ZLIB has a two-byte header (as documented in RFC 1950). // 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 first four bits is the CINFO (compression info), which is 7 for the default deflate window size.
...@@ -66,7 +66,7 @@ func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) { ...@@ -66,7 +66,7 @@ func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) {
case 7, 8, 9: case 7, 8, 9:
z.scratch[1] = 3 << 6 z.scratch[1] = 3 << 6
default: default:
return nil, os.NewError("level out of range") return nil, errors.New("level out of range")
} }
if dict != nil { if dict != nil {
z.scratch[1] |= 1 << 5 z.scratch[1] |= 1 << 5
...@@ -94,7 +94,7 @@ func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) { ...@@ -94,7 +94,7 @@ func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, os.Error) {
return z, nil return z, nil
} }
func (z *Writer) Write(p []byte) (n int, err os.Error) { func (z *Writer) Write(p []byte) (n int, err error) {
if z.err != nil { if z.err != nil {
return 0, z.err return 0, z.err
} }
...@@ -111,7 +111,7 @@ func (z *Writer) Write(p []byte) (n int, err os.Error) { ...@@ -111,7 +111,7 @@ func (z *Writer) Write(p []byte) (n int, err os.Error) {
} }
// Flush flushes the underlying compressor. // Flush flushes the underlying compressor.
func (z *Writer) Flush() os.Error { func (z *Writer) Flush() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }
...@@ -120,7 +120,7 @@ func (z *Writer) Flush() os.Error { ...@@ -120,7 +120,7 @@ func (z *Writer) Flush() os.Error {
} }
// Calling Close does not close the wrapped io.Writer originally passed to NewWriter. // Calling Close does not close the wrapped io.Writer originally passed to NewWriter.
func (z *Writer) Close() os.Error { func (z *Writer) Close() error {
if z.err != nil { if z.err != nil {
return z.err return z.err
} }
......
...@@ -4,10 +4,7 @@ ...@@ -4,10 +4,7 @@
package aes package aes
import ( import "strconv"
"os"
"strconv"
)
// The AES block size in bytes. // The AES block size in bytes.
const BlockSize = 16 const BlockSize = 16
...@@ -20,7 +17,7 @@ type Cipher struct { ...@@ -20,7 +17,7 @@ type Cipher struct {
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/aes: invalid key size " + strconv.Itoa(int(k)) return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
} }
...@@ -28,7 +25,7 @@ func (k KeySizeError) String() string { ...@@ -28,7 +25,7 @@ func (k KeySizeError) String() string {
// The key argument should be the AES key, // The key argument should be the AES key,
// either 16, 24, or 32 bytes to select // either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256. // AES-128, AES-192, or AES-256.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
k := len(key) k := len(key)
switch k { switch k {
default: default:
......
...@@ -4,10 +4,7 @@ ...@@ -4,10 +4,7 @@
package bcrypt package bcrypt
import ( import "encoding/base64"
"encoding/base64"
"os"
)
const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
...@@ -23,7 +20,7 @@ func base64Encode(src []byte) []byte { ...@@ -23,7 +20,7 @@ func base64Encode(src []byte) []byte {
return dst[:n] return dst[:n]
} }
func base64Decode(src []byte) ([]byte, os.Error) { func base64Decode(src []byte) ([]byte, error) {
numOfEquals := 4 - (len(src) % 4) numOfEquals := 4 - (len(src) % 4)
for i := 0; i < numOfEquals; i++ { for i := 0; i < numOfEquals; i++ {
src = append(src, '=') src = append(src, '=')
......
...@@ -11,9 +11,9 @@ import ( ...@@ -11,9 +11,9 @@ import (
"crypto/blowfish" "crypto/blowfish"
"crypto/rand" "crypto/rand"
"crypto/subtle" "crypto/subtle"
"errors"
"fmt" "fmt"
"io" "io"
"os"
"strconv" "strconv"
) )
...@@ -25,30 +25,30 @@ const ( ...@@ -25,30 +25,30 @@ const (
// The error returned from CompareHashAndPassword when a password and hash do // The error returned from CompareHashAndPassword when a password and hash do
// not match. // not match.
var MismatchedHashAndPasswordError = os.NewError("crypto/bcrypt: hashedPassword is not the hash of the given password") var MismatchedHashAndPasswordError = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password")
// The error returned from CompareHashAndPassword when a hash is too short to // The error returned from CompareHashAndPassword when a hash is too short to
// be a bcrypt hash. // be a bcrypt hash.
var HashTooShortError = os.NewError("crypto/bcrypt: hashedSecret too short to be a bcrypted password") var HashTooShortError = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password")
// The error returned from CompareHashAndPassword when a hash was created with // The error returned from CompareHashAndPassword when a hash was created with
// a bcrypt algorithm newer than this implementation. // a bcrypt algorithm newer than this implementation.
type HashVersionTooNewError byte type HashVersionTooNewError byte
func (hv HashVersionTooNewError) String() string { func (hv HashVersionTooNewError) Error() string {
return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion) return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion)
} }
// The error returned from CompareHashAndPassword when a hash starts with something other than '$' // The error returned from CompareHashAndPassword when a hash starts with something other than '$'
type InvalidHashPrefixError byte type InvalidHashPrefixError byte
func (ih InvalidHashPrefixError) String() string { func (ih InvalidHashPrefixError) Error() string {
return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih)) return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih))
} }
type InvalidCostError int type InvalidCostError int
func (ic InvalidCostError) String() string { func (ic InvalidCostError) Error() string {
return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost)) return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost))
} }
...@@ -85,7 +85,7 @@ type hashed struct { ...@@ -85,7 +85,7 @@ type hashed struct {
// cost. If the cost given is less than MinCost, the cost will be set to // cost. If the cost given is less than MinCost, the cost will be set to
// MinCost, instead. Use CompareHashAndPassword, as defined in this package, // MinCost, instead. Use CompareHashAndPassword, as defined in this package,
// to compare the returned hashed password with its cleartext version. // to compare the returned hashed password with its cleartext version.
func GenerateFromPassword(password []byte, cost int) ([]byte, os.Error) { func GenerateFromPassword(password []byte, cost int) ([]byte, error) {
p, err := newFromPassword(password, cost) p, err := newFromPassword(password, cost)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -96,7 +96,7 @@ func GenerateFromPassword(password []byte, cost int) ([]byte, os.Error) { ...@@ -96,7 +96,7 @@ func GenerateFromPassword(password []byte, cost int) ([]byte, os.Error) {
// CompareHashAndPassword compares a bcrypt hashed password with its possible // CompareHashAndPassword compares a bcrypt hashed password with its possible
// plaintext equivalent. Note: Using bytes.Equal for this job is // plaintext equivalent. Note: Using bytes.Equal for this job is
// insecure. Returns nil on success, or an error on failure. // insecure. Returns nil on success, or an error on failure.
func CompareHashAndPassword(hashedPassword, password []byte) os.Error { func CompareHashAndPassword(hashedPassword, password []byte) error {
p, err := newFromHash(hashedPassword) p, err := newFromHash(hashedPassword)
if err != nil { if err != nil {
return err return err
...@@ -115,7 +115,7 @@ func CompareHashAndPassword(hashedPassword, password []byte) os.Error { ...@@ -115,7 +115,7 @@ func CompareHashAndPassword(hashedPassword, password []byte) os.Error {
return MismatchedHashAndPasswordError return MismatchedHashAndPasswordError
} }
func newFromPassword(password []byte, cost int) (*hashed, os.Error) { func newFromPassword(password []byte, cost int) (*hashed, error) {
if cost < MinCost { if cost < MinCost {
cost = DefaultCost cost = DefaultCost
} }
...@@ -144,7 +144,7 @@ func newFromPassword(password []byte, cost int) (*hashed, os.Error) { ...@@ -144,7 +144,7 @@ func newFromPassword(password []byte, cost int) (*hashed, os.Error) {
return p, err return p, err
} }
func newFromHash(hashedSecret []byte) (*hashed, os.Error) { func newFromHash(hashedSecret []byte) (*hashed, error) {
if len(hashedSecret) < minHashSize { if len(hashedSecret) < minHashSize {
return nil, HashTooShortError return nil, HashTooShortError
} }
...@@ -172,7 +172,7 @@ func newFromHash(hashedSecret []byte) (*hashed, os.Error) { ...@@ -172,7 +172,7 @@ func newFromHash(hashedSecret []byte) (*hashed, os.Error) {
return p, nil return p, nil
} }
func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, os.Error) { func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, error) {
cipherData := make([]byte, len(magicCipherData)) cipherData := make([]byte, len(magicCipherData))
copy(cipherData, magicCipherData) copy(cipherData, magicCipherData)
...@@ -193,7 +193,7 @@ func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, os.Error) { ...@@ -193,7 +193,7 @@ func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, os.Error) {
return hsh, nil return hsh, nil
} }
func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, os.Error) { func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {
csalt, err := base64Decode(salt) csalt, err := base64Decode(salt)
if err != nil { if err != nil {
...@@ -240,7 +240,7 @@ func (p *hashed) Hash() []byte { ...@@ -240,7 +240,7 @@ func (p *hashed) Hash() []byte {
return arr[:n] return arr[:n]
} }
func (p *hashed) decodeVersion(sbytes []byte) (int, os.Error) { func (p *hashed) decodeVersion(sbytes []byte) (int, error) {
if sbytes[0] != '$' { if sbytes[0] != '$' {
return -1, InvalidHashPrefixError(sbytes[0]) return -1, InvalidHashPrefixError(sbytes[0])
} }
...@@ -257,7 +257,7 @@ func (p *hashed) decodeVersion(sbytes []byte) (int, os.Error) { ...@@ -257,7 +257,7 @@ func (p *hashed) decodeVersion(sbytes []byte) (int, os.Error) {
} }
// sbytes should begin where decodeVersion left off. // sbytes should begin where decodeVersion left off.
func (p *hashed) decodeCost(sbytes []byte) (int, os.Error) { func (p *hashed) decodeCost(sbytes []byte) (int, error) {
cost, err := strconv.Atoi(string(sbytes[0:2])) cost, err := strconv.Atoi(string(sbytes[0:2]))
if err != nil { if err != nil {
return -1, err return -1, err
...@@ -274,7 +274,7 @@ func (p *hashed) String() string { ...@@ -274,7 +274,7 @@ func (p *hashed) String() string {
return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor) return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor)
} }
func checkCost(cost int) os.Error { func checkCost(cost int) error {
if cost < MinCost || cost > MaxCost { if cost < MinCost || cost > MaxCost {
return InvalidCostError(cost) return InvalidCostError(cost)
} }
......
...@@ -6,7 +6,6 @@ package bcrypt ...@@ -6,7 +6,6 @@ package bcrypt
import ( import (
"bytes" "bytes"
"os"
"testing" "testing"
) )
...@@ -68,7 +67,7 @@ func TestTooLongPasswordsWork(t *testing.T) { ...@@ -68,7 +67,7 @@ func TestTooLongPasswordsWork(t *testing.T) {
} }
type InvalidHashTest struct { type InvalidHashTest struct {
err os.Error err error
hash []byte hash []byte
} }
...@@ -81,7 +80,7 @@ var invalidTests = []InvalidHashTest{ ...@@ -81,7 +80,7 @@ var invalidTests = []InvalidHashTest{
} }
func TestInvalidHashErrors(t *testing.T) { func TestInvalidHashErrors(t *testing.T) {
check := func(name string, expected, err os.Error) { check := func(name string, expected, err error) {
if err == nil { if err == nil {
t.Errorf("%s: Should have returned an error", name) t.Errorf("%s: Should have returned an error", name)
} }
......
...@@ -8,10 +8,7 @@ package blowfish ...@@ -8,10 +8,7 @@ package blowfish
// The code is a port of Bruce Schneier's C implementation. // The code is a port of Bruce Schneier's C implementation.
// See http://www.schneier.com/blowfish.html. // See http://www.schneier.com/blowfish.html.
import ( import "strconv"
"os"
"strconv"
)
// The Blowfish block size in bytes. // The Blowfish block size in bytes.
const BlockSize = 8 const BlockSize = 8
...@@ -24,13 +21,13 @@ type Cipher struct { ...@@ -24,13 +21,13 @@ type Cipher struct {
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k))
} }
// NewCipher creates and returns a Cipher. // NewCipher creates and returns a Cipher.
// The key argument should be the Blowfish key, 4 to 56 bytes. // The key argument should be the Blowfish key, 4 to 56 bytes.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
var result Cipher var result Cipher
k := len(key) k := len(key)
if k < 4 || k > 56 { if k < 4 || k > 56 {
...@@ -45,7 +42,7 @@ func NewCipher(key []byte) (*Cipher, os.Error) { ...@@ -45,7 +42,7 @@ func NewCipher(key []byte) (*Cipher, os.Error) {
// schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is
// sufficient and desirable. For bcrypt compatiblity, the key can be over 56 // sufficient and desirable. For bcrypt compatiblity, the key can be over 56
// bytes. // bytes.
func NewSaltedCipher(key, salt []byte) (*Cipher, os.Error) { func NewSaltedCipher(key, salt []byte) (*Cipher, error) {
var result Cipher var result Cipher
k := len(key) k := len(key)
if k < 4 { if k < 4 {
......
...@@ -6,9 +6,7 @@ ...@@ -6,9 +6,7 @@
// OpenPGP cipher. // OpenPGP cipher.
package cast5 package cast5
import ( import "errors"
"os"
)
const BlockSize = 8 const BlockSize = 8
const KeySize = 16 const KeySize = 16
...@@ -18,9 +16,9 @@ type Cipher struct { ...@@ -18,9 +16,9 @@ type Cipher struct {
rotate [16]uint8 rotate [16]uint8
} }
func NewCipher(key []byte) (c *Cipher, err os.Error) { func NewCipher(key []byte) (c *Cipher, err error) {
if len(key) != KeySize { if len(key) != KeySize {
return nil, os.NewError("CAST5: keys must be 16 bytes") return nil, errors.New("CAST5: keys must be 16 bytes")
} }
c = new(Cipher) c = new(Cipher)
......
...@@ -4,10 +4,7 @@ ...@@ -4,10 +4,7 @@
package cipher package cipher
import ( import "io"
"os"
"io"
)
// The Stream* objects are so simple that all their members are public. Users // The Stream* objects are so simple that all their members are public. Users
// can create them themselves. // can create them themselves.
...@@ -19,7 +16,7 @@ type StreamReader struct { ...@@ -19,7 +16,7 @@ type StreamReader struct {
R io.Reader R io.Reader
} }
func (r StreamReader) Read(dst []byte) (n int, err os.Error) { func (r StreamReader) Read(dst []byte) (n int, err error) {
n, err = r.R.Read(dst) n, err = r.R.Read(dst)
r.S.XORKeyStream(dst[:n], dst[:n]) r.S.XORKeyStream(dst[:n], dst[:n])
return return
...@@ -31,10 +28,10 @@ func (r StreamReader) Read(dst []byte) (n int, err os.Error) { ...@@ -31,10 +28,10 @@ func (r StreamReader) Read(dst []byte) (n int, err os.Error) {
type StreamWriter struct { type StreamWriter struct {
S Stream S Stream
W io.Writer W io.Writer
Err os.Error Err error
} }
func (w StreamWriter) Write(src []byte) (n int, err os.Error) { func (w StreamWriter) Write(src []byte) (n int, err error) {
if w.Err != nil { if w.Err != nil {
return 0, w.Err return 0, w.Err
} }
...@@ -50,7 +47,7 @@ func (w StreamWriter) Write(src []byte) (n int, err os.Error) { ...@@ -50,7 +47,7 @@ func (w StreamWriter) Write(src []byte) (n int, err os.Error) {
return return
} }
func (w StreamWriter) Close() os.Error { func (w StreamWriter) Close() error {
// This saves us from either requiring a WriteCloser or having a // This saves us from either requiring a WriteCloser or having a
// StreamWriterCloser. // StreamWriterCloser.
return w.W.(io.Closer).Close() return w.W.(io.Closer).Close()
......
...@@ -4,17 +4,14 @@ ...@@ -4,17 +4,14 @@
package des package des
import ( import "strconv"
"os"
"strconv"
)
// The DES block size in bytes. // The DES block size in bytes.
const BlockSize = 8 const BlockSize = 8
type KeySizeError int type KeySizeError int
func (k KeySizeError) String() string { func (k KeySizeError) Error() string {
return "crypto/des: invalid key size " + strconv.Itoa(int(k)) return "crypto/des: invalid key size " + strconv.Itoa(int(k))
} }
...@@ -24,7 +21,7 @@ type Cipher struct { ...@@ -24,7 +21,7 @@ type Cipher struct {
} }
// NewCipher creates and returns a new Cipher. // NewCipher creates and returns a new Cipher.
func NewCipher(key []byte) (*Cipher, os.Error) { func NewCipher(key []byte) (*Cipher, error) {
if len(key) != 8 { if len(key) != 8 {
return nil, KeySizeError(len(key)) return nil, KeySizeError(len(key))
} }
...@@ -60,7 +57,7 @@ type TripleDESCipher struct { ...@@ -60,7 +57,7 @@ type TripleDESCipher struct {
} }
// NewCipher creates and returns a new Cipher. // NewCipher creates and returns a new Cipher.
func NewTripleDESCipher(key []byte) (*TripleDESCipher, os.Error) { func NewTripleDESCipher(key []byte) (*TripleDESCipher, error) {
if len(key) != 24 { if len(key) != 24 {
return nil, KeySizeError(len(key)) return nil, KeySizeError(len(key))
} }
......
...@@ -7,8 +7,8 @@ package dsa ...@@ -7,8 +7,8 @@ package dsa
import ( import (
"big" "big"
"errors"
"io" "io"
"os"
) )
// Parameters represents the domain parameters for a key. These parameters can // Parameters represents the domain parameters for a key. These parameters can
...@@ -31,7 +31,7 @@ type PrivateKey struct { ...@@ -31,7 +31,7 @@ type PrivateKey struct {
type invalidPublicKeyError int type invalidPublicKeyError int
func (invalidPublicKeyError) String() string { func (invalidPublicKeyError) Error() string {
return "crypto/dsa: invalid public key" return "crypto/dsa: invalid public key"
} }
...@@ -58,7 +58,7 @@ const numMRTests = 64 ...@@ -58,7 +58,7 @@ const numMRTests = 64
// GenerateParameters puts a random, valid set of DSA parameters into params. // GenerateParameters puts a random, valid set of DSA parameters into params.
// This function takes many seconds, even on fast machines. // This function takes many seconds, even on fast machines.
func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err os.Error) { func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err error) {
// This function doesn't follow FIPS 186-3 exactly in that it doesn't // This function doesn't follow FIPS 186-3 exactly in that it doesn't
// use a verification seed to generate the primes. The verification // use a verification seed to generate the primes. The verification
// seed doesn't appear to be exported or used by other code and // seed doesn't appear to be exported or used by other code and
...@@ -79,7 +79,7 @@ func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes ...@@ -79,7 +79,7 @@ func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes
L = 3072 L = 3072
N = 256 N = 256
default: default:
return os.NewError("crypto/dsa: invalid ParameterSizes") return errors.New("crypto/dsa: invalid ParameterSizes")
} }
qBytes := make([]byte, N/8) qBytes := make([]byte, N/8)
...@@ -156,9 +156,9 @@ GeneratePrimes: ...@@ -156,9 +156,9 @@ GeneratePrimes:
// GenerateKey generates a public&private key pair. The Parameters of the // GenerateKey generates a public&private key pair. The Parameters of the
// PrivateKey must already be valid (see GenerateParameters). // PrivateKey must already be valid (see GenerateParameters).
func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error { func GenerateKey(priv *PrivateKey, rand io.Reader) error {
if priv.P == nil || priv.Q == nil || priv.G == nil { if priv.P == nil || priv.Q == nil || priv.G == nil {
return os.NewError("crypto/dsa: parameters not set up before generating key") return errors.New("crypto/dsa: parameters not set up before generating key")
} }
x := new(big.Int) x := new(big.Int)
...@@ -185,7 +185,7 @@ func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error { ...@@ -185,7 +185,7 @@ func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error {
// larger message) using the private key, priv. It returns the signature as a // larger message) using the private key, priv. It returns the signature as a
// pair of integers. The security of the private key depends on the entropy of // pair of integers. The security of the private key depends on the entropy of
// rand. // rand.
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err os.Error) { func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
// FIPS 186-3, section 4.6 // FIPS 186-3, section 4.6
n := priv.Q.BitLen() n := priv.Q.BitLen()
......
...@@ -16,7 +16,6 @@ import ( ...@@ -16,7 +16,6 @@ import (
"big" "big"
"crypto/elliptic" "crypto/elliptic"
"io" "io"
"os"
) )
// PublicKey represents an ECDSA public key. // PublicKey represents an ECDSA public key.
...@@ -35,7 +34,7 @@ var one = new(big.Int).SetInt64(1) ...@@ -35,7 +34,7 @@ var one = new(big.Int).SetInt64(1)
// randFieldElement returns a random element of the field underlying the given // randFieldElement returns a random element of the field underlying the given
// curve using the procedure given in [NSA] A.2.1. // curve using the procedure given in [NSA] A.2.1.
func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err os.Error) { func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
b := make([]byte, c.BitSize/8+8) b := make([]byte, c.BitSize/8+8)
_, err = io.ReadFull(rand, b) _, err = io.ReadFull(rand, b)
if err != nil { if err != nil {
...@@ -50,7 +49,7 @@ func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err os.Err ...@@ -50,7 +49,7 @@ func randFieldElement(c *elliptic.Curve, rand io.Reader) (k *big.Int, err os.Err
} }
// GenerateKey generates a public&private key pair. // GenerateKey generates a public&private key pair.
func GenerateKey(c *elliptic.Curve, rand io.Reader) (priv *PrivateKey, err os.Error) { func GenerateKey(c *elliptic.Curve, rand io.Reader) (priv *PrivateKey, err error) {
k, err := randFieldElement(c, rand) k, err := randFieldElement(c, rand)
if err != nil { if err != nil {
return return
...@@ -86,7 +85,7 @@ func hashToInt(hash []byte, c *elliptic.Curve) *big.Int { ...@@ -86,7 +85,7 @@ func hashToInt(hash []byte, c *elliptic.Curve) *big.Int {
// larger message) using the private key, priv. It returns the signature as a // larger message) using the private key, priv. It returns the signature as a
// pair of integers. The security of the private key depends on the entropy of // pair of integers. The security of the private key depends on the entropy of
// rand. // rand.
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err os.Error) { func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
// See [NSA] 3.4.1 // See [NSA] 3.4.1
c := priv.PublicKey.Curve c := priv.PublicKey.Curve
......
...@@ -16,7 +16,6 @@ package elliptic ...@@ -16,7 +16,6 @@ package elliptic
import ( import (
"big" "big"
"io" "io"
"os"
"sync" "sync"
) )
...@@ -249,7 +248,7 @@ var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f} ...@@ -249,7 +248,7 @@ var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
// GenerateKey returns a public/private key pair. The private key is generated // GenerateKey returns a public/private key pair. The private key is generated
// using the given reader, which must return random data. // using the given reader, which must return random data.
func (curve *Curve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err os.Error) { func (curve *Curve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) {
byteLen := (curve.BitSize + 7) >> 3 byteLen := (curve.BitSize + 7) >> 3
priv = make([]byte, byteLen) priv = make([]byte, byteLen)
......
...@@ -13,7 +13,6 @@ import ( ...@@ -13,7 +13,6 @@ import (
"crypto/sha1" "crypto/sha1"
"crypto/sha256" "crypto/sha256"
"hash" "hash"
"os"
) )
// FIPS 198: // FIPS 198:
...@@ -60,7 +59,7 @@ func (h *hmac) Sum() []byte { ...@@ -60,7 +59,7 @@ func (h *hmac) Sum() []byte {
return h.outer.Sum() return h.outer.Sum()
} }
func (h *hmac) Write(p []byte) (n int, err os.Error) { func (h *hmac) Write(p []byte) (n int, err error) {
return h.inner.Write(p) return h.inner.Write(p)
} }
......
...@@ -8,7 +8,6 @@ package md4 ...@@ -8,7 +8,6 @@ package md4
import ( import (
"crypto" "crypto"
"hash" "hash"
"os"
) )
func init() { func init() {
...@@ -52,7 +51,7 @@ func New() hash.Hash { ...@@ -52,7 +51,7 @@ func New() hash.Hash {
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) { func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p) nn = len(p)
d.len += uint64(nn) d.len += uint64(nn)
if d.nx > 0 { if d.nx > 0 {
......
...@@ -8,7 +8,6 @@ package md5 ...@@ -8,7 +8,6 @@ package md5
import ( import (
"crypto" "crypto"
"hash" "hash"
"os"
) )
func init() { func init() {
...@@ -52,7 +51,7 @@ func New() hash.Hash { ...@@ -52,7 +51,7 @@ func New() hash.Hash {
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) { func (d *digest) Write(p []byte) (nn int, err error) {
nn = len(p) nn = len(p)
d.len += uint64(nn) d.len += uint64(nn)
if d.nx > 0 { if d.nx > 0 {
......
...@@ -14,7 +14,6 @@ import ( ...@@ -14,7 +14,6 @@ import (
_ "crypto/sha1" _ "crypto/sha1"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"os"
"time" "time"
) )
...@@ -106,7 +105,7 @@ type Response struct { ...@@ -106,7 +105,7 @@ type Response struct {
// ParseError results from an invalid OCSP response. // ParseError results from an invalid OCSP response.
type ParseError string type ParseError string
func (p ParseError) String() string { func (p ParseError) Error() string {
return string(p) return string(p)
} }
...@@ -114,7 +113,7 @@ func (p ParseError) String() string { ...@@ -114,7 +113,7 @@ func (p ParseError) String() string {
// responses for a single certificate and only those using RSA signatures. // responses for a single certificate and only those using RSA signatures.
// Non-RSA responses will result in an x509.UnsupportedAlgorithmError. // Non-RSA responses will result in an x509.UnsupportedAlgorithmError.
// Signature errors or parse failures will result in a ParseError. // Signature errors or parse failures will result in a ParseError.
func ParseResponse(bytes []byte) (*Response, os.Error) { func ParseResponse(bytes []byte) (*Response, error) {
var resp responseASN1 var resp responseASN1
rest, err := asn1.Unmarshal(bytes, &resp) rest, err := asn1.Unmarshal(bytes, &resp)
if err != nil { if err != nil {
......
...@@ -9,10 +9,9 @@ package armor ...@@ -9,10 +9,9 @@ package armor
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"encoding/base64" "encoding/base64"
"io" "io"
"os"
) )
// A Block represents an OpenPGP armored structure. // A Block represents an OpenPGP armored structure.
...@@ -36,7 +35,7 @@ type Block struct { ...@@ -36,7 +35,7 @@ type Block struct {
oReader openpgpReader oReader openpgpReader
} }
var ArmorCorrupt os.Error = error.StructuralError("armor invalid") var ArmorCorrupt error = error_.StructuralError("armor invalid")
const crc24Init = 0xb704ce const crc24Init = 0xb704ce
const crc24Poly = 0x1864cfb const crc24Poly = 0x1864cfb
...@@ -69,9 +68,9 @@ type lineReader struct { ...@@ -69,9 +68,9 @@ type lineReader struct {
crc uint32 crc uint32
} }
func (l *lineReader) Read(p []byte) (n int, err os.Error) { func (l *lineReader) Read(p []byte) (n int, err error) {
if l.eof { if l.eof {
return 0, os.EOF return 0, io.EOF
} }
if len(l.buf) > 0 { if len(l.buf) > 0 {
...@@ -101,7 +100,7 @@ func (l *lineReader) Read(p []byte) (n int, err os.Error) { ...@@ -101,7 +100,7 @@ func (l *lineReader) Read(p []byte) (n int, err os.Error) {
uint32(expectedBytes[2]) uint32(expectedBytes[2])
line, _, err = l.in.ReadLine() line, _, err = l.in.ReadLine()
if err != nil && err != os.EOF { if err != nil && err != io.EOF {
return return
} }
if !bytes.HasPrefix(line, armorEnd) { if !bytes.HasPrefix(line, armorEnd) {
...@@ -109,7 +108,7 @@ func (l *lineReader) Read(p []byte) (n int, err os.Error) { ...@@ -109,7 +108,7 @@ func (l *lineReader) Read(p []byte) (n int, err os.Error) {
} }
l.eof = true l.eof = true
return 0, os.EOF return 0, io.EOF
} }
if len(line) > 64 { if len(line) > 64 {
...@@ -138,11 +137,11 @@ type openpgpReader struct { ...@@ -138,11 +137,11 @@ type openpgpReader struct {
currentCRC uint32 currentCRC uint32
} }
func (r *openpgpReader) Read(p []byte) (n int, err os.Error) { func (r *openpgpReader) Read(p []byte) (n int, err error) {
n, err = r.b64Reader.Read(p) n, err = r.b64Reader.Read(p)
r.currentCRC = crc24(r.currentCRC, p[:n]) r.currentCRC = crc24(r.currentCRC, p[:n])
if err == os.EOF { if err == io.EOF {
if r.lReader.crc != uint32(r.currentCRC&crc24Mask) { if r.lReader.crc != uint32(r.currentCRC&crc24Mask) {
return 0, ArmorCorrupt return 0, ArmorCorrupt
} }
...@@ -155,7 +154,7 @@ func (r *openpgpReader) Read(p []byte) (n int, err os.Error) { ...@@ -155,7 +154,7 @@ func (r *openpgpReader) Read(p []byte) (n int, err os.Error) {
// leading garbage. If it doesn't find a block, it will return nil, os.EOF. The // leading garbage. If it doesn't find a block, it will return nil, os.EOF. The
// given Reader is not usable after calling this function: an arbitrary amount // given Reader is not usable after calling this function: an arbitrary amount
// of data may have been read past the end of the block. // of data may have been read past the end of the block.
func Decode(in io.Reader) (p *Block, err os.Error) { func Decode(in io.Reader) (p *Block, err error) {
r, _ := bufio.NewReaderSize(in, 100) r, _ := bufio.NewReaderSize(in, 100)
var line []byte var line []byte
ignoreNext := false ignoreNext := false
......
...@@ -7,7 +7,6 @@ package armor ...@@ -7,7 +7,6 @@ package armor
import ( import (
"encoding/base64" "encoding/base64"
"io" "io"
"os"
) )
var armorHeaderSep = []byte(": ") var armorHeaderSep = []byte(": ")
...@@ -16,7 +15,7 @@ var newline = []byte("\n") ...@@ -16,7 +15,7 @@ var newline = []byte("\n")
var armorEndOfLineOut = []byte("-----\n") var armorEndOfLineOut = []byte("-----\n")
// writeSlices writes its arguments to the given Writer. // writeSlices writes its arguments to the given Writer.
func writeSlices(out io.Writer, slices ...[]byte) (err os.Error) { func writeSlices(out io.Writer, slices ...[]byte) (err error) {
for _, s := range slices { for _, s := range slices {
_, err = out.Write(s) _, err = out.Write(s)
if err != nil { if err != nil {
...@@ -45,7 +44,7 @@ func newLineBreaker(out io.Writer, lineLength int) *lineBreaker { ...@@ -45,7 +44,7 @@ func newLineBreaker(out io.Writer, lineLength int) *lineBreaker {
} }
} }
func (l *lineBreaker) Write(b []byte) (n int, err os.Error) { func (l *lineBreaker) Write(b []byte) (n int, err error) {
n = len(b) n = len(b)
if n == 0 { if n == 0 {
...@@ -81,7 +80,7 @@ func (l *lineBreaker) Write(b []byte) (n int, err os.Error) { ...@@ -81,7 +80,7 @@ func (l *lineBreaker) Write(b []byte) (n int, err os.Error) {
return return
} }
func (l *lineBreaker) Close() (err os.Error) { func (l *lineBreaker) Close() (err error) {
if l.used > 0 { if l.used > 0 {
_, err = l.out.Write(l.line[0:l.used]) _, err = l.out.Write(l.line[0:l.used])
if err != nil { if err != nil {
...@@ -106,12 +105,12 @@ type encoding struct { ...@@ -106,12 +105,12 @@ type encoding struct {
blockType []byte blockType []byte
} }
func (e *encoding) Write(data []byte) (n int, err os.Error) { func (e *encoding) Write(data []byte) (n int, err error) {
e.crc = crc24(e.crc, data) e.crc = crc24(e.crc, data)
return e.b64.Write(data) return e.b64.Write(data)
} }
func (e *encoding) Close() (err os.Error) { func (e *encoding) Close() (err error) {
err = e.b64.Close() err = e.b64.Close()
if err != nil { if err != nil {
return return
...@@ -131,7 +130,7 @@ func (e *encoding) Close() (err os.Error) { ...@@ -131,7 +130,7 @@ func (e *encoding) Close() (err os.Error) {
// Encode returns a WriteCloser which will encode the data written to it in // Encode returns a WriteCloser which will encode the data written to it in
// OpenPGP armor. // OpenPGP armor.
func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err os.Error) { func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) {
bType := []byte(blockType) bType := []byte(blockType)
err = writeSlices(out, armorStart, bType, armorEndOfLineOut) err = writeSlices(out, armorStart, bType, armorEndOfLineOut)
if err != nil { if err != nil {
......
...@@ -4,10 +4,7 @@ ...@@ -4,10 +4,7 @@
package openpgp package openpgp
import ( import "hash"
"hash"
"os"
)
// NewCanonicalTextHash reformats text written to it into the canonical // NewCanonicalTextHash reformats text written to it into the canonical
// form and then applies the hash h. See RFC 4880, section 5.2.1. // form and then applies the hash h. See RFC 4880, section 5.2.1.
...@@ -22,7 +19,7 @@ type canonicalTextHash struct { ...@@ -22,7 +19,7 @@ type canonicalTextHash struct {
var newline = []byte{'\r', '\n'} var newline = []byte{'\r', '\n'}
func (cth *canonicalTextHash) Write(buf []byte) (int, os.Error) { func (cth *canonicalTextHash) Write(buf []byte) (int, error) {
start := 0 start := 0
for i, c := range buf { for i, c := range buf {
......
...@@ -6,7 +6,6 @@ package openpgp ...@@ -6,7 +6,6 @@ package openpgp
import ( import (
"bytes" "bytes"
"os"
"testing" "testing"
) )
...@@ -14,7 +13,7 @@ type recordingHash struct { ...@@ -14,7 +13,7 @@ type recordingHash struct {
buf *bytes.Buffer buf *bytes.Buffer
} }
func (r recordingHash) Write(b []byte) (n int, err os.Error) { func (r recordingHash) Write(b []byte) (n int, err error) {
return r.buf.Write(b) return r.buf.Write(b)
} }
......
...@@ -16,8 +16,8 @@ import ( ...@@ -16,8 +16,8 @@ import (
"big" "big"
"crypto/rand" "crypto/rand"
"crypto/subtle" "crypto/subtle"
"errors"
"io" "io"
"os"
) )
// PublicKey represents an ElGamal public key. // PublicKey represents an ElGamal public key.
...@@ -34,10 +34,10 @@ type PrivateKey struct { ...@@ -34,10 +34,10 @@ type PrivateKey struct {
// Encrypt encrypts the given message to the given public key. The result is a // Encrypt encrypts the given message to the given public key. The result is a
// pair of integers. Errors can result from reading random, or because msg is // pair of integers. Errors can result from reading random, or because msg is
// too large to be encrypted to the public key. // too large to be encrypted to the public key.
func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err os.Error) { func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) {
pLen := (pub.P.BitLen() + 7) / 8 pLen := (pub.P.BitLen() + 7) / 8
if len(msg) > pLen-11 { if len(msg) > pLen-11 {
err = os.NewError("elgamal: message too long") err = errors.New("elgamal: message too long")
return return
} }
...@@ -74,7 +74,7 @@ func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err ...@@ -74,7 +74,7 @@ func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err
// be used to break the cryptosystem. See ``Chosen Ciphertext Attacks // be used to break the cryptosystem. See ``Chosen Ciphertext Attacks
// Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel // Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel
// Bleichenbacher, Advances in Cryptology (Crypto '98), // Bleichenbacher, Advances in Cryptology (Crypto '98),
func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) { func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) {
s := new(big.Int).Exp(c1, priv.X, priv.P) s := new(big.Int).Exp(c1, priv.X, priv.P)
s.ModInverse(s, priv.P) s.ModInverse(s, priv.P)
s.Mul(s, c2) s.Mul(s, c2)
...@@ -97,13 +97,13 @@ func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) { ...@@ -97,13 +97,13 @@ func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) {
} }
if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 {
return nil, os.NewError("elgamal: decryption error") return nil, errors.New("elgamal: decryption error")
} }
return em[index+1:], nil return em[index+1:], nil
} }
// nonZeroRandomBytes fills the given slice with non-zero random octets. // nonZeroRandomBytes fills the given slice with non-zero random octets.
func nonZeroRandomBytes(s []byte, rand io.Reader) (err os.Error) { func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
_, err = io.ReadFull(rand, s) _, err = io.ReadFull(rand, s)
if err != nil { if err != nil {
return return
......
...@@ -13,7 +13,7 @@ import ( ...@@ -13,7 +13,7 @@ import (
// invalid. // invalid.
type StructuralError string type StructuralError string
func (s StructuralError) String() string { func (s StructuralError) Error() string {
return "OpenPGP data invalid: " + string(s) return "OpenPGP data invalid: " + string(s)
} }
...@@ -21,7 +21,7 @@ func (s StructuralError) String() string { ...@@ -21,7 +21,7 @@ func (s StructuralError) String() string {
// makes use of currently unimplemented features. // makes use of currently unimplemented features.
type UnsupportedError string type UnsupportedError string
func (s UnsupportedError) String() string { func (s UnsupportedError) Error() string {
return "OpenPGP feature unsupported: " + string(s) return "OpenPGP feature unsupported: " + string(s)
} }
...@@ -29,7 +29,7 @@ func (s UnsupportedError) String() string { ...@@ -29,7 +29,7 @@ func (s UnsupportedError) String() string {
// incorrect value. // incorrect value.
type InvalidArgumentError string type InvalidArgumentError string
func (i InvalidArgumentError) String() string { func (i InvalidArgumentError) Error() string {
return "OpenPGP argument invalid: " + string(i) return "OpenPGP argument invalid: " + string(i)
} }
...@@ -37,13 +37,13 @@ func (i InvalidArgumentError) String() string { ...@@ -37,13 +37,13 @@ func (i InvalidArgumentError) String() string {
// validate. // validate.
type SignatureError string type SignatureError string
func (b SignatureError) String() string { func (b SignatureError) Error() string {
return "OpenPGP signature invalid: " + string(b) return "OpenPGP signature invalid: " + string(b)
} }
type keyIncorrectError int type keyIncorrectError int
func (ki keyIncorrectError) String() string { func (ki keyIncorrectError) Error() string {
return "the given key was incorrect" return "the given key was incorrect"
} }
...@@ -51,7 +51,7 @@ var KeyIncorrectError = keyIncorrectError(0) ...@@ -51,7 +51,7 @@ var KeyIncorrectError = keyIncorrectError(0)
type unknownIssuerError int type unknownIssuerError int
func (unknownIssuerError) String() string { func (unknownIssuerError) Error() string {
return "signature make by unknown entity" return "signature make by unknown entity"
} }
...@@ -59,6 +59,6 @@ var UnknownIssuerError = unknownIssuerError(0) ...@@ -59,6 +59,6 @@ var UnknownIssuerError = unknownIssuerError(0)
type UnknownPacketTypeError uint8 type UnknownPacketTypeError uint8
func (upte UnknownPacketTypeError) String() string { func (upte UnknownPacketTypeError) Error() string {
return "unknown OpenPGP packet type: " + strconv.Itoa(int(upte)) return "unknown OpenPGP packet type: " + strconv.Itoa(int(upte))
} }
...@@ -7,11 +7,10 @@ package openpgp ...@@ -7,11 +7,10 @@ package openpgp
import ( import (
"crypto" "crypto"
"crypto/openpgp/armor" "crypto/openpgp/armor"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/packet" "crypto/openpgp/packet"
"crypto/rsa" "crypto/rsa"
"io" "io"
"os"
"time" "time"
) )
...@@ -178,16 +177,16 @@ func (el EntityList) DecryptionKeys() (keys []Key) { ...@@ -178,16 +177,16 @@ func (el EntityList) DecryptionKeys() (keys []Key) {
} }
// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) { func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
block, err := armor.Decode(r) block, err := armor.Decode(r)
if err == os.EOF { if err == io.EOF {
return nil, error.InvalidArgumentError("no armored data found") return nil, error_.InvalidArgumentError("no armored data found")
} }
if err != nil { if err != nil {
return nil, err return nil, err
} }
if block.Type != PublicKeyType && block.Type != PrivateKeyType { if block.Type != PublicKeyType && block.Type != PrivateKeyType {
return nil, error.InvalidArgumentError("expected public or private key block, got: " + block.Type) return nil, error_.InvalidArgumentError("expected public or private key block, got: " + block.Type)
} }
return ReadKeyRing(block.Body) return ReadKeyRing(block.Body)
...@@ -195,19 +194,19 @@ func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) { ...@@ -195,19 +194,19 @@ func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) {
// ReadKeyRing reads one or more public/private keys. Unsupported keys are // ReadKeyRing reads one or more public/private keys. Unsupported keys are
// ignored as long as at least a single valid key is found. // ignored as long as at least a single valid key is found.
func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) { func ReadKeyRing(r io.Reader) (el EntityList, err error) {
packets := packet.NewReader(r) packets := packet.NewReader(r)
var lastUnsupportedError os.Error var lastUnsupportedError error
for { for {
var e *Entity var e *Entity
e, err = readEntity(packets) e, err = readEntity(packets)
if err != nil { if err != nil {
if _, ok := err.(error.UnsupportedError); ok { if _, ok := err.(error_.UnsupportedError); ok {
lastUnsupportedError = err lastUnsupportedError = err
err = readToNextPublicKey(packets) err = readToNextPublicKey(packets)
} }
if err == os.EOF { if err == io.EOF {
err = nil err = nil
break break
} }
...@@ -228,14 +227,14 @@ func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) { ...@@ -228,14 +227,14 @@ func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) {
// readToNextPublicKey reads packets until the start of the entity and leaves // readToNextPublicKey reads packets until the start of the entity and leaves
// the first packet of the new entity in the Reader. // the first packet of the new entity in the Reader.
func readToNextPublicKey(packets *packet.Reader) (err os.Error) { func readToNextPublicKey(packets *packet.Reader) (err error) {
var p packet.Packet var p packet.Packet
for { for {
p, err = packets.Next() p, err = packets.Next()
if err == os.EOF { if err == io.EOF {
return return
} else if err != nil { } else if err != nil {
if _, ok := err.(error.UnsupportedError); ok { if _, ok := err.(error_.UnsupportedError); ok {
err = nil err = nil
continue continue
} }
...@@ -253,7 +252,7 @@ func readToNextPublicKey(packets *packet.Reader) (err os.Error) { ...@@ -253,7 +252,7 @@ func readToNextPublicKey(packets *packet.Reader) (err os.Error) {
// readEntity reads an entity (public key, identities, subkeys etc) from the // readEntity reads an entity (public key, identities, subkeys etc) from the
// given Reader. // given Reader.
func readEntity(packets *packet.Reader) (*Entity, os.Error) { func readEntity(packets *packet.Reader) (*Entity, error) {
e := new(Entity) e := new(Entity)
e.Identities = make(map[string]*Identity) e.Identities = make(map[string]*Identity)
...@@ -266,21 +265,21 @@ func readEntity(packets *packet.Reader) (*Entity, os.Error) { ...@@ -266,21 +265,21 @@ func readEntity(packets *packet.Reader) (*Entity, os.Error) {
if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
packets.Unread(p) packets.Unread(p)
return nil, error.StructuralError("first packet was not a public/private key") return nil, error_.StructuralError("first packet was not a public/private key")
} else { } else {
e.PrimaryKey = &e.PrivateKey.PublicKey e.PrimaryKey = &e.PrivateKey.PublicKey
} }
} }
if !e.PrimaryKey.PubKeyAlgo.CanSign() { if !e.PrimaryKey.PubKeyAlgo.CanSign() {
return nil, error.StructuralError("primary key cannot be used for signatures") return nil, error_.StructuralError("primary key cannot be used for signatures")
} }
var current *Identity var current *Identity
EachPacket: EachPacket:
for { for {
p, err := packets.Next() p, err := packets.Next()
if err == os.EOF { if err == io.EOF {
break break
} else if err != nil { } else if err != nil {
return nil, err return nil, err
...@@ -295,7 +294,7 @@ EachPacket: ...@@ -295,7 +294,7 @@ EachPacket:
for { for {
p, err = packets.Next() p, err = packets.Next()
if err == os.EOF { if err == io.EOF {
return nil, io.ErrUnexpectedEOF return nil, io.ErrUnexpectedEOF
} else if err != nil { } else if err != nil {
return nil, err return nil, err
...@@ -303,12 +302,12 @@ EachPacket: ...@@ -303,12 +302,12 @@ EachPacket:
sig, ok := p.(*packet.Signature) sig, ok := p.(*packet.Signature)
if !ok { if !ok {
return nil, error.StructuralError("user ID packet not followed by self-signature") return nil, error_.StructuralError("user ID packet not followed by self-signature")
} }
if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId { if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil { if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil {
return nil, error.StructuralError("user ID self-signature invalid: " + err.String()) return nil, error_.StructuralError("user ID self-signature invalid: " + err.Error())
} }
current.SelfSignature = sig current.SelfSignature = sig
break break
...@@ -317,7 +316,7 @@ EachPacket: ...@@ -317,7 +316,7 @@ EachPacket:
} }
case *packet.Signature: case *packet.Signature:
if current == nil { if current == nil {
return nil, error.StructuralError("signature packet found before user id packet") return nil, error_.StructuralError("signature packet found before user id packet")
} }
current.Signatures = append(current.Signatures, pkt) current.Signatures = append(current.Signatures, pkt)
case *packet.PrivateKey: case *packet.PrivateKey:
...@@ -344,34 +343,34 @@ EachPacket: ...@@ -344,34 +343,34 @@ EachPacket:
} }
if len(e.Identities) == 0 { if len(e.Identities) == 0 {
return nil, error.StructuralError("entity without any identities") return nil, error_.StructuralError("entity without any identities")
} }
return e, nil return e, nil
} }
func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) os.Error { func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
var subKey Subkey var subKey Subkey
subKey.PublicKey = pub subKey.PublicKey = pub
subKey.PrivateKey = priv subKey.PrivateKey = priv
p, err := packets.Next() p, err := packets.Next()
if err == os.EOF { if err == io.EOF {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF
} }
if err != nil { if err != nil {
return error.StructuralError("subkey signature invalid: " + err.String()) return error_.StructuralError("subkey signature invalid: " + err.Error())
} }
var ok bool var ok bool
subKey.Sig, ok = p.(*packet.Signature) subKey.Sig, ok = p.(*packet.Signature)
if !ok { if !ok {
return error.StructuralError("subkey packet not followed by signature") return error_.StructuralError("subkey packet not followed by signature")
} }
if subKey.Sig.SigType != packet.SigTypeSubkeyBinding { if subKey.Sig.SigType != packet.SigTypeSubkeyBinding {
return error.StructuralError("subkey signature with wrong type") return error_.StructuralError("subkey signature with wrong type")
} }
err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig) err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
if err != nil { if err != nil {
return error.StructuralError("subkey signature invalid: " + err.String()) return error_.StructuralError("subkey signature invalid: " + err.Error())
} }
e.Subkeys = append(e.Subkeys, subKey) e.Subkeys = append(e.Subkeys, subKey)
return nil return nil
...@@ -382,10 +381,10 @@ const defaultRSAKeyBits = 2048 ...@@ -382,10 +381,10 @@ const defaultRSAKeyBits = 2048
// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of // single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00". // which may be empty but must not contain any of "()<>\x00".
func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, os.Error) { func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, error) {
uid := packet.NewUserId(name, comment, email) uid := packet.NewUserId(name, comment, email)
if uid == nil { if uid == nil {
return nil, error.InvalidArgumentError("user id field contained invalid characters") return nil, error_.InvalidArgumentError("user id field contained invalid characters")
} }
signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits) signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
if err != nil { if err != nil {
...@@ -442,7 +441,7 @@ func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email strin ...@@ -442,7 +441,7 @@ func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email strin
// SerializePrivate serializes an Entity, including private key material, to // SerializePrivate serializes an Entity, including private key material, to
// the given Writer. For now, it must only be used on an Entity returned from // the given Writer. For now, it must only be used on an Entity returned from
// NewEntity. // NewEntity.
func (e *Entity) SerializePrivate(w io.Writer) (err os.Error) { func (e *Entity) SerializePrivate(w io.Writer) (err error) {
err = e.PrivateKey.Serialize(w) err = e.PrivateKey.Serialize(w)
if err != nil { if err != nil {
return return
...@@ -480,7 +479,7 @@ func (e *Entity) SerializePrivate(w io.Writer) (err os.Error) { ...@@ -480,7 +479,7 @@ func (e *Entity) SerializePrivate(w io.Writer) (err os.Error) {
// Serialize writes the public part of the given Entity to w. (No private // Serialize writes the public part of the given Entity to w. (No private
// key material will be output). // key material will be output).
func (e *Entity) Serialize(w io.Writer) os.Error { func (e *Entity) Serialize(w io.Writer) error {
err := e.PrimaryKey.Serialize(w) err := e.PrimaryKey.Serialize(w)
if err != nil { if err != nil {
return err return err
...@@ -518,16 +517,16 @@ func (e *Entity) Serialize(w io.Writer) os.Error { ...@@ -518,16 +517,16 @@ func (e *Entity) Serialize(w io.Writer) os.Error {
// associated with e. The provided identity must already be an element of // associated with e. The provided identity must already be an element of
// e.Identities and the private key of signer must have been decrypted if // e.Identities and the private key of signer must have been decrypted if
// necessary. // necessary.
func (e *Entity) SignIdentity(identity string, signer *Entity) os.Error { func (e *Entity) SignIdentity(identity string, signer *Entity) error {
if signer.PrivateKey == nil { if signer.PrivateKey == nil {
return error.InvalidArgumentError("signing Entity must have a private key") return error_.InvalidArgumentError("signing Entity must have a private key")
} }
if signer.PrivateKey.Encrypted { if signer.PrivateKey.Encrypted {
return error.InvalidArgumentError("signing Entity's private key must be decrypted") return error_.InvalidArgumentError("signing Entity's private key must be decrypted")
} }
ident, ok := e.Identities[identity] ident, ok := e.Identities[identity]
if !ok { if !ok {
return error.InvalidArgumentError("given identity string not found in Entity") return error_.InvalidArgumentError("given identity string not found in Entity")
} }
sig := &packet.Signature{ sig := &packet.Signature{
......
...@@ -7,9 +7,8 @@ package packet ...@@ -7,9 +7,8 @@ package packet
import ( import (
"compress/flate" "compress/flate"
"compress/zlib" "compress/zlib"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"io" "io"
"os"
"strconv" "strconv"
) )
...@@ -19,7 +18,7 @@ type Compressed struct { ...@@ -19,7 +18,7 @@ type Compressed struct {
Body io.Reader Body io.Reader
} }
func (c *Compressed) parse(r io.Reader) os.Error { func (c *Compressed) parse(r io.Reader) error {
var buf [1]byte var buf [1]byte
_, err := readFull(r, buf[:]) _, err := readFull(r, buf[:])
if err != nil { if err != nil {
...@@ -32,7 +31,7 @@ func (c *Compressed) parse(r io.Reader) os.Error { ...@@ -32,7 +31,7 @@ func (c *Compressed) parse(r io.Reader) os.Error {
case 2: case 2:
c.Body, err = zlib.NewReader(r) c.Body, err = zlib.NewReader(r)
default: default:
err = error.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) err = error_.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0])))
} }
return err return err
......
...@@ -7,7 +7,7 @@ package packet ...@@ -7,7 +7,7 @@ package packet
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"os" "io"
"io/ioutil" "io/ioutil"
"testing" "testing"
) )
...@@ -26,7 +26,7 @@ func TestCompressed(t *testing.T) { ...@@ -26,7 +26,7 @@ func TestCompressed(t *testing.T) {
} }
contents, err := ioutil.ReadAll(c.Body) contents, err := ioutil.ReadAll(c.Body)
if err != nil && err != os.EOF { if err != nil && err != io.EOF {
t.Error(err) t.Error(err)
return return
} }
......
...@@ -7,12 +7,11 @@ package packet ...@@ -7,12 +7,11 @@ package packet
import ( import (
"big" "big"
"crypto/openpgp/elgamal" "crypto/openpgp/elgamal"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"encoding/binary" "encoding/binary"
"io" "io"
"os"
"strconv" "strconv"
) )
...@@ -29,14 +28,14 @@ type EncryptedKey struct { ...@@ -29,14 +28,14 @@ type EncryptedKey struct {
encryptedMPI1, encryptedMPI2 []byte encryptedMPI1, encryptedMPI2 []byte
} }
func (e *EncryptedKey) parse(r io.Reader) (err os.Error) { func (e *EncryptedKey) parse(r io.Reader) (err error) {
var buf [10]byte var buf [10]byte
_, err = readFull(r, buf[:]) _, err = readFull(r, buf[:])
if err != nil { if err != nil {
return return
} }
if buf[0] != encryptedKeyVersion { if buf[0] != encryptedKeyVersion {
return error.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0]))) return error_.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0])))
} }
e.KeyId = binary.BigEndian.Uint64(buf[1:9]) e.KeyId = binary.BigEndian.Uint64(buf[1:9])
e.Algo = PublicKeyAlgorithm(buf[9]) e.Algo = PublicKeyAlgorithm(buf[9])
...@@ -64,8 +63,8 @@ func checksumKeyMaterial(key []byte) uint16 { ...@@ -64,8 +63,8 @@ func checksumKeyMaterial(key []byte) uint16 {
// Decrypt decrypts an encrypted session key with the given private key. The // Decrypt decrypts an encrypted session key with the given private key. The
// private key must have been decrypted first. // private key must have been decrypted first.
func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error { func (e *EncryptedKey) Decrypt(priv *PrivateKey) error {
var err os.Error var err error
var b []byte var b []byte
// TODO(agl): use session key decryption routines here to avoid // TODO(agl): use session key decryption routines here to avoid
...@@ -78,7 +77,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error { ...@@ -78,7 +77,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
c2 := new(big.Int).SetBytes(e.encryptedMPI2) c2 := new(big.Int).SetBytes(e.encryptedMPI2)
b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2) b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
default: default:
err = error.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) err = error_.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
} }
if err != nil { if err != nil {
...@@ -90,7 +89,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error { ...@@ -90,7 +89,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1]) expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
checksum := checksumKeyMaterial(e.Key) checksum := checksumKeyMaterial(e.Key)
if checksum != expectedChecksum { if checksum != expectedChecksum {
return error.StructuralError("EncryptedKey checksum incorrect") return error_.StructuralError("EncryptedKey checksum incorrect")
} }
return nil return nil
...@@ -98,7 +97,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error { ...@@ -98,7 +97,7 @@ func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
// SerializeEncryptedKey serializes an encrypted key packet to w that contains // SerializeEncryptedKey serializes an encrypted key packet to w that contains
// key, encrypted to pub. // key, encrypted to pub.
func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFunc CipherFunction, key []byte) os.Error { func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFunc CipherFunction, key []byte) error {
var buf [10]byte var buf [10]byte
buf[0] = encryptedKeyVersion buf[0] = encryptedKeyVersion
binary.BigEndian.PutUint64(buf[1:9], pub.KeyId) binary.BigEndian.PutUint64(buf[1:9], pub.KeyId)
...@@ -117,16 +116,16 @@ func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFu ...@@ -117,16 +116,16 @@ func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFu
case PubKeyAlgoElGamal: case PubKeyAlgoElGamal:
return serializeEncryptedKeyElGamal(w, rand, buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock) return serializeEncryptedKeyElGamal(w, rand, buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock)
case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly: case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly:
return error.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) return error_.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
} }
return error.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) return error_.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
} }
func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) os.Error { func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error {
cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock) cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock)
if err != nil { if err != nil {
return error.InvalidArgumentError("RSA encryption failed: " + err.String()) return error_.InvalidArgumentError("RSA encryption failed: " + err.Error())
} }
packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText) packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText)
...@@ -142,10 +141,10 @@ func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub ...@@ -142,10 +141,10 @@ func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub
return writeMPI(w, 8*uint16(len(cipherText)), cipherText) return writeMPI(w, 8*uint16(len(cipherText)), cipherText)
} }
func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) os.Error { func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error {
c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock) c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock)
if err != nil { if err != nil {
return error.InvalidArgumentError("ElGamal encryption failed: " + err.String()) return error_.InvalidArgumentError("ElGamal encryption failed: " + err.Error())
} }
packetLen := 10 /* header length */ packetLen := 10 /* header length */
......
...@@ -7,7 +7,6 @@ package packet ...@@ -7,7 +7,6 @@ package packet
import ( import (
"encoding/binary" "encoding/binary"
"io" "io"
"os"
) )
// LiteralData represents an encrypted file. See RFC 4880, section 5.9. // LiteralData represents an encrypted file. See RFC 4880, section 5.9.
...@@ -24,7 +23,7 @@ func (l *LiteralData) ForEyesOnly() bool { ...@@ -24,7 +23,7 @@ func (l *LiteralData) ForEyesOnly() bool {
return l.FileName == "_CONSOLE" return l.FileName == "_CONSOLE"
} }
func (l *LiteralData) parse(r io.Reader) (err os.Error) { func (l *LiteralData) parse(r io.Reader) (err error) {
var buf [256]byte var buf [256]byte
_, err = readFull(r, buf[:2]) _, err = readFull(r, buf[:2])
...@@ -55,7 +54,7 @@ func (l *LiteralData) parse(r io.Reader) (err os.Error) { ...@@ -55,7 +54,7 @@ func (l *LiteralData) parse(r io.Reader) (err os.Error) {
// SerializeLiteral serializes a literal data packet to w and returns a // SerializeLiteral serializes a literal data packet to w and returns a
// WriteCloser to which the data itself can be written and which MUST be closed // WriteCloser to which the data itself can be written and which MUST be closed
// on completion. The fileName is truncated to 255 bytes. // on completion. The fileName is truncated to 255 bytes.
func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err os.Error) { func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) {
var buf [4]byte var buf [4]byte
buf[0] = 't' buf[0] = 't'
if isBinary { if isBinary {
......
...@@ -6,11 +6,10 @@ package packet ...@@ -6,11 +6,10 @@ package packet
import ( import (
"crypto" "crypto"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"encoding/binary" "encoding/binary"
"io" "io"
"os"
"strconv" "strconv"
) )
...@@ -26,7 +25,7 @@ type OnePassSignature struct { ...@@ -26,7 +25,7 @@ type OnePassSignature struct {
const onePassSignatureVersion = 3 const onePassSignatureVersion = 3
func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) { func (ops *OnePassSignature) parse(r io.Reader) (err error) {
var buf [13]byte var buf [13]byte
_, err = readFull(r, buf[:]) _, err = readFull(r, buf[:])
...@@ -34,13 +33,13 @@ func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) { ...@@ -34,13 +33,13 @@ func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) {
return return
} }
if buf[0] != onePassSignatureVersion { if buf[0] != onePassSignatureVersion {
err = error.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) err = error_.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0])))
} }
var ok bool var ok bool
ops.Hash, ok = s2k.HashIdToHash(buf[2]) ops.Hash, ok = s2k.HashIdToHash(buf[2])
if !ok { if !ok {
return error.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) return error_.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2])))
} }
ops.SigType = SignatureType(buf[1]) ops.SigType = SignatureType(buf[1])
...@@ -51,14 +50,14 @@ func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) { ...@@ -51,14 +50,14 @@ func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) {
} }
// Serialize marshals the given OnePassSignature to w. // Serialize marshals the given OnePassSignature to w.
func (ops *OnePassSignature) Serialize(w io.Writer) os.Error { func (ops *OnePassSignature) Serialize(w io.Writer) error {
var buf [13]byte var buf [13]byte
buf[0] = onePassSignatureVersion buf[0] = onePassSignatureVersion
buf[1] = uint8(ops.SigType) buf[1] = uint8(ops.SigType)
var ok bool var ok bool
buf[2], ok = s2k.HashToHashId(ops.Hash) buf[2], ok = s2k.HashToHashId(ops.Hash)
if !ok { if !ok {
return error.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) return error_.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash)))
} }
buf[3] = uint8(ops.PubKeyAlgo) buf[3] = uint8(ops.PubKeyAlgo)
binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) binary.BigEndian.PutUint64(buf[4:12], ops.KeyId)
......
...@@ -11,23 +11,22 @@ import ( ...@@ -11,23 +11,22 @@ import (
"crypto/aes" "crypto/aes"
"crypto/cast5" "crypto/cast5"
"crypto/cipher" "crypto/cipher"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"io" "io"
"os"
) )
// readFull is the same as io.ReadFull except that reading zero bytes returns // readFull is the same as io.ReadFull except that reading zero bytes returns
// ErrUnexpectedEOF rather than EOF. // ErrUnexpectedEOF rather than EOF.
func readFull(r io.Reader, buf []byte) (n int, err os.Error) { func readFull(r io.Reader, buf []byte) (n int, err error) {
n, err = io.ReadFull(r, buf) n, err = io.ReadFull(r, buf)
if err == os.EOF { if err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return return
} }
// readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2. // readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2.
func readLength(r io.Reader) (length int64, isPartial bool, err os.Error) { func readLength(r io.Reader) (length int64, isPartial bool, err error) {
var buf [4]byte var buf [4]byte
_, err = readFull(r, buf[:1]) _, err = readFull(r, buf[:1])
if err != nil { if err != nil {
...@@ -68,10 +67,10 @@ type partialLengthReader struct { ...@@ -68,10 +67,10 @@ type partialLengthReader struct {
isPartial bool isPartial bool
} }
func (r *partialLengthReader) Read(p []byte) (n int, err os.Error) { func (r *partialLengthReader) Read(p []byte) (n int, err error) {
for r.remaining == 0 { for r.remaining == 0 {
if !r.isPartial { if !r.isPartial {
return 0, os.EOF return 0, io.EOF
} }
r.remaining, r.isPartial, err = readLength(r.r) r.remaining, r.isPartial, err = readLength(r.r)
if err != nil { if err != nil {
...@@ -86,7 +85,7 @@ func (r *partialLengthReader) Read(p []byte) (n int, err os.Error) { ...@@ -86,7 +85,7 @@ func (r *partialLengthReader) Read(p []byte) (n int, err os.Error) {
n, err = r.r.Read(p[:int(toRead)]) n, err = r.r.Read(p[:int(toRead)])
r.remaining -= int64(n) r.remaining -= int64(n)
if n < int(toRead) && err == os.EOF { if n < int(toRead) && err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return return
...@@ -99,7 +98,7 @@ type partialLengthWriter struct { ...@@ -99,7 +98,7 @@ type partialLengthWriter struct {
lengthByte [1]byte lengthByte [1]byte
} }
func (w *partialLengthWriter) Write(p []byte) (n int, err os.Error) { func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
for len(p) > 0 { for len(p) > 0 {
for power := uint(14); power < 32; power-- { for power := uint(14); power < 32; power-- {
l := 1 << power l := 1 << power
...@@ -123,7 +122,7 @@ func (w *partialLengthWriter) Write(p []byte) (n int, err os.Error) { ...@@ -123,7 +122,7 @@ func (w *partialLengthWriter) Write(p []byte) (n int, err os.Error) {
return return
} }
func (w *partialLengthWriter) Close() os.Error { func (w *partialLengthWriter) Close() error {
w.lengthByte[0] = 0 w.lengthByte[0] = 0
_, err := w.w.Write(w.lengthByte[:]) _, err := w.w.Write(w.lengthByte[:])
if err != nil { if err != nil {
...@@ -139,16 +138,16 @@ type spanReader struct { ...@@ -139,16 +138,16 @@ type spanReader struct {
n int64 n int64
} }
func (l *spanReader) Read(p []byte) (n int, err os.Error) { func (l *spanReader) Read(p []byte) (n int, err error) {
if l.n <= 0 { if l.n <= 0 {
return 0, os.EOF return 0, io.EOF
} }
if int64(len(p)) > l.n { if int64(len(p)) > l.n {
p = p[0:l.n] p = p[0:l.n]
} }
n, err = l.r.Read(p) n, err = l.r.Read(p)
l.n -= int64(n) l.n -= int64(n)
if l.n > 0 && err == os.EOF { if l.n > 0 && err == io.EOF {
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return return
...@@ -156,14 +155,14 @@ func (l *spanReader) Read(p []byte) (n int, err os.Error) { ...@@ -156,14 +155,14 @@ func (l *spanReader) Read(p []byte) (n int, err os.Error) {
// readHeader parses a packet header and returns an io.Reader which will return // readHeader parses a packet header and returns an io.Reader which will return
// the contents of the packet. See RFC 4880, section 4.2. // the contents of the packet. See RFC 4880, section 4.2.
func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err os.Error) { func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
var buf [4]byte var buf [4]byte
_, err = io.ReadFull(r, buf[:1]) _, err = io.ReadFull(r, buf[:1])
if err != nil { if err != nil {
return return
} }
if buf[0]&0x80 == 0 { if buf[0]&0x80 == 0 {
err = error.StructuralError("tag byte does not have MSB set") err = error_.StructuralError("tag byte does not have MSB set")
return return
} }
if buf[0]&0x40 == 0 { if buf[0]&0x40 == 0 {
...@@ -209,7 +208,7 @@ func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, ...@@ -209,7 +208,7 @@ func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader,
// serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section // serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section
// 4.2. // 4.2.
func serializeHeader(w io.Writer, ptype packetType, length int) (err os.Error) { func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
var buf [6]byte var buf [6]byte
var n int var n int
...@@ -238,7 +237,7 @@ func serializeHeader(w io.Writer, ptype packetType, length int) (err os.Error) { ...@@ -238,7 +237,7 @@ func serializeHeader(w io.Writer, ptype packetType, length int) (err os.Error) {
// serializeStreamHeader writes an OpenPGP packet header to w where the // serializeStreamHeader writes an OpenPGP packet header to w where the
// length of the packet is unknown. It returns a io.WriteCloser which can be // length of the packet is unknown. It returns a io.WriteCloser which can be
// used to write the contents of the packet. See RFC 4880, section 4.2. // used to write the contents of the packet. See RFC 4880, section 4.2.
func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err os.Error) { func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
var buf [1]byte var buf [1]byte
buf[0] = 0x80 | 0x40 | byte(ptype) buf[0] = 0x80 | 0x40 | byte(ptype)
_, err = w.Write(buf[:]) _, err = w.Write(buf[:])
...@@ -252,19 +251,19 @@ func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteClos ...@@ -252,19 +251,19 @@ func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteClos
// Packet represents an OpenPGP packet. Users are expected to try casting // Packet represents an OpenPGP packet. Users are expected to try casting
// instances of this interface to specific packet types. // instances of this interface to specific packet types.
type Packet interface { type Packet interface {
parse(io.Reader) os.Error parse(io.Reader) error
} }
// consumeAll reads from the given Reader until error, returning the number of // consumeAll reads from the given Reader until error, returning the number of
// bytes read. // bytes read.
func consumeAll(r io.Reader) (n int64, err os.Error) { func consumeAll(r io.Reader) (n int64, err error) {
var m int var m int
var buf [1024]byte var buf [1024]byte
for { for {
m, err = r.Read(buf[:]) m, err = r.Read(buf[:])
n += int64(m) n += int64(m)
if err == os.EOF { if err == io.EOF {
err = nil err = nil
return return
} }
...@@ -298,7 +297,7 @@ const ( ...@@ -298,7 +297,7 @@ const (
// Read reads a single OpenPGP packet from the given io.Reader. If there is an // Read reads a single OpenPGP packet from the given io.Reader. If there is an
// error parsing a packet, the whole packet is consumed from the input. // error parsing a packet, the whole packet is consumed from the input.
func Read(r io.Reader) (p Packet, err os.Error) { func Read(r io.Reader) (p Packet, err error) {
tag, _, contents, err := readHeader(r) tag, _, contents, err := readHeader(r)
if err != nil { if err != nil {
return return
...@@ -338,7 +337,7 @@ func Read(r io.Reader) (p Packet, err os.Error) { ...@@ -338,7 +337,7 @@ func Read(r io.Reader) (p Packet, err os.Error) {
se.MDC = true se.MDC = true
p = se p = se
default: default:
err = error.UnknownPacketTypeError(tag) err = error_.UnknownPacketTypeError(tag)
} }
if p != nil { if p != nil {
err = p.parse(contents) err = p.parse(contents)
...@@ -447,7 +446,7 @@ func (cipher CipherFunction) new(key []byte) (block cipher.Block) { ...@@ -447,7 +446,7 @@ func (cipher CipherFunction) new(key []byte) (block cipher.Block) {
// readMPI reads a big integer from r. The bit length returned is the bit // readMPI reads a big integer from r. The bit length returned is the bit
// length that was specified in r. This is preserved so that the integer can be // length that was specified in r. This is preserved so that the integer can be
// reserialized exactly. // reserialized exactly.
func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err os.Error) { func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
var buf [2]byte var buf [2]byte
_, err = readFull(r, buf[0:]) _, err = readFull(r, buf[0:])
if err != nil { if err != nil {
...@@ -469,7 +468,7 @@ func mpiLength(n *big.Int) (mpiLengthInBytes int) { ...@@ -469,7 +468,7 @@ func mpiLength(n *big.Int) (mpiLengthInBytes int) {
} }
// writeMPI serializes a big integer to w. // writeMPI serializes a big integer to w.
func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err os.Error) { func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
_, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)}) _, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
if err == nil { if err == nil {
_, err = w.Write(mpiBytes) _, err = w.Write(mpiBytes)
...@@ -478,6 +477,6 @@ func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err os.Error) { ...@@ -478,6 +477,6 @@ func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err os.Error) {
} }
// writeBig serializes a *big.Int to w. // writeBig serializes a *big.Int to w.
func writeBig(w io.Writer, i *big.Int) os.Error { func writeBig(w io.Writer, i *big.Int) error {
return writeMPI(w, uint16(i.BitLen()), i.Bytes()) return writeMPI(w, uint16(i.BitLen()), i.Bytes())
} }
...@@ -6,12 +6,11 @@ package packet ...@@ -6,12 +6,11 @@ package packet
import ( import (
"bytes" "bytes"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"testing" "testing"
) )
...@@ -49,7 +48,7 @@ var readLengthTests = []struct { ...@@ -49,7 +48,7 @@ var readLengthTests = []struct {
hexInput string hexInput string
length int64 length int64
isPartial bool isPartial bool
err os.Error err error
}{ }{
{"", 0, false, io.ErrUnexpectedEOF}, {"", 0, false, io.ErrUnexpectedEOF},
{"1f", 31, false, nil}, {"1f", 31, false, nil},
...@@ -87,7 +86,7 @@ func TestReadLength(t *testing.T) { ...@@ -87,7 +86,7 @@ func TestReadLength(t *testing.T) {
var partialLengthReaderTests = []struct { var partialLengthReaderTests = []struct {
hexInput string hexInput string
err os.Error err error
hexOutput string hexOutput string
}{ }{
{"e0", io.ErrUnexpectedEOF, ""}, {"e0", io.ErrUnexpectedEOF, ""},
...@@ -153,14 +152,14 @@ func TestReadHeader(t *testing.T) { ...@@ -153,14 +152,14 @@ func TestReadHeader(t *testing.T) {
for i, test := range readHeaderTests { for i, test := range readHeaderTests {
tag, length, contents, err := readHeader(readerFromHex(test.hexInput)) tag, length, contents, err := readHeader(readerFromHex(test.hexInput))
if test.structuralError { if test.structuralError {
if _, ok := err.(error.StructuralError); ok { if _, ok := err.(error_.StructuralError); ok {
continue continue
} }
t.Errorf("%d: expected StructuralError, got:%s", i, err) t.Errorf("%d: expected StructuralError, got:%s", i, err)
continue continue
} }
if err != nil { if err != nil {
if len(test.hexInput) == 0 && err == os.EOF { if len(test.hexInput) == 0 && err == io.EOF {
continue continue
} }
if !test.unexpectedEOF || err != io.ErrUnexpectedEOF { if !test.unexpectedEOF || err != io.ErrUnexpectedEOF {
......
...@@ -10,13 +10,12 @@ import ( ...@@ -10,13 +10,12 @@ import (
"crypto/cipher" "crypto/cipher"
"crypto/dsa" "crypto/dsa"
"crypto/openpgp/elgamal" "crypto/openpgp/elgamal"
"crypto/openpgp/error" error_ "crypto/openpgp/error"
"crypto/openpgp/s2k" "crypto/openpgp/s2k"
"crypto/rsa" "crypto/rsa"
"crypto/sha1" "crypto/sha1"
"io" "io"
"io/ioutil" "io/ioutil"
"os"
"strconv" "strconv"
) )
...@@ -40,7 +39,7 @@ func NewRSAPrivateKey(currentTimeSecs uint32, priv *rsa.PrivateKey, isSubkey boo ...@@ -40,7 +39,7 @@ func NewRSAPrivateKey(currentTimeSecs uint32, priv *rsa.PrivateKey, isSubkey boo
return pk return pk
} }
func (pk *PrivateKey) parse(r io.Reader) (err os.Error) { func (pk *PrivateKey) parse(r io.Reader) (err error) {
err = (&pk.PublicKey).parse(r) err = (&pk.PublicKey).parse(r)
if err != nil { if err != nil {
return return
...@@ -72,13 +71,13 @@ func (pk *PrivateKey) parse(r io.Reader) (err os.Error) { ...@@ -72,13 +71,13 @@ func (pk *PrivateKey) parse(r io.Reader) (err os.Error) {
pk.sha1Checksum = true pk.sha1Checksum = true
} }
default: default:
return error.UnsupportedError("deprecated s2k function in private key") return error_.UnsupportedError("deprecated s2k function in private key")
} }
if pk.Encrypted { if pk.Encrypted {
blockSize := pk.cipher.blockSize() blockSize := pk.cipher.blockSize()
if blockSize == 0 { if blockSize == 0 {
return error.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher))) return error_.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
} }
pk.iv = make([]byte, blockSize) pk.iv = make([]byte, blockSize)
_, err = readFull(r, pk.iv) _, err = readFull(r, pk.iv)
...@@ -111,7 +110,7 @@ func mod64kHash(d []byte) uint16 { ...@@ -111,7 +110,7 @@ func mod64kHash(d []byte) uint16 {
return h return h
} }
func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) { func (pk *PrivateKey) Serialize(w io.Writer) (err error) {
// TODO(agl): support encrypted private keys // TODO(agl): support encrypted private keys
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
err = pk.PublicKey.serializeWithoutHeaders(buf) err = pk.PublicKey.serializeWithoutHeaders(buf)
...@@ -126,7 +125,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) { ...@@ -126,7 +125,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) {
case *rsa.PrivateKey: case *rsa.PrivateKey:
err = serializeRSAPrivateKey(privateKeyBuf, priv) err = serializeRSAPrivateKey(privateKeyBuf, priv)
default: default:
err = error.InvalidArgumentError("non-RSA private key") err = error_.InvalidArgumentError("non-RSA private key")
} }
if err != nil { if err != nil {
return return
...@@ -160,7 +159,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) { ...@@ -160,7 +159,7 @@ func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) {
return return
} }
func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) os.Error { func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error {
err := writeBig(w, priv.D) err := writeBig(w, priv.D)
if err != nil { if err != nil {
return err return err
...@@ -177,7 +176,7 @@ func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) os.Error { ...@@ -177,7 +176,7 @@ func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) os.Error {
} }
// Decrypt decrypts an encrypted private key using a passphrase. // Decrypt decrypts an encrypted private key using a passphrase.
func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error { func (pk *PrivateKey) Decrypt(passphrase []byte) error {
if !pk.Encrypted { if !pk.Encrypted {
return nil return nil
} }
...@@ -192,18 +191,18 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error { ...@@ -192,18 +191,18 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
if pk.sha1Checksum { if pk.sha1Checksum {
if len(data) < sha1.Size { if len(data) < sha1.Size {
return error.StructuralError("truncated private key data") return error_.StructuralError("truncated private key data")
} }
h := sha1.New() h := sha1.New()
h.Write(data[:len(data)-sha1.Size]) h.Write(data[:len(data)-sha1.Size])
sum := h.Sum() sum := h.Sum()
if !bytes.Equal(sum, data[len(data)-sha1.Size:]) { if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
return error.StructuralError("private key checksum failure") return error_.StructuralError("private key checksum failure")
} }
data = data[:len(data)-sha1.Size] data = data[:len(data)-sha1.Size]
} else { } else {
if len(data) < 2 { if len(data) < 2 {
return error.StructuralError("truncated private key data") return error_.StructuralError("truncated private key data")
} }
var sum uint16 var sum uint16
for i := 0; i < len(data)-2; i++ { for i := 0; i < len(data)-2; i++ {
...@@ -211,7 +210,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error { ...@@ -211,7 +210,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
} }
if data[len(data)-2] != uint8(sum>>8) || if data[len(data)-2] != uint8(sum>>8) ||
data[len(data)-1] != uint8(sum) { data[len(data)-1] != uint8(sum) {
return error.StructuralError("private key checksum failure") return error_.StructuralError("private key checksum failure")
} }
data = data[:len(data)-2] data = data[:len(data)-2]
} }
...@@ -219,7 +218,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error { ...@@ -219,7 +218,7 @@ func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
return pk.parsePrivateKey(data) return pk.parsePrivateKey(data)
} }
func (pk *PrivateKey) parsePrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) {
switch pk.PublicKey.PubKeyAlgo { switch pk.PublicKey.PubKeyAlgo {
case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly: case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly:
return pk.parseRSAPrivateKey(data) return pk.parseRSAPrivateKey(data)
...@@ -231,7 +230,7 @@ func (pk *PrivateKey) parsePrivateKey(data []byte) (err os.Error) { ...@@ -231,7 +230,7 @@ func (pk *PrivateKey) parsePrivateKey(data []byte) (err os.Error) {
panic("impossible") panic("impossible")
} }
func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) {
rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
rsaPriv := new(rsa.PrivateKey) rsaPriv := new(rsa.PrivateKey)
rsaPriv.PublicKey = *rsaPub rsaPriv.PublicKey = *rsaPub
...@@ -262,7 +261,7 @@ func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) { ...@@ -262,7 +261,7 @@ func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) {
return nil return nil
} }
func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) {
dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey) dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey)
dsaPriv := new(dsa.PrivateKey) dsaPriv := new(dsa.PrivateKey)
dsaPriv.PublicKey = *dsaPub dsaPriv.PublicKey = *dsaPub
...@@ -281,7 +280,7 @@ func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err os.Error) { ...@@ -281,7 +280,7 @@ func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err os.Error) {
return nil return nil
} }
func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err os.Error) { func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) {
pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey) pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey)
priv := new(elgamal.PrivateKey) priv := new(elgamal.PrivateKey)
priv.PublicKey = *pub priv.PublicKey = *pub
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment