func main() {
var n = 10000
if len(os.Args) > 1 {
- var err os.Error
+ var err error
n, err = strconv.Atoi(os.Args[1])
if err != nil {
print("bad arg\n")
func main() {
ga, e0 := os.Getenverror("GOARCH")
if e0 != nil {
- print("$GOARCH: ", e0.String(), "\n")
+ print("$GOARCH: ", e0.Error(), "\n")
os.Exit(1)
}
if ga != runtime.GOARCH {
}
xxx, e1 := os.Getenverror("DOES_NOT_EXIST")
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)
}
}
package main
import os "os"
-type _ os.Error
+type _ os.FileInfo
func f() (os int) {
// In the next line "os" should refer to the result variable, not
// to the package.
package main
-import "os"
+import "errors"
// Issue 481: closures and var declarations
// with multiple variables assigned from one
}
}()
- var conn, _ = Dial("tcp", "", listen.Addr().String())
+ var conn, _ = Dial("tcp", "", listen.Addr().Error())
_ = conn
}
return global, y
}
-func (t T) Addr() os.Error {
- return os.NewError("stringer")
+func (t T) Addr() error {
+ return errors.New("stringer")
}
func (t T) Accept() (int, string) {
return "abc"
}
-func g() *os.Error {
+func g() *error {
trace += "g"
- var x os.Error
+ var x error
return &x
}
return &i
}
-
func main() {
m := make(map[string]int)
m[f()], *g() = strconv.Atoi(h())
println("BUG", m["abc"], trace)
panic("fail")
}
- mm := make(map[string]os.Error)
+ mm := make(map[string]error)
trace = ""
mm["abc"] = os.EINVAL
*i(), mm[f()] = strconv.Atoi(h())
package p
-import "os"
-
-func f() (_ int, err os.Error) {
+func f() (_ int, err error) {
return
}
-func g() (x int, _ os.Error) {
+func g() (x int, _ error) {
return
}
-func h() (_ int, _ os.Error) {
+func h() (_ int, _ error) {
return
}
-func i() (int, os.Error) {
- return // ERROR "not enough arguments to return"
+func i() (int, error) {
+ return // ERROR "not enough arguments to return"
}
-func f1() (_ int, err os.Error) {
+func f1() (_ int, err error) {
return 1, nil
}
-func g1() (x int, _ os.Error) {
+func g1() (x int, _ error) {
return 1, nil
}
-func h1() (_ int, _ os.Error) {
+func h1() (_ int, _ error) {
return 1, nil
}
-func ii() (int, os.Error) {
+func ii() (int, error) {
return 1, nil
}
package main
-import "os"
+import "io"
-func f() (_ string, x float64, err os.Error) {
+func f() (_ string, x float64, err error) {
return
}
-func g() (_ string, x float64, err os.Error) {
- return "hello", 3.14, os.EOF
+func g() (_ string, x float64, err error) {
+ return "hello", 3.14, io.EOF
}
-var _ func() (string, float64, os.Error) = f
-var _ func() (string, float64, os.Error) = g
+var _ func() (string, float64, error) = f
+var _ func() (string, float64, error) = g
func main() {
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)
}
}
package main
-import (
- "os"
-)
-
type Inner struct {
- F func() os.Error
+ F func() error
}
type Outer struct {
// 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 }}}}
// license that can be found in the LICENSE file.
package main
-import os "os"
type t1 int
type t2 int
func f9(os int) int {
return os
}
-func f10(err os.Error) os.Error {
+func f10(err error) error {
return err
}
func f11(t1 string) string {
import "os"
import . "os"
-func f(e os.Error)
+func f(e *os.File)
func main() {
- var _e_ _os_.Error
- var dot Error
+ var _e_ *_os_.File
+ var dot *File
f(_e_)
f(dot)
}
-
package main
-import (
- "os"
- "strings"
-)
+import "strings"
var x = make([]byte, 10)
if v == nil {
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)
}
}
println(name, "panicked but not with runtime.Error")
return
}
- s := runt.String()
+ s := runt.Error()
if strings.Index(s, err) < 0 {
bug()
println(name, "panicked with", s, "not", err)
-941b8015061a
+780c85032b17
The first line of this file holds the Mercurial revision number of the
last merge done from the master library sources.
cmath.gox \
crypto.gox \
csv.gox \
+ errors.gox \
exec.gox \
expvar.gox \
flag.gox \
go/csv/reader.go \
go/csv/writer.go
+go_errors_files = \
+ go/errors/errors.go
+
go_exec_files = \
go/exec/exec.go \
go/exec/lp_unix.go
cmath/cmath.lo \
crypto/crypto.lo \
csv/csv.lo \
+ errors/errors.lo \
exec/exec.lo \
expvar/expvar.lo \
flag/flag.lo \
@$(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
exec/exec.lo.dep: $(go_exec_files)
$(BUILDDEPS)
$(BUILDGOX)
csv.gox: csv/csv.lo
$(BUILDGOX)
+errors.gox: errors/errors.lo
+ $(BUILDGOX)
exec.gox: exec/exec.lo
$(BUILDGOX)
expvar.gox: expvar/expvar.lo
bytes/check \
cmath/check \
csv/check \
+ errors/check \
exec/check \
expvar/check \
flag/check \
am__DEPENDENCIES_1 =
am__DEPENDENCIES_2 = asn1/asn1.lo big/big.lo bufio/bufio.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 \
- fmt/fmt.lo gob/gob.lo hash/hash.lo html/html.lo http/http.lo \
- image/image.lo io/io.lo json/json.lo log/log.lo math/math.lo \
- mail/mail.lo mime/mime.lo net/net.lo os/os.lo patch/patch.lo \
- path/path.lo rand/rand.lo reflect/reflect.lo regexp/regexp.lo \
- rpc/rpc.lo runtime/runtime.lo scanner/scanner.lo smtp/smtp.lo \
- sort/sort.lo strconv/strconv.lo strings/strings.lo \
- sync/sync.lo syslog/syslog.lo syslog/syslog_c.lo \
- tabwriter/tabwriter.lo template/template.lo time/time.lo \
- unicode/unicode.lo url/url.lo utf16/utf16.lo utf8/utf8.lo \
- websocket/websocket.lo xml/xml.lo archive/tar.lo \
- archive/zip.lo compress/bzip2.lo compress/flate.lo \
- compress/gzip.lo compress/lzw.lo compress/zlib.lo \
- container/heap.lo container/list.lo container/ring.lo \
- crypto/aes.lo crypto/bcrypt.lo crypto/blowfish.lo \
- crypto/cast5.lo crypto/cipher.lo crypto/des.lo crypto/dsa.lo \
- crypto/ecdsa.lo crypto/elliptic.lo crypto/hmac.lo \
- crypto/md4.lo crypto/md5.lo crypto/ocsp.lo crypto/openpgp.lo \
- crypto/rand.lo crypto/rc4.lo crypto/ripemd160.lo crypto/rsa.lo \
- crypto/sha1.lo crypto/sha256.lo crypto/sha512.lo \
- crypto/subtle.lo crypto/tls.lo crypto/twofish.lo \
- crypto/x509.lo crypto/xtea.lo crypto/openpgp/armor.lo \
- crypto/openpgp/elgamal.lo crypto/openpgp/error.lo \
- crypto/openpgp/packet.lo crypto/openpgp/s2k.lo \
- crypto/x509/pkix.lo debug/dwarf.lo debug/elf.lo debug/gosym.lo \
- debug/macho.lo debug/pe.lo encoding/ascii85.lo \
- encoding/base32.lo encoding/base64.lo encoding/binary.lo \
- encoding/git85.lo encoding/hex.lo encoding/pem.lo exp/ebnf.lo \
- exp/gui.lo exp/norm.lo exp/spdy.lo exp/sql.lo exp/ssh.lo \
- exp/terminal.lo exp/types.lo exp/gui/x11.lo exp/sql/driver.lo \
- exp/template/html.lo go/ast.lo go/build.lo go/doc.lo \
- go/parser.lo go/printer.lo go/scanner.lo go/token.lo \
- hash/adler32.lo hash/crc32.lo hash/crc64.lo hash/fnv.lo \
- http/cgi.lo http/fcgi.lo http/httptest.lo http/pprof.lo \
- image/bmp.lo image/color.lo image/draw.lo image/gif.lo \
- image/jpeg.lo image/png.lo image/tiff.lo image/ycbcr.lo \
- index/suffixarray.lo io/ioutil.lo mime/multipart.lo \
- net/dict.lo net/textproto.lo old/netchan.lo old/regexp.lo \
- old/template.lo $(am__DEPENDENCIES_1) os/user.lo os/signal.lo \
- path/filepath.lo regexp/syntax.lo rpc/jsonrpc.lo \
+ csv/csv.lo errors/errors.lo exec/exec.lo expvar/expvar.lo \
+ flag/flag.lo fmt/fmt.lo gob/gob.lo hash/hash.lo html/html.lo \
+ http/http.lo image/image.lo io/io.lo json/json.lo log/log.lo \
+ math/math.lo mail/mail.lo mime/mime.lo net/net.lo os/os.lo \
+ patch/patch.lo path/path.lo rand/rand.lo reflect/reflect.lo \
+ regexp/regexp.lo rpc/rpc.lo runtime/runtime.lo \
+ scanner/scanner.lo smtp/smtp.lo sort/sort.lo \
+ strconv/strconv.lo strings/strings.lo sync/sync.lo \
+ syslog/syslog.lo syslog/syslog_c.lo tabwriter/tabwriter.lo \
+ template/template.lo time/time.lo unicode/unicode.lo \
+ url/url.lo utf16/utf16.lo utf8/utf8.lo websocket/websocket.lo \
+ xml/xml.lo archive/tar.lo archive/zip.lo compress/bzip2.lo \
+ compress/flate.lo compress/gzip.lo compress/lzw.lo \
+ compress/zlib.lo container/heap.lo container/list.lo \
+ container/ring.lo crypto/aes.lo crypto/bcrypt.lo \
+ crypto/blowfish.lo crypto/cast5.lo crypto/cipher.lo \
+ crypto/des.lo crypto/dsa.lo crypto/ecdsa.lo crypto/elliptic.lo \
+ crypto/hmac.lo crypto/md4.lo crypto/md5.lo crypto/ocsp.lo \
+ crypto/openpgp.lo crypto/rand.lo crypto/rc4.lo \
+ crypto/ripemd160.lo crypto/rsa.lo crypto/sha1.lo \
+ crypto/sha256.lo crypto/sha512.lo crypto/subtle.lo \
+ crypto/tls.lo crypto/twofish.lo crypto/x509.lo crypto/xtea.lo \
+ crypto/openpgp/armor.lo crypto/openpgp/elgamal.lo \
+ crypto/openpgp/error.lo crypto/openpgp/packet.lo \
+ crypto/openpgp/s2k.lo crypto/x509/pkix.lo debug/dwarf.lo \
+ debug/elf.lo debug/gosym.lo debug/macho.lo debug/pe.lo \
+ encoding/ascii85.lo encoding/base32.lo encoding/base64.lo \
+ encoding/binary.lo encoding/git85.lo encoding/hex.lo \
+ encoding/pem.lo exp/ebnf.lo exp/gui.lo exp/norm.lo exp/spdy.lo \
+ exp/sql.lo exp/ssh.lo exp/terminal.lo exp/types.lo \
+ exp/gui/x11.lo exp/sql/driver.lo exp/template/html.lo \
+ go/ast.lo go/build.lo go/doc.lo go/parser.lo go/printer.lo \
+ go/scanner.lo go/token.lo hash/adler32.lo hash/crc32.lo \
+ hash/crc64.lo hash/fnv.lo http/cgi.lo http/fcgi.lo \
+ http/httptest.lo http/pprof.lo image/bmp.lo image/color.lo \
+ image/draw.lo image/gif.lo image/jpeg.lo image/png.lo \
+ image/tiff.lo image/ycbcr.lo index/suffixarray.lo io/ioutil.lo \
+ mime/multipart.lo net/dict.lo net/textproto.lo old/netchan.lo \
+ old/regexp.lo old/template.lo $(am__DEPENDENCIES_1) os/user.lo \
+ os/signal.lo path/filepath.lo regexp/syntax.lo rpc/jsonrpc.lo \
runtime/debug.lo runtime/pprof.lo sync/atomic.lo \
sync/atomic_c.lo syscall/syscall.lo syscall/errno.lo \
syscall/wait.lo template/parse.lo testing/testing.lo \
cmath.gox \
crypto.gox \
csv.gox \
+ errors.gox \
exec.gox \
expvar.gox \
flag.gox \
go/csv/reader.go \
go/csv/writer.go
+go_errors_files = \
+ go/errors/errors.go
+
go_exec_files = \
go/exec/exec.go \
go/exec/lp_unix.go
cmath/cmath.lo \
crypto/crypto.lo \
csv/csv.lo \
+ errors/errors.lo \
exec/exec.lo \
expvar/expvar.lo \
flag/flag.lo \
bytes/check \
cmath/check \
csv/check \
+ errors/check \
exec/check \
expvar/check \
flag/check \
@$(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
exec/exec.lo.dep: $(go_exec_files)
$(BUILDDEPS)
$(BUILDGOX)
csv.gox: csv/csv.lo
$(BUILDGOX)
+errors.gox: errors/errors.lo
+ $(BUILDGOX)
exec.gox: exec/exec.lo
$(BUILDGOX)
expvar.gox: expvar/expvar.lo
import (
"bytes"
+ "errors"
"io"
"io/ioutil"
"os"
)
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.
// }
type Reader struct {
r io.Reader
- err os.Error
+ err error
nb int64 // number of unread bytes for current file entry
pad int64 // amount of padding (ignored) after current file entry
}
func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
// Next advances to the next entry in the tar archive.
-func (tr *Reader) Next() (*Header, os.Error) {
+func (tr *Reader) Next() (*Header, error) {
var hdr *Header
if tr.err == nil {
tr.skipUnread()
return nil
}
if bytes.Equal(header, zeroBlock[0:blockSize]) {
- tr.err = os.EOF
+ tr.err = io.EOF
} else {
tr.err = HeaderError // zero block and then non-zero block
}
// Read reads from the current entry in the tar archive.
// It returns 0, os.EOF when it reaches the end of that 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 {
// file consumed
- return 0, os.EOF
+ return 0, io.EOF
}
if int64(len(b)) > tr.nb {
n, err = tr.r.Read(b)
tr.nb -= int64(n)
- if err == os.EOF && tr.nb > 0 {
+ if err == io.EOF && tr.nb > 0 {
err = io.ErrUnexpectedEOF
}
tr.err = err
}
}
hdr, err := tr.Next()
- if err == os.EOF {
+ if err == io.EOF {
break
}
if hdr != nil || err != nil {
// loop over all files
for ; ; nread++ {
hdr, err := tr.Next()
- if hdr == nil || err == os.EOF {
+ if hdr == nil || err == io.EOF {
break
}
rdbuf := make([]uint8, 8)
for {
nr, err := tr.Read(rdbuf)
- if err == os.EOF {
+ if err == io.EOF {
break
}
if err != nil {
for {
nr, err := f.Read(rdbuf)
w.Write(rdbuf[0:nr])
- if err == os.EOF {
+ if err == io.EOF {
break
}
}
for ; ; nread++ {
hdr, err := tr.Next()
- if hdr == nil || err == os.EOF {
+ if hdr == nil || err == io.EOF {
break
}
}
// - catch more errors (no first header, write after close, etc.)
import (
+ "errors"
"io"
- "os"
"strconv"
)
var (
- ErrWriteTooLong = os.NewError("write too long")
- ErrFieldTooLong = os.NewError("header field too long")
- ErrWriteAfterClose = os.NewError("write after close")
+ ErrWriteTooLong = errors.New("write too long")
+ ErrFieldTooLong = errors.New("header field too long")
+ ErrWriteAfterClose = errors.New("write after close")
)
// A Writer provides sequential writing of a tar archive in POSIX.1 format.
// tw.Close()
type Writer struct {
w io.Writer
- err os.Error
+ err error
nb int64 // number of unwritten bytes for current file entry
pad int64 // amount of padding to write after current file entry
closed bool
func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
// Flush finishes writing the current file (optional).
-func (tw *Writer) Flush() os.Error {
+func (tw *Writer) Flush() error {
n := tw.nb + tw.pad
for n > 0 && tw.err == nil {
nr := n
// WriteHeader writes hdr and prepares to accept the file's contents.
// WriteHeader calls Flush if it is not the first header.
// 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 {
return ErrWriteAfterClose
}
// Write writes to the current entry in the tar archive.
// Write returns the error ErrWriteTooLong if more than
// 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 {
err = ErrWriteTooLong
return
// Close closes the tar archive, flushing any unwritten
// data to the underlying writer.
-func (tw *Writer) Close() os.Error {
+func (tw *Writer) Close() error {
if tw.err != nil || tw.closed {
return tw.err
}
import (
"bufio"
"compress/flate"
+ "errors"
"hash"
"hash/crc32"
"encoding/binary"
)
var (
- FormatError = os.NewError("zip: not a valid zip file")
- UnsupportedMethod = os.NewError("zip: unsupported compression algorithm")
- ChecksumError = os.NewError("zip: checksum error")
+ FormatError = errors.New("zip: not a valid zip file")
+ UnsupportedMethod = errors.New("zip: unsupported compression algorithm")
+ ChecksumError = errors.New("zip: checksum error")
)
type Reader struct {
}
// 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)
if err != nil {
return nil, err
// NewReader returns a new Reader reading from r, which is assumed to
// 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)
if err := zr.init(r, size); err != nil {
return nil, err
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)
if err != nil {
return err
}
// 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()
}
// Open returns a ReadCloser that provides access to the File's contents.
// 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()
if err != nil {
return
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)
r.hash.Write(b[:n])
- if err != os.EOF {
+ if err != io.EOF {
return
}
if r.f.hasDataDescriptor() {
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
if _, err := io.ReadFull(r, b[:]); err != nil {
return err
// findBodyOffset does the minimum work to verify the file has a header
// 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)
var b [fileHeaderLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil {
// readDirectoryHeader attempts to read a directory header from r.
// It returns io.ErrUnexpectedEOF if it cannot read a complete header,
// 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
if _, err := io.ReadFull(r, b[:]); err != nil {
return err
return nil
}
-func readDataDescriptor(r io.Reader, f *File) os.Error {
+func readDataDescriptor(r io.Reader, f *File) error {
var b [dataDescriptorLen]byte
if _, err := io.ReadFull(r, b[:]); err != nil {
return err
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
var b []byte
for i, bLen := range []int64{1024, 65 * 1024} {
bLen = size
}
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
}
if p := findSignatureInBlock(b); p >= 0 {
"encoding/binary"
"io"
"io/ioutil"
- "os"
"testing"
"time"
)
Name string
Comment string
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 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)])
return len(b), nil
}
*/
package zip
-import "os"
+import "errors"
import "time"
// Compression methods.
comment string
}
-func recoverError(errp *os.Error) {
+func recoverError(errp *error) {
if e := recover(); e != nil {
- if err, ok := e.(os.Error); ok {
+ if err, ok := e.(error); ok {
*errp = err
return
}
// Mode returns the permission and mode bits for the FileHeader.
// 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 {
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.
"bufio"
"compress/flate"
"encoding/binary"
+ "errors"
"hash"
"hash/crc32"
"io"
- "os"
)
// TODO(adg): support zip file comments
// Close finishes writing the zip file by writing the central directory.
// 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 err = w.last.close(); err != nil {
return
w.last = nil
}
if w.closed {
- return os.NewError("zip: writer closed twice")
+ return errors.New("zip: writer closed twice")
}
w.closed = true
// 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
// 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{
Name: name,
Method: Deflate,
// 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
// 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 err := w.last.close(); err != nil {
return nil, err
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)
write(w, uint32(fileHeaderSignature))
write(w, h.ReaderVersion)
closed bool
}
-func (w *fileWriter) Write(p []byte) (int, os.Error) {
+func (w *fileWriter) Write(p []byte) (int, error) {
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)
return w.rawCount.Write(p)
}
-func (w *fileWriter) close() (err os.Error) {
+func (w *fileWriter) close() (err error) {
if w.closed {
- return os.NewError("zip: file closed twice")
+ return errors.New("zip: file closed twice")
}
w.closed = true
if err = w.comp.Close(); err != nil {
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)
w.count += int64(n)
return n, err
io.Writer
}
-func (w nopCloser) Close() os.Error {
+func (w nopCloser) Close() error {
return nil
}
import (
"bytes"
"fmt"
- "os"
+ "io"
"testing"
)
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)) {
- return 0, os.EOF
+ return 0, io.EOF
}
n = copy(p, s[off:])
return
import (
"big"
"fmt"
- "os"
"reflect"
"time"
)
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.
type SyntaxError struct {
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.
// BOOLEAN
-func parseBool(bytes []byte) (ret bool, err os.Error) {
+func parseBool(bytes []byte) (ret bool, err error) {
if len(bytes) != 1 {
err = SyntaxError{"invalid boolean"}
return
// parseInt64 treats the given bytes as a big-endian, signed integer and
// returns the result.
-func parseInt64(bytes []byte) (ret int64, err os.Error) {
+func parseInt64(bytes []byte) (ret int64, err error) {
if len(bytes) > 8 {
// We'll overflow an int64 in this case.
err = StructuralError{"integer too large"}
// parseInt treats the given bytes as a big-endian, signed integer and returns
// the result.
-func parseInt(bytes []byte) (int, os.Error) {
+func parseInt(bytes []byte) (int, error) {
ret64, err := parseInt64(bytes)
if err != nil {
return 0, err
}
// 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 {
err = SyntaxError{"zero length BIT STRING"}
return
// parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
// returns it. An object identifier is a sequence of variable length integers
// 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 {
err = SyntaxError{"zero length OBJECT IDENTIFIER"}
return
// parseBase128Int parses a base-128 encoded int from the given offset in the
// 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
for shifted := 0; offset < len(bytes); shifted++ {
if shifted > 4 {
// UTCTime
-func parseUTCTime(bytes []byte) (ret *time.Time, err os.Error) {
+func parseUTCTime(bytes []byte) (ret *time.Time, err error) {
s := string(bytes)
ret, err = time.Parse("0601021504Z0700", s)
if err == nil {
// parseGeneralizedTime parses the GeneralizedTime from the given byte slice
// 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))
}
// parsePrintableString parses a ASN.1 PrintableString from the given byte
// 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 {
if !isPrintable(b) {
err = SyntaxError{"PrintableString contains invalid character"}
// parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
// 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 {
if b >= 0x80 {
err = SyntaxError{"IA5String contains invalid character"}
// parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
// 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
}
// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
// 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
}
// 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
// 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
b := bytes[offset]
offset++
// 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
// 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)
if !ok {
err = StructuralError{"unknown Go type for slice"}
// 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
// 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
fieldType := v.Type()
return
case timeType:
var time *time.Time
- var err1 os.Error
+ var err1 error
if universalTag == tagUTCTime {
time, err1 = parseUTCTime(innerBytes)
} else {
//
// Other ASN.1 types are not supported; if it encounters them,
// 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, "")
}
// UnmarshalWithParams allows field parameters to be specified for the
// 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()
offset, err := parseField(v, b, 0, parseFieldParameters(params))
if err != nil {
"bytes"
"fmt"
"io"
- "os"
"reflect"
"time"
)
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())
if err != nil {
return
return
}
-func marshalBase128Int(out *forkableWriter, n int64) (err os.Error) {
+func marshalBase128Int(out *forkableWriter, n int64) (err error) {
if n == 0 {
err = out.WriteByte(0)
return
return nil
}
-func marshalInt64(out *forkableWriter, i int64) (err os.Error) {
+func marshalInt64(out *forkableWriter, i int64) (err error) {
n := int64Length(i)
for ; n > 0; n-- {
return
}
-func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) {
+func marshalBigInt(out *forkableWriter, n *big.Int) (err error) {
if n.Sign() < 0 {
// A negative number has to be converted to two's-complement
// form. So we'll subtract 1 and invert. If the
return
}
-func marshalLength(out *forkableWriter, i int) (err os.Error) {
+func marshalLength(out *forkableWriter, i int) (err error) {
n := lengthLength(i)
for ; n > 0; n-- {
return
}
-func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err os.Error) {
+func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) {
b := uint8(t.class) << 6
if t.isCompound {
b |= 0x20
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)
err = out.WriteByte(paddingBits)
if err != nil {
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 {
return StructuralError{"invalid object identifier"}
}
return
}
-func marshalPrintableString(out *forkableWriter, s string) (err os.Error) {
+func marshalPrintableString(out *forkableWriter, s string) (err error) {
b := []byte(s)
for _, c := range b {
if !isPrintable(c) {
return
}
-func marshalIA5String(out *forkableWriter, s string) (err os.Error) {
+func marshalIA5String(out *forkableWriter, s string) (err error) {
b := []byte(s)
for _, c := range b {
if c > 127 {
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))
if err != nil {
return
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 {
case 1950 <= t.Year && t.Year < 2000:
err = marshalTwoDigits(out, int(t.Year-1900))
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() {
case timeType:
return marshalUTCTime(out, value.Interface().(*time.Time))
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 v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 {
return marshalField(out, v.Elem(), params)
}
// 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
v := reflect.ValueOf(val)
f := newForkableWriter()
package big
import (
+ "errors"
"fmt"
"io"
- "os"
"rand"
"strings"
)
// ``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.
//
-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
ch, _, err := r.ReadRune()
if err != nil {
// 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),
// '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
base := 0
switch ch {
case 's', 'v':
// let scan determine the base
default:
- return os.NewError("Int.Scan: invalid verb")
+ return errors.New("Int.Scan: invalid verb")
}
_, _, err := z.scan(s, base)
return err
return nil, false
}
_, _, err = r.ReadRune()
- if err != os.EOF {
+ if err != io.EOF {
return nil, false
}
return z, true // err == os.EOF => scan consumed all of s
const intGobVersion byte = 1
// 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
i := z.abs.bytes(buf) - 1 // i >= 0
b := intGobVersion << 1 // make space for sign bit
}
// 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 {
- return os.NewError("Int.GobDecode: no data")
+ return errors.New("Int.GobDecode: no data")
}
b := buf[0]
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.abs = z.abs.setBytes(buf[1:])
// and rationals.
import (
+ "errors"
"io"
- "os"
"rand"
)
// ``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.
//
-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
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
return z, 0, err
}
}
- case os.EOF:
+ case io.EOF:
return z.make(0), 10, nil
default:
return z, 10, err
}
if ch, _, err = r.ReadRune(); err != nil {
- if err != os.EOF {
+ if err != io.EOF {
return z, int(b), err
}
break
return z, 10, nil
case base != 0 || b != 8:
// 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
import (
"fmt"
- "os"
+ "io"
"strings"
"testing"
)
t.Errorf("scan%+v\n\tgot b = %d; want %d", a, b, a.base)
}
next, _, err := r.ReadRune()
- if err == os.EOF {
+ if err == io.EOF {
next = 0
err = nil
}
import (
"encoding/binary"
+ "errors"
"fmt"
- "os"
"strings"
)
// Scan is a support routine for fmt.Scanner. It accepts the formats
// '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)
if err != nil {
return err
}
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 {
- return os.NewError("Rat.Scan: invalid syntax")
+ return errors.New("Rat.Scan: invalid syntax")
}
return nil
}
return nil, false
}
s = s[sep+1:]
- var err os.Error
+ var err error
if z.b, _, err = z.b.scan(strings.NewReader(s), 10); err != nil {
return nil, false
}
const ratGobVersion byte = 1
// 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)
i := z.b.bytes(buf)
j := z.a.abs.bytes(buf[0:i])
n := i - j
if int(uint32(n)) != n {
// 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))
j -= 1 + 4
}
// 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 {
- return os.NewError("Rat.GobDecode: no data")
+ return errors.New("Rat.GobDecode: no data")
}
b := buf[0]
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
i := j + binary.BigEndian.Uint32(buf[j-4:j])
import (
"bytes"
"io"
- "os"
"strconv"
"utf8"
)
ErrorString string
}
-func (err *Error) String() string { return err.ErrorString }
+func (err *Error) Error() string { return err.ErrorString }
var (
- ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"}
- ErrInvalidUnreadRune os.Error = &Error{"bufio: invalid use of UnreadRune"}
- ErrBufferFull os.Error = &Error{"bufio: buffer full"}
- ErrNegativeCount os.Error = &Error{"bufio: negative count"}
- errInternal os.Error = &Error{"bufio: internal error"}
+ ErrInvalidUnreadByte error = &Error{"bufio: invalid use of UnreadByte"}
+ ErrInvalidUnreadRune error = &Error{"bufio: invalid use of UnreadRune"}
+ ErrBufferFull error = &Error{"bufio: buffer full"}
+ ErrNegativeCount error = &Error{"bufio: negative count"}
+ errInternal error = &Error{"bufio: internal error"}
)
// BufSizeError is the error representing an invalid buffer size.
type BufSizeError int
-func (b BufSizeError) String() string {
+func (b BufSizeError) Error() string {
return "bufio: bad buffer size " + strconv.Itoa(int(b))
}
buf []byte
rd io.Reader
r, w int
- err os.Error
+ err error
lastByte int
lastRuneSize int
}
// which must be greater than one. If the argument io.Reader is already a
// Reader with large enough size, it returns the underlying Reader.
// 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 {
return nil, BufSizeError(size)
}
}
}
-func (b *Reader) readErr() os.Error {
+func (b *Reader) readErr() error {
err := b.err
b.err = nil
return err
// 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
// 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 {
return nil, ErrNegativeCount
}
// It calls Read at most once on the underlying Reader,
// hence n may be less than len(p).
// 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)
if n == 0 {
return 0, b.readErr()
// ReadByte reads and returns a single byte.
// 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
for b.w == b.r {
if b.err != nil {
}
// 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
if b.r == b.w && b.lastByte >= 0 {
b.w = 1
// ReadRune reads a single UTF-8 encoded Unicode character and returns the
// 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 {
b.fill()
}
// the buffer was not a ReadRune, UnreadRune returns an error. (In this
// regard it is stricter than UnreadByte, which will unread the last byte
// from any read operation.)
-func (b *Reader) UnreadRune() os.Error {
+func (b *Reader) UnreadRune() error {
if b.lastRuneSize < 0 || b.r == 0 {
return ErrInvalidUnreadRune
}
// by the next I/O operation, most clients should use
// ReadBytes or ReadString instead.
// 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.
if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 {
line1 := b.buf[b.r : b.r+i+1]
// 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,
// 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')
if err == ErrBufferFull {
// Handle the case where "\r\n" straddles the buffer.
// 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
// 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,
// accumulating full buffers.
var frag []byte
err = nil
for {
- var e os.Error
+ var e error
frag, e = b.ReadSlice(delim)
if e == nil { // got final fragment
break
// 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
// 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)
return string(bytes), e
}
// Writer implements buffering for an io.Writer object.
type Writer struct {
- err os.Error
+ err error
buf []byte
n int
wr io.Writer
// which must be greater than zero. If the argument io.Writer is already a
// Writer with large enough size, it returns the underlying Writer.
// 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 {
return nil, BufSizeError(size)
}
}
// 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 {
return b.err
}
// It returns the number of bytes written.
// If nn < len(p), it also returns an error explaining
// 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 {
var n int
if b.Buffered() == 0 {
}
// WriteByte writes a single byte.
-func (b *Writer) WriteByte(c byte) os.Error {
+func (b *Writer) WriteByte(c byte) error {
if b.err != nil {
return b.err
}
// WriteRune writes a single Unicode code point, returning
// 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 {
err = b.WriteByte(byte(r))
if err != nil {
// It returns the number of bytes written.
// If the count is less than len(s), it also returns an error explaining
// why the write is short.
-func (b *Writer) WriteString(s string) (int, os.Error) {
+func (b *Writer) WriteString(s string) (int, error) {
nn := 0
for len(s) > b.Available() && b.err == nil {
n := copy(b.buf[b.n:], s)
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)
if e != nil {
return n, e
nb := 0
for {
c, e := buf.ReadByte()
- if e == os.EOF {
+ if e == io.EOF {
break
}
if e == nil {
b[nb] = c
nb++
} else if e != iotest.ErrTimeout {
- panic("Data: " + e.String())
+ panic("Data: " + e.Error())
}
}
return string(b[0:nb])
s := ""
for {
s1, e := b.ReadString('\n')
- if e == os.EOF {
+ if e == io.EOF {
break
}
if e != nil && e != iotest.ErrTimeout {
- panic("GetLines: " + e.String())
+ panic("GetLines: " + e.Error())
}
s += s1
}
for {
n, e := buf.Read(b[nb : nb+m])
nb += n
- if e == os.EOF {
+ if e == io.EOF {
break
}
}
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) {
s := r.data[r.step]
n = copy(p, s)
r.step++
} else {
- err = os.EOF
+ err = io.EOF
}
return
}
for {
r, _, err := r.ReadRune()
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
return
}
break
for {
r1, _, err := r.ReadRune()
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
t.Error("unexpected EOF")
}
break
_, _, err := r.ReadRune()
if err == nil {
t.Error("expected error at EOF")
- } else if err != os.EOF {
+ } else if err != io.EOF {
t.Error("expected EOF; got", err)
}
}
type errorWriterTest struct {
n, m int
- err os.Error
- expect os.Error
+ err 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
}
if s, err := buf.Peek(0); string(s) != "" || err != nil {
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)
}
}
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
if n > len(t.data) {
n = len(t.data)
copy(buf, t.data)
t.data = t.data[n:]
if len(t.data) == 0 {
- err = os.EOF
+ err = io.EOF
}
return
}
t.Errorf("ReadLine returned prefix")
}
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
t.Fatalf("Got unknown error: %s", err)
}
break
func TestReadEmptyBuffer(t *testing.T) {
l, _ := NewReaderSize(bytes.NewBuffer(nil), 10)
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)
}
}
}
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)
}
}
type readLineResult struct {
line []byte
isPrefix bool
- err os.Error
+ err error
}
var readLineNewlinesTests = []struct {
{nil, false, nil},
{[]byte("b"), true, nil},
{nil, false, nil},
- {nil, false, os.EOF},
+ {nil, false, io.EOF},
}},
{"hello\r\nworld\r\n", 6, []readLineResult{
{[]byte("hello"), true, nil},
{nil, false, nil},
{[]byte("world"), true, nil},
{nil, false, nil},
- {nil, false, os.EOF},
+ {nil, false, io.EOF},
}},
{"hello\rworld\r", 6, []readLineResult{
{[]byte("hello"), true, nil},
{[]byte("\rworld"), true, nil},
{[]byte("\r"), false, nil},
- {nil, false, os.EOF},
+ {nil, false, io.EOF},
}},
{"h\ri\r\n\r", 2, []readLineResult{
{[]byte("h"), true, nil},
{[]byte("\ri"), true, nil},
{nil, false, nil},
{[]byte("\r"), false, nil},
- {nil, false, os.EOF},
+ {nil, false, io.EOF},
}},
}
// Simple byte buffer for marshaling data.
import (
+ "errors"
"io"
- "os"
"utf8"
)
// Write appends the contents of p to the buffer. The return
// value n is the length of p; err is always nil.
-func (b *Buffer) Write(p []byte) (n int, err os.Error) {
+func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(p))
copy(b.buf[m:], p)
// WriteString appends the contents of s to the buffer. The return
// value n is the length of s; err is always nil.
-func (b *Buffer) WriteString(s string) (n int, err os.Error) {
+func (b *Buffer) WriteString(s string) (n int, err error) {
b.lastRead = opInvalid
m := b.grow(len(s))
return copy(b.buf[m:], s), nil
// The return value n is the number of bytes read.
// Any error except os.EOF encountered during the read
// 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
// If buffer is empty, reset to recover space.
if b.off >= len(b.buf) {
m, e := r.Read(b.buf[len(b.buf):cap(b.buf)])
b.buf = b.buf[0 : len(b.buf)+m]
n += int64(m)
- if e == os.EOF {
+ if e == io.EOF {
break
}
if e != nil {
// 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.
// 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
if b.off < len(b.buf) {
m, e := w.Write(b.buf[b.off:])
// WriteByte appends the byte c to the buffer.
// The returned error is always nil, but is included
// to match bufio.Writer's WriteByte.
-func (b *Buffer) WriteByte(c byte) os.Error {
+func (b *Buffer) WriteByte(c byte) error {
b.lastRead = opInvalid
m := b.grow(1)
b.buf[m] = c
// code point r to the buffer, returning its length and
// an error, which is always nil but is included
// 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 {
b.WriteByte(byte(r))
return 1, nil
// 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;
// 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
if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space.
b.Truncate(0)
- return 0, os.EOF
+ return 0, io.EOF
}
n = copy(p, b.buf[b.off:])
b.off += n
// ReadByte reads and returns the next byte from the buffer.
// 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
if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space.
b.Truncate(0)
- return 0, os.EOF
+ return 0, io.EOF
}
c = b.buf[b.off]
b.off++
// If no bytes are available, the error returned is os.EOF.
// If the bytes are an erroneous UTF-8 encoding, it
// 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
if b.off >= len(b.buf) {
// Buffer is empty, reset to recover space.
b.Truncate(0)
- return 0, 0, os.EOF
+ return 0, 0, io.EOF
}
b.lastRead = opReadRune
c := b.buf[b.off]
// not a ReadRune, UnreadRune returns an error. (In this regard
// it is stricter than UnreadByte, which will unread the last byte
// from any read operation.)
-func (b *Buffer) UnreadRune() os.Error {
+func (b *Buffer) UnreadRune() error {
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
if b.off > 0 {
// UnreadByte unreads the last byte returned by the most recent
// read operation. If write has happened since the last read, UnreadByte
// returns an error.
-func (b *Buffer) UnreadByte() os.Error {
+func (b *Buffer) UnreadByte() error {
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
if b.off > 0 {
// 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
// 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)
size := i + 1
if i < 0 {
size = len(b.buf) - b.off
- err = os.EOF
+ err = io.EOF
}
line = make([]byte, size)
copy(line, b.buf[b.off:])
// 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 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)
return string(bytes), err
}
import (
. "bytes"
- "os"
+ "io"
"rand"
"testing"
"utf8"
buffer string
delim byte
expected []string
- err os.Error
+ err error
}{
- {"", 0, []string{""}, os.EOF},
+ {"", 0, []string{""}, io.EOF},
{"a\x00", 0, []string{"a\x00"}, nil},
{"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, 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', []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) {
for _, test := range readBytesTests {
buf := NewBufferString(test.buffer)
- var err os.Error
+ var err error
for _, expected := range test.expected {
var bytes []byte
bytes, err = buf.ReadBytes(test.delim)
import (
"bufio"
"io"
- "os"
)
// 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
// be checked afterwards.
type bitReader struct {
r byteReader
n uint64
bits uint
- err os.Error
+ err error
}
// 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
// a bufio.Reader.
type byteReader interface {
- ReadByte() (byte, os.Error)
+ ReadByte() (byte, error)
}
func newBitReader(r io.Reader) bitReader {
func (br *bitReader) ReadBits64(bits uint) (n uint64) {
for bits > br.bits {
b, err := br.r.ReadByte()
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
if err != nil {
return n != 0
}
-func (br *bitReader) Error() os.Error {
+func (br *bitReader) Error() error {
return br.err
}
// Package bzip2 implements bzip2 decompression.
package bzip2
-import (
- "io"
- "os"
-)
+import "io"
// There's no RFC for bzip2. I used the Wikipedia page for reference and a lot
// of guessing: http://en.wikipedia.org/wiki/Bzip2
// syntactically invalid.
type StructuralError string
-func (s StructuralError) String() string {
+func (s StructuralError) Error() string {
return "bzip2 data invalid: " + string(s)
}
const bzip2FinalMagic = 0x177245385090
// setup parses the bzip2 header.
-func (bz2 *reader) setup() os.Error {
+func (bz2 *reader) setup() error {
br := &bz2.br
magic := br.ReadBits(16)
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 {
- return 0, os.EOF
+ return 0, io.EOF
}
if !bz2.setupDone {
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
// preprocessing step. The block based nature means that we can
// preallocate fixed-size buffers and reuse them. However, the RLE
if magic == bzip2FinalMagic {
br.ReadBits64(32) // ignored CRC
bz2.eof = true
- return 0, os.EOF
+ return 0, io.EOF
} else if magic != bzip2BlockMagic {
return 0, StructuralError("bad magic value found")
}
}
// 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.ReadBits64(32) // skip checksum. TODO: check it if we can figure out what it is.
randomized := br.ReadBits(1)
"encoding/hex"
"io"
"io/ioutil"
- "os"
"testing"
)
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))
return ioutil.ReadAll(r)
}
package bzip2
-import (
- "os"
- "sort"
-)
+import "sort"
// A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a
// symbol.
// newHuffmanTree builds a Huffman tree from a slice containing the code
// 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
// each symbol (consider reflecting a tree down the middle, for
// example). Since the code length assignments determine the
// 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
// 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)
// We have to search the list of codes to find the divide between the left and right sides.
import (
"io"
"math"
- "os"
)
const (
offset int
hash int
maxInsertIndex int
- err os.Error
+ err error
}
func (d *compressor) fillDeflate(b []byte) int {
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 {
var window []byte
if d.blockStart <= index {
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 {
return d.w.err
}
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)
b = b[d.fill(d, b):]
for len(b) > 0 {
return n, d.err
}
-func (d *compressor) syncFlush() os.Error {
+func (d *compressor) syncFlush() error {
d.sync = true
d.step(d)
if d.err == nil {
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)
switch {
return nil
}
-func (d *compressor) close() os.Error {
+func (d *compressor) close() error {
d.sync = true
d.step(d)
if d.err != nil {
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 {
return w.w.Write(b)
}
// Write writes data to w, which will eventually write the
// 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)
}
// 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.
-func (w *Writer) Flush() os.Error {
+func (w *Writer) Flush() error {
// For more about flushing:
// http://www.bolet.org/~pornin/deflate-flush.html
return w.d.syncFlush()
}
// Close flushes and closes the writer.
-func (w *Writer) Close() os.Error {
+func (w *Writer) Close() error {
return w.d.close()
}
"fmt"
"io"
"io/ioutil"
- "os"
"sync"
"testing"
)
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 {
b.mu.RLock()
n, err = b.buf.Read(p)
}
}
-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)
b.signal()
return
b.signal()
}
-func (b *syncBuffer) Close() os.Error {
+func (b *syncBuffer) Close() error {
b.closed = true
b.signal()
return nil
}
buf.ReadMode()
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])
}
if buf.buf.Len() != 0 {
}
}
-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)
w := NewWriter(buffer, level)
w.Write(input)
import (
"io"
"math"
- "os"
"strconv"
)
literalEncoding *huffmanEncoder
offsetEncoding *huffmanEncoder
codegenEncoding *huffmanEncoder
- err os.Error
+ err error
}
type WrongValueError struct {
}
}
-func (err WrongValueError) String() string {
+func (err WrongValueError) Error() string {
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))
}
import (
"bufio"
"io"
- "os"
"strconv"
)
// A CorruptInputError reports the presence of corrupt input at a given offset.
type CorruptInputError int64
-func (e CorruptInputError) String() string {
+func (e CorruptInputError) Error() string {
return "flate: corrupt input before offset " + strconv.Itoa64(int64(e))
}
// An InternalError reports an error in the flate code itself.
type InternalError string
-func (e InternalError) String() string { return "flate: internal error: " + string(e) }
+func (e InternalError) Error() string { return "flate: internal error: " + string(e) }
// A ReadError reports an error encountered while reading input.
type ReadError struct {
- Offset int64 // byte offset where error occurred
- Error os.Error // error returned by underlying Read
+ Offset int64 // byte offset where error occurred
+ Err error // error returned by underlying Read
}
-func (e *ReadError) String() string {
- return "flate: read error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Error.String()
+func (e *ReadError) Error() string {
+ return "flate: read error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Err.Error()
}
// A WriteError reports an error encountered while writing output.
type WriteError struct {
- Offset int64 // byte offset where error occurred
- Error os.Error // error returned by underlying Write
+ Offset int64 // byte offset where error occurred
+ Err error // error returned by underlying Write
}
-func (e *WriteError) String() string {
- return "flate: write error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Error.String()
+func (e *WriteError) Error() string {
+ return "flate: write error at offset " + strconv.Itoa64(e.Offset) + ": " + e.Err.Error()
}
// Huffman decoder is based on
// the NewReader will introduce its own buffering.
type Reader interface {
io.Reader
- ReadByte() (c byte, err os.Error)
+ ReadByte() (c byte, err error)
}
// Decompress state.
// and decompression state.
step func(*decompressor)
final bool
- err os.Error
+ err error
toRead []byte
hl, hd *huffmanDecoder
copyLen int
f.flush((*decompressor).nextBlock)
return
}
- f.err = os.EOF
+ f.err = io.EOF
return
}
for f.nb < 1+2 {
}
}
-func (f *decompressor) Read(b []byte) (int, os.Error) {
+func (f *decompressor) Read(b []byte) (int, error) {
for {
if len(f.toRead) > 0 {
n := copy(b, f.toRead)
panic("unreachable")
}
-func (f *decompressor) Close() os.Error {
- if f.err == os.EOF {
+func (f *decompressor) Close() error {
+ if f.err == io.EOF {
return nil
}
return f.err
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].
for f.nb < 5+5+4 {
if err := f.moreBits(); err != nil {
f.hw = f.hp
}
-func (f *decompressor) moreBits() os.Error {
+func (f *decompressor) moreBits() error {
c, err := f.r.ReadByte()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return err
}
// 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++ {
lim := h.limit[n]
if lim == -1 {
import (
"bufio"
"compress/flate"
+ "errors"
"hash"
"hash/crc32"
"io"
- "os"
)
// BUG(nigeltao): Comments and Names don't properly map UTF-8 character codes outside of
return bufio.NewReader(r)
}
-var HeaderError = os.NewError("invalid gzip header")
-var ChecksumError = os.NewError("gzip checksum error")
+var HeaderError = errors.New("invalid gzip header")
+var ChecksumError = errors.New("gzip checksum error")
// 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.
size uint32
flg byte
buf [512]byte
- err os.Error
+ err error
}
// NewReader creates a new Decompressor reading the given reader.
// The implementation buffers input and may read more data than necessary from r.
// It is the caller's responsibility to call Close on the Decompressor when done.
-func NewReader(r io.Reader) (*Decompressor, os.Error) {
+func NewReader(r io.Reader) (*Decompressor, error) {
z := new(Decompressor)
z.r = makeReader(r)
z.digest = crc32.NewIEEE()
return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
}
-func (z *Decompressor) readString() (string, os.Error) {
- var err os.Error
+func (z *Decompressor) readString() (string, error) {
+ var err error
for i := 0; ; i++ {
if i >= len(z.buf) {
return "", HeaderError
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])
if err != nil {
return 0, err
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])
if err != nil {
return err
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 {
return 0, z.err
}
n, err = z.decompressor.Read(p)
z.digest.Write(p[0:n])
z.size += uint32(n)
- if n != 0 || err != os.EOF {
+ if n != 0 || err != io.EOF {
z.err = err
return
}
}
// 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() }
import (
"bytes"
"io"
- "os"
"testing"
)
desc string
raw string
gzip []byte
- err os.Error
+ err error
}
var gunzipTests = []gunzipTest{
import (
"compress/flate"
+ "errors"
"hash"
"hash/crc32"
"io"
- "os"
)
// These constants are copied from the flate package, so that code that imports
size uint32
closed bool
buf [10]byte
- err os.Error
+ err error
}
// 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)
}
// It is the caller's responsibility to call Close on the WriteCloser when done.
// level is the compression level, which can be DefaultCompression, NoCompression,
// 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.OS = 255 // unknown
z.w = 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 {
- 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)))
_, err := z.w.Write(z.buf[0:2])
}
// 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).
// TODO(nigeltao): Convert from UTF-8 to ISO 8859-1 (Latin-1).
for _, v := range s {
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)
return err
}
-func (z *Compressor) Write(p []byte) (int, os.Error) {
+func (z *Compressor) Write(p []byte) (int, error) {
if z.err != nil {
return 0, z.err
}
}
// 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 {
return z.err
}
import (
"bufio"
+ "errors"
"fmt"
"io"
"os"
bits uint32
nBits uint
width uint
- read func(*decoder) (uint16, os.Error) // readLSB or readMSB
- litWidth int // width in bits of literal codes
- err os.Error
+ read func(*decoder) (uint16, error) // readLSB or readMSB
+ litWidth int // width in bits of literal codes
+ err error
// The first 1<<litWidth codes are literal codes.
// The next two codes mean clear and EOF.
}
// 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 {
x, err := d.r.ReadByte()
if err != nil {
}
// 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 {
x, err := d.r.ReadByte()
if err != nil {
return code, nil
}
-func (d *decoder) Read(b []byte) (int, os.Error) {
+func (d *decoder) Read(b []byte) (int, error) {
for {
if len(d.toRead) > 0 {
n := copy(b, d.toRead)
for {
code, err := d.read(d)
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
d.err = err
continue
case code == d.eof:
d.flush()
- d.err = os.EOF
+ d.err = io.EOF
return
case code <= d.hi:
c, i := code, len(d.output)-1
d.prefix[d.hi] = d.last
}
default:
- d.err = os.NewError("lzw: invalid code")
+ d.err = errors.New("lzw: invalid code")
return
}
d.last, d.hi = code, d.hi+1
d.o = 0
}
-func (d *decoder) Close() os.Error {
+func (d *decoder) Close() error {
d.err = os.EINVAL // in case any Reads come along
return nil
}
case MSB:
d.read = (*decoder).readMSB
default:
- d.err = os.NewError("lzw: unknown order")
+ d.err = errors.New("lzw: unknown order")
return d
}
if litWidth < 2 || 8 < litWidth {
"bytes"
"io"
"io/ioutil"
- "os"
"runtime"
"strconv"
"strings"
desc string
raw string
compressed string
- err os.Error
+ err error
}
var lzwTests = []lzwTest{
import (
"bufio"
+ "errors"
"fmt"
"io"
"os"
// A writer is a buffered, flushable writer.
type writer interface {
- WriteByte(byte) os.Error
- Flush() os.Error
+ WriteByte(byte) error
+ Flush() error
}
// An errWriteCloser is an io.WriteCloser that always returns a given error.
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
}
-func (e *errWriteCloser) Close() os.Error {
+func (e *errWriteCloser) Close() error {
return e.err
}
w writer
// write, bits, nBits and width are the state for converting a code stream
// into a byte stream.
- write func(*encoder, uint32) os.Error
+ write func(*encoder, uint32) error
bits uint32
nBits uint
width uint
savedCode uint32
// err is the first error encountered during writing. Closing the encoder
// 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
// 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.
}
// 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.nBits += e.width
for e.nBits >= 8 {
}
// 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.nBits += e.width
for e.nBits >= 8 {
// 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.
-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
// unused codes. In the latter case, incHi sends a clear code, resets the
// encoder state and returns errOutOfCodes.
-func (e *encoder) incHi() os.Error {
+func (e *encoder) incHi() error {
e.hi++
if e.hi == e.overflow {
e.width++
}
// 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 {
return 0, e.err
}
// Close closes the encoder, flushing any pending output. It does not close or
// flush e's underlying writer.
-func (e *encoder) Close() os.Error {
+func (e *encoder) Close() error {
if e.err != nil {
if e.err == os.EINVAL {
return nil
// The number of bits to use for literal codes, litWidth, must be in the
// range [2,8] and is typically 8.
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 {
case LSB:
write = (*encoder).writeLSB
case MSB:
write = (*encoder).writeMSB
default:
- return &errWriteCloser{os.NewError("lzw: unknown order")}
+ return &errWriteCloser{errors.New("lzw: unknown order")}
}
if litWidth < 2 || 8 < litWidth {
return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)}
var b [4096]byte
for {
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)
return
}
t.Errorf("%s (order=%d litWidth=%d): %v", fn, order, litWidth, err1)
return
}
- if err0 == os.EOF {
+ if err0 == io.EOF {
break
}
}
import (
"bufio"
"compress/flate"
+ "errors"
"hash"
"hash/adler32"
"io"
- "os"
)
const zlibDeflate = 8
-var ChecksumError = os.NewError("zlib checksum error")
-var HeaderError = os.NewError("invalid zlib header")
-var DictionaryError = os.NewError("invalid zlib dictionary")
+var ChecksumError = errors.New("zlib checksum error")
+var HeaderError = errors.New("invalid zlib header")
+var DictionaryError = errors.New("invalid zlib dictionary")
type reader struct {
r flate.Reader
decompressor io.ReadCloser
digest hash.Hash32
- err os.Error
+ err error
scratch [4]byte
}
// 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.
// 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)
}
// NewReaderDict is like NewReader but uses a preset dictionary.
// 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)
if fr, ok := r.(flate.Reader); ok {
z.r = fr
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 {
return 0, z.err
}
n, err = z.decompressor.Read(p)
z.digest.Write(p[0:n])
- if n != 0 || err != os.EOF {
+ if n != 0 || err != io.EOF {
z.err = err
return
}
}
// 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 {
return z.err
}
import (
"bytes"
"io"
- "os"
"testing"
)
raw string
compressed []byte
dict []byte
- err os.Error
+ err error
}
// Compare-to-golden test data was generated by the ZLIB example program at
import (
"compress/flate"
+ "errors"
"hash"
"hash/adler32"
"io"
- "os"
)
// These constants are copied from the flate package, so that code that imports
w io.Writer
compressor *flate.Writer
digest hash.Hash32
- err os.Error
+ err error
scratch [4]byte
}
// 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)
}
// 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)
}
// level is the compression level, which can be DefaultCompression, NoCompression,
// or any integer value between BestSpeed and BestCompression (inclusive).
// 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)
// 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.
case 7, 8, 9:
z.scratch[1] = 3 << 6
default:
- return nil, os.NewError("level out of range")
+ return nil, errors.New("level out of range")
}
if dict != nil {
z.scratch[1] |= 1 << 5
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 {
return 0, z.err
}
}
// Flush flushes the underlying compressor.
-func (z *Writer) Flush() os.Error {
+func (z *Writer) Flush() error {
if z.err != nil {
return z.err
}
}
// 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 {
return z.err
}
package aes
-import (
- "os"
- "strconv"
-)
+import "strconv"
// The AES block size in bytes.
const BlockSize = 16
type KeySizeError int
-func (k KeySizeError) String() string {
+func (k KeySizeError) Error() string {
return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
}
// The key argument should be the AES key,
// either 16, 24, or 32 bytes to select
// AES-128, AES-192, or AES-256.
-func NewCipher(key []byte) (*Cipher, os.Error) {
+func NewCipher(key []byte) (*Cipher, error) {
k := len(key)
switch k {
default:
package bcrypt
-import (
- "encoding/base64"
- "os"
-)
+import "encoding/base64"
const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
return dst[:n]
}
-func base64Decode(src []byte) ([]byte, os.Error) {
+func base64Decode(src []byte) ([]byte, error) {
numOfEquals := 4 - (len(src) % 4)
for i := 0; i < numOfEquals; i++ {
src = append(src, '=')
"crypto/blowfish"
"crypto/rand"
"crypto/subtle"
+ "errors"
"fmt"
"io"
- "os"
"strconv"
)
// The error returned from CompareHashAndPassword when a password and hash do
// 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
// 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
// a bcrypt algorithm newer than this implementation.
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)
}
// The error returned from CompareHashAndPassword when a hash starts with something other than '$'
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))
}
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))
}
// cost. If the cost given is less than MinCost, the cost will be set to
// MinCost, instead. Use CompareHashAndPassword, as defined in this package,
// 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)
if err != nil {
return nil, err
// CompareHashAndPassword compares a bcrypt hashed password with its possible
// plaintext equivalent. Note: Using bytes.Equal for this job is
// 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)
if err != nil {
return err
return MismatchedHashAndPasswordError
}
-func newFromPassword(password []byte, cost int) (*hashed, os.Error) {
+func newFromPassword(password []byte, cost int) (*hashed, error) {
if cost < MinCost {
cost = DefaultCost
}
return p, err
}
-func newFromHash(hashedSecret []byte) (*hashed, os.Error) {
+func newFromHash(hashedSecret []byte) (*hashed, error) {
if len(hashedSecret) < minHashSize {
return nil, HashTooShortError
}
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))
copy(cipherData, magicCipherData)
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)
if err != nil {
return arr[:n]
}
-func (p *hashed) decodeVersion(sbytes []byte) (int, os.Error) {
+func (p *hashed) decodeVersion(sbytes []byte) (int, error) {
if sbytes[0] != '$' {
return -1, InvalidHashPrefixError(sbytes[0])
}
}
// 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]))
if err != nil {
return -1, err
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 {
return InvalidCostError(cost)
}
import (
"bytes"
- "os"
"testing"
)
}
type InvalidHashTest struct {
- err os.Error
+ err error
hash []byte
}
}
func TestInvalidHashErrors(t *testing.T) {
- check := func(name string, expected, err os.Error) {
+ check := func(name string, expected, err error) {
if err == nil {
t.Errorf("%s: Should have returned an error", name)
}
// The code is a port of Bruce Schneier's C implementation.
// See http://www.schneier.com/blowfish.html.
-import (
- "os"
- "strconv"
-)
+import "strconv"
// The Blowfish block size in bytes.
const BlockSize = 8
type KeySizeError int
-func (k KeySizeError) String() string {
+func (k KeySizeError) Error() string {
return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k))
}
// NewCipher creates and returns a Cipher.
// 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
k := len(key)
if k < 4 || k > 56 {
// schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is
// sufficient and desirable. For bcrypt compatiblity, the key can be over 56
// bytes.
-func NewSaltedCipher(key, salt []byte) (*Cipher, os.Error) {
+func NewSaltedCipher(key, salt []byte) (*Cipher, error) {
var result Cipher
k := len(key)
if k < 4 {
// OpenPGP cipher.
package cast5
-import (
- "os"
-)
+import "errors"
const BlockSize = 8
const KeySize = 16
rotate [16]uint8
}
-func NewCipher(key []byte) (c *Cipher, err os.Error) {
+func NewCipher(key []byte) (c *Cipher, err error) {
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)
package cipher
-import (
- "os"
- "io"
-)
+import "io"
// The Stream* objects are so simple that all their members are public. Users
// can create them themselves.
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)
r.S.XORKeyStream(dst[:n], dst[:n])
return
type StreamWriter struct {
S Stream
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 {
return 0, w.Err
}
return
}
-func (w StreamWriter) Close() os.Error {
+func (w StreamWriter) Close() error {
// This saves us from either requiring a WriteCloser or having a
// StreamWriterCloser.
return w.W.(io.Closer).Close()
package des
-import (
- "os"
- "strconv"
-)
+import "strconv"
// The DES block size in bytes.
const BlockSize = 8
type KeySizeError int
-func (k KeySizeError) String() string {
+func (k KeySizeError) Error() string {
return "crypto/des: invalid key size " + strconv.Itoa(int(k))
}
}
// NewCipher creates and returns a new Cipher.
-func NewCipher(key []byte) (*Cipher, os.Error) {
+func NewCipher(key []byte) (*Cipher, error) {
if len(key) != 8 {
return nil, KeySizeError(len(key))
}
}
// NewCipher creates and returns a new Cipher.
-func NewTripleDESCipher(key []byte) (*TripleDESCipher, os.Error) {
+func NewTripleDESCipher(key []byte) (*TripleDESCipher, error) {
if len(key) != 24 {
return nil, KeySizeError(len(key))
}
import (
"big"
+ "errors"
"io"
- "os"
)
// Parameters represents the domain parameters for a key. These parameters can
type invalidPublicKeyError int
-func (invalidPublicKeyError) String() string {
+func (invalidPublicKeyError) Error() string {
return "crypto/dsa: invalid public key"
}
// GenerateParameters puts a random, valid set of DSA parameters into params.
// 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
// use a verification seed to generate the primes. The verification
// seed doesn't appear to be exported or used by other code and
L = 3072
N = 256
default:
- return os.NewError("crypto/dsa: invalid ParameterSizes")
+ return errors.New("crypto/dsa: invalid ParameterSizes")
}
qBytes := make([]byte, N/8)
// GenerateKey generates a public&private key pair. The Parameters of the
// 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 {
- 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)
// 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
// 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
n := priv.Q.BitLen()
"big"
"crypto/elliptic"
"io"
- "os"
)
// PublicKey represents an ECDSA public key.
// randFieldElement returns a random element of the field underlying the given
// 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)
_, err = io.ReadFull(rand, b)
if err != nil {
}
// 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)
if err != nil {
return
// 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
// 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
c := priv.PublicKey.Curve
import (
"big"
"io"
- "os"
"sync"
)
// GenerateKey returns a public/private key pair. The private key is generated
// 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
priv = make([]byte, byteLen)
"crypto/sha1"
"crypto/sha256"
"hash"
- "os"
)
// FIPS 198:
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)
}
import (
"crypto"
"hash"
- "os"
)
func init() {
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)
d.len += uint64(nn)
if d.nx > 0 {
import (
"crypto"
"hash"
- "os"
)
func init() {
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)
d.len += uint64(nn)
if d.nx > 0 {
_ "crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
- "os"
"time"
)
// ParseError results from an invalid OCSP response.
type ParseError string
-func (p ParseError) String() string {
+func (p ParseError) Error() string {
return string(p)
}
// responses for a single certificate and only those using RSA signatures.
// Non-RSA responses will result in an x509.UnsupportedAlgorithmError.
// 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
rest, err := asn1.Unmarshal(bytes, &resp)
if err != nil {
import (
"bufio"
"bytes"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"encoding/base64"
"io"
- "os"
)
// A Block represents an OpenPGP armored structure.
oReader openpgpReader
}
-var ArmorCorrupt os.Error = error.StructuralError("armor invalid")
+var ArmorCorrupt error = error_.StructuralError("armor invalid")
const crc24Init = 0xb704ce
const crc24Poly = 0x1864cfb
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 {
- return 0, os.EOF
+ return 0, io.EOF
}
if len(l.buf) > 0 {
uint32(expectedBytes[2])
line, _, err = l.in.ReadLine()
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
return
}
if !bytes.HasPrefix(line, armorEnd) {
}
l.eof = true
- return 0, os.EOF
+ return 0, io.EOF
}
if len(line) > 64 {