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 {
currentCRC uint32
}
-func (r *openpgpReader) Read(p []byte) (n int, err os.Error) {
+func (r *openpgpReader) Read(p []byte) (n int, err error) {
n, err = r.b64Reader.Read(p)
r.currentCRC = crc24(r.currentCRC, p[:n])
- if err == os.EOF {
+ if err == io.EOF {
if r.lReader.crc != uint32(r.currentCRC&crc24Mask) {
return 0, ArmorCorrupt
}
// leading garbage. If it doesn't find a block, it will return nil, os.EOF. The
// given Reader is not usable after calling this function: an arbitrary amount
// of data may have been read past the end of the block.
-func Decode(in io.Reader) (p *Block, err os.Error) {
+func Decode(in io.Reader) (p *Block, err error) {
r, _ := bufio.NewReaderSize(in, 100)
var line []byte
ignoreNext := false
import (
"encoding/base64"
"io"
- "os"
)
var armorHeaderSep = []byte(": ")
var armorEndOfLineOut = []byte("-----\n")
// writeSlices writes its arguments to the given Writer.
-func writeSlices(out io.Writer, slices ...[]byte) (err os.Error) {
+func writeSlices(out io.Writer, slices ...[]byte) (err error) {
for _, s := range slices {
_, err = out.Write(s)
if err != nil {
}
}
-func (l *lineBreaker) Write(b []byte) (n int, err os.Error) {
+func (l *lineBreaker) Write(b []byte) (n int, err error) {
n = len(b)
if n == 0 {
return
}
-func (l *lineBreaker) Close() (err os.Error) {
+func (l *lineBreaker) Close() (err error) {
if l.used > 0 {
_, err = l.out.Write(l.line[0:l.used])
if err != nil {
blockType []byte
}
-func (e *encoding) Write(data []byte) (n int, err os.Error) {
+func (e *encoding) Write(data []byte) (n int, err error) {
e.crc = crc24(e.crc, data)
return e.b64.Write(data)
}
-func (e *encoding) Close() (err os.Error) {
+func (e *encoding) Close() (err error) {
err = e.b64.Close()
if err != nil {
return
// Encode returns a WriteCloser which will encode the data written to it in
// OpenPGP armor.
-func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err os.Error) {
+func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) {
bType := []byte(blockType)
err = writeSlices(out, armorStart, bType, armorEndOfLineOut)
if err != nil {
package openpgp
-import (
- "hash"
- "os"
-)
+import "hash"
// NewCanonicalTextHash reformats text written to it into the canonical
// form and then applies the hash h. See RFC 4880, section 5.2.1.
var newline = []byte{'\r', '\n'}
-func (cth *canonicalTextHash) Write(buf []byte) (int, os.Error) {
+func (cth *canonicalTextHash) Write(buf []byte) (int, error) {
start := 0
for i, c := range buf {
import (
"bytes"
- "os"
"testing"
)
buf *bytes.Buffer
}
-func (r recordingHash) Write(b []byte) (n int, err os.Error) {
+func (r recordingHash) Write(b []byte) (n int, err error) {
return r.buf.Write(b)
}
"big"
"crypto/rand"
"crypto/subtle"
+ "errors"
"io"
- "os"
)
// PublicKey represents an ElGamal public key.
// Encrypt encrypts the given message to the given public key. The result is a
// pair of integers. Errors can result from reading random, or because msg is
// too large to be encrypted to the public key.
-func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err os.Error) {
+func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) {
pLen := (pub.P.BitLen() + 7) / 8
if len(msg) > pLen-11 {
- err = os.NewError("elgamal: message too long")
+ err = errors.New("elgamal: message too long")
return
}
// be used to break the cryptosystem. See ``Chosen Ciphertext Attacks
// Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel
// Bleichenbacher, Advances in Cryptology (Crypto '98),
-func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) {
+func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) {
s := new(big.Int).Exp(c1, priv.X, priv.P)
s.ModInverse(s, priv.P)
s.Mul(s, c2)
}
if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 {
- return nil, os.NewError("elgamal: decryption error")
+ return nil, errors.New("elgamal: decryption error")
}
return em[index+1:], nil
}
// nonZeroRandomBytes fills the given slice with non-zero random octets.
-func nonZeroRandomBytes(s []byte, rand io.Reader) (err os.Error) {
+func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
_, err = io.ReadFull(rand, s)
if err != nil {
return
// invalid.
type StructuralError string
-func (s StructuralError) String() string {
+func (s StructuralError) Error() string {
return "OpenPGP data invalid: " + string(s)
}
// makes use of currently unimplemented features.
type UnsupportedError string
-func (s UnsupportedError) String() string {
+func (s UnsupportedError) Error() string {
return "OpenPGP feature unsupported: " + string(s)
}
// incorrect value.
type InvalidArgumentError string
-func (i InvalidArgumentError) String() string {
+func (i InvalidArgumentError) Error() string {
return "OpenPGP argument invalid: " + string(i)
}
// validate.
type SignatureError string
-func (b SignatureError) String() string {
+func (b SignatureError) Error() string {
return "OpenPGP signature invalid: " + string(b)
}
type keyIncorrectError int
-func (ki keyIncorrectError) String() string {
+func (ki keyIncorrectError) Error() string {
return "the given key was incorrect"
}
type unknownIssuerError int
-func (unknownIssuerError) String() string {
+func (unknownIssuerError) Error() string {
return "signature make by unknown entity"
}
type UnknownPacketTypeError uint8
-func (upte UnknownPacketTypeError) String() string {
+func (upte UnknownPacketTypeError) Error() string {
return "unknown OpenPGP packet type: " + strconv.Itoa(int(upte))
}
import (
"crypto"
"crypto/openpgp/armor"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/packet"
"crypto/rsa"
"io"
- "os"
"time"
)
}
// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file.
-func ReadArmoredKeyRing(r io.Reader) (EntityList, os.Error) {
+func ReadArmoredKeyRing(r io.Reader) (EntityList, error) {
block, err := armor.Decode(r)
- if err == os.EOF {
- return nil, error.InvalidArgumentError("no armored data found")
+ if err == io.EOF {
+ return nil, error_.InvalidArgumentError("no armored data found")
}
if err != nil {
return nil, err
}
if block.Type != PublicKeyType && block.Type != PrivateKeyType {
- return nil, error.InvalidArgumentError("expected public or private key block, got: " + block.Type)
+ return nil, error_.InvalidArgumentError("expected public or private key block, got: " + block.Type)
}
return ReadKeyRing(block.Body)
// ReadKeyRing reads one or more public/private keys. Unsupported keys are
// ignored as long as at least a single valid key is found.
-func ReadKeyRing(r io.Reader) (el EntityList, err os.Error) {
+func ReadKeyRing(r io.Reader) (el EntityList, err error) {
packets := packet.NewReader(r)
- var lastUnsupportedError os.Error
+ var lastUnsupportedError error
for {
var e *Entity
e, err = readEntity(packets)
if err != nil {
- if _, ok := err.(error.UnsupportedError); ok {
+ if _, ok := err.(error_.UnsupportedError); ok {
lastUnsupportedError = err
err = readToNextPublicKey(packets)
}
- if err == os.EOF {
+ if err == io.EOF {
err = nil
break
}
// readToNextPublicKey reads packets until the start of the entity and leaves
// the first packet of the new entity in the Reader.
-func readToNextPublicKey(packets *packet.Reader) (err os.Error) {
+func readToNextPublicKey(packets *packet.Reader) (err error) {
var p packet.Packet
for {
p, err = packets.Next()
- if err == os.EOF {
+ if err == io.EOF {
return
} else if err != nil {
- if _, ok := err.(error.UnsupportedError); ok {
+ if _, ok := err.(error_.UnsupportedError); ok {
err = nil
continue
}
// readEntity reads an entity (public key, identities, subkeys etc) from the
// given Reader.
-func readEntity(packets *packet.Reader) (*Entity, os.Error) {
+func readEntity(packets *packet.Reader) (*Entity, error) {
e := new(Entity)
e.Identities = make(map[string]*Identity)
if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
packets.Unread(p)
- return nil, error.StructuralError("first packet was not a public/private key")
+ return nil, error_.StructuralError("first packet was not a public/private key")
} else {
e.PrimaryKey = &e.PrivateKey.PublicKey
}
}
if !e.PrimaryKey.PubKeyAlgo.CanSign() {
- return nil, error.StructuralError("primary key cannot be used for signatures")
+ return nil, error_.StructuralError("primary key cannot be used for signatures")
}
var current *Identity
EachPacket:
for {
p, err := packets.Next()
- if err == os.EOF {
+ if err == io.EOF {
break
} else if err != nil {
return nil, err
for {
p, err = packets.Next()
- if err == os.EOF {
+ if err == io.EOF {
return nil, io.ErrUnexpectedEOF
} else if err != nil {
return nil, err
sig, ok := p.(*packet.Signature)
if !ok {
- return nil, error.StructuralError("user ID packet not followed by self-signature")
+ return nil, error_.StructuralError("user ID packet not followed by self-signature")
}
if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil {
- return nil, error.StructuralError("user ID self-signature invalid: " + err.String())
+ return nil, error_.StructuralError("user ID self-signature invalid: " + err.Error())
}
current.SelfSignature = sig
break
}
case *packet.Signature:
if current == nil {
- return nil, error.StructuralError("signature packet found before user id packet")
+ return nil, error_.StructuralError("signature packet found before user id packet")
}
current.Signatures = append(current.Signatures, pkt)
case *packet.PrivateKey:
}
if len(e.Identities) == 0 {
- return nil, error.StructuralError("entity without any identities")
+ return nil, error_.StructuralError("entity without any identities")
}
return e, nil
}
-func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) os.Error {
+func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
var subKey Subkey
subKey.PublicKey = pub
subKey.PrivateKey = priv
p, err := packets.Next()
- if err == os.EOF {
+ if err == io.EOF {
return io.ErrUnexpectedEOF
}
if err != nil {
- return error.StructuralError("subkey signature invalid: " + err.String())
+ return error_.StructuralError("subkey signature invalid: " + err.Error())
}
var ok bool
subKey.Sig, ok = p.(*packet.Signature)
if !ok {
- return error.StructuralError("subkey packet not followed by signature")
+ return error_.StructuralError("subkey packet not followed by signature")
}
if subKey.Sig.SigType != packet.SigTypeSubkeyBinding {
- return error.StructuralError("subkey signature with wrong type")
+ return error_.StructuralError("subkey signature with wrong type")
}
err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
if err != nil {
- return error.StructuralError("subkey signature invalid: " + err.String())
+ return error_.StructuralError("subkey signature invalid: " + err.Error())
}
e.Subkeys = append(e.Subkeys, subKey)
return nil
// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
// single identity composed of the given full name, comment and email, any of
// which may be empty but must not contain any of "()<>\x00".
-func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, os.Error) {
+func NewEntity(rand io.Reader, currentTimeSecs int64, name, comment, email string) (*Entity, error) {
uid := packet.NewUserId(name, comment, email)
if uid == nil {
- return nil, error.InvalidArgumentError("user id field contained invalid characters")
+ return nil, error_.InvalidArgumentError("user id field contained invalid characters")
}
signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits)
if err != nil {
// SerializePrivate serializes an Entity, including private key material, to
// the given Writer. For now, it must only be used on an Entity returned from
// NewEntity.
-func (e *Entity) SerializePrivate(w io.Writer) (err os.Error) {
+func (e *Entity) SerializePrivate(w io.Writer) (err error) {
err = e.PrivateKey.Serialize(w)
if err != nil {
return
// Serialize writes the public part of the given Entity to w. (No private
// key material will be output).
-func (e *Entity) Serialize(w io.Writer) os.Error {
+func (e *Entity) Serialize(w io.Writer) error {
err := e.PrimaryKey.Serialize(w)
if err != nil {
return err
// associated with e. The provided identity must already be an element of
// e.Identities and the private key of signer must have been decrypted if
// necessary.
-func (e *Entity) SignIdentity(identity string, signer *Entity) os.Error {
+func (e *Entity) SignIdentity(identity string, signer *Entity) error {
if signer.PrivateKey == nil {
- return error.InvalidArgumentError("signing Entity must have a private key")
+ return error_.InvalidArgumentError("signing Entity must have a private key")
}
if signer.PrivateKey.Encrypted {
- return error.InvalidArgumentError("signing Entity's private key must be decrypted")
+ return error_.InvalidArgumentError("signing Entity's private key must be decrypted")
}
ident, ok := e.Identities[identity]
if !ok {
- return error.InvalidArgumentError("given identity string not found in Entity")
+ return error_.InvalidArgumentError("given identity string not found in Entity")
}
sig := &packet.Signature{
import (
"compress/flate"
"compress/zlib"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"io"
- "os"
"strconv"
)
Body io.Reader
}
-func (c *Compressed) parse(r io.Reader) os.Error {
+func (c *Compressed) parse(r io.Reader) error {
var buf [1]byte
_, err := readFull(r, buf[:])
if err != nil {
case 2:
c.Body, err = zlib.NewReader(r)
default:
- err = error.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0])))
+ err = error_.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0])))
}
return err
import (
"bytes"
"encoding/hex"
- "os"
+ "io"
"io/ioutil"
"testing"
)
}
contents, err := ioutil.ReadAll(c.Body)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
t.Error(err)
return
}
import (
"big"
"crypto/openpgp/elgamal"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/rand"
"crypto/rsa"
"encoding/binary"
"io"
- "os"
"strconv"
)
encryptedMPI1, encryptedMPI2 []byte
}
-func (e *EncryptedKey) parse(r io.Reader) (err os.Error) {
+func (e *EncryptedKey) parse(r io.Reader) (err error) {
var buf [10]byte
_, err = readFull(r, buf[:])
if err != nil {
return
}
if buf[0] != encryptedKeyVersion {
- return error.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0])))
+ return error_.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0])))
}
e.KeyId = binary.BigEndian.Uint64(buf[1:9])
e.Algo = PublicKeyAlgorithm(buf[9])
// Decrypt decrypts an encrypted session key with the given private key. The
// private key must have been decrypted first.
-func (e *EncryptedKey) Decrypt(priv *PrivateKey) os.Error {
- var err os.Error
+func (e *EncryptedKey) Decrypt(priv *PrivateKey) error {
+ var err error
var b []byte
// TODO(agl): use session key decryption routines here to avoid
c2 := new(big.Int).SetBytes(e.encryptedMPI2)
b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2)
default:
- err = error.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
+ err = error_.InvalidArgumentError("cannot decrypted encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo)))
}
if err != nil {
expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1])
checksum := checksumKeyMaterial(e.Key)
if checksum != expectedChecksum {
- return error.StructuralError("EncryptedKey checksum incorrect")
+ return error_.StructuralError("EncryptedKey checksum incorrect")
}
return nil
// SerializeEncryptedKey serializes an encrypted key packet to w that contains
// key, encrypted to pub.
-func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFunc CipherFunction, key []byte) os.Error {
+func SerializeEncryptedKey(w io.Writer, rand io.Reader, pub *PublicKey, cipherFunc CipherFunction, key []byte) error {
var buf [10]byte
buf[0] = encryptedKeyVersion
binary.BigEndian.PutUint64(buf[1:9], pub.KeyId)
case PubKeyAlgoElGamal:
return serializeEncryptedKeyElGamal(w, rand, buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock)
case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly:
- return error.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
+ return error_.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
}
- return error.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
+ return error_.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo)))
}
-func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) os.Error {
+func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error {
cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock)
if err != nil {
- return error.InvalidArgumentError("RSA encryption failed: " + err.String())
+ return error_.InvalidArgumentError("RSA encryption failed: " + err.Error())
}
packetLen := 10 /* header length */ + 2 /* mpi size */ + len(cipherText)
return writeMPI(w, 8*uint16(len(cipherText)), cipherText)
}
-func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) os.Error {
+func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error {
c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock)
if err != nil {
- return error.InvalidArgumentError("ElGamal encryption failed: " + err.String())
+ return error_.InvalidArgumentError("ElGamal encryption failed: " + err.Error())
}
packetLen := 10 /* header length */
import (
"encoding/binary"
"io"
- "os"
)
// LiteralData represents an encrypted file. See RFC 4880, section 5.9.
return l.FileName == "_CONSOLE"
}
-func (l *LiteralData) parse(r io.Reader) (err os.Error) {
+func (l *LiteralData) parse(r io.Reader) (err error) {
var buf [256]byte
_, err = readFull(r, buf[:2])
// SerializeLiteral serializes a literal data packet to w and returns a
// WriteCloser to which the data itself can be written and which MUST be closed
// on completion. The fileName is truncated to 255 bytes.
-func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err os.Error) {
+func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) {
var buf [4]byte
buf[0] = 't'
if isBinary {
import (
"crypto"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/s2k"
"encoding/binary"
"io"
- "os"
"strconv"
)
const onePassSignatureVersion = 3
-func (ops *OnePassSignature) parse(r io.Reader) (err os.Error) {
+func (ops *OnePassSignature) parse(r io.Reader) (err error) {
var buf [13]byte
_, err = readFull(r, buf[:])
return
}
if buf[0] != onePassSignatureVersion {
- err = error.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0])))
+ err = error_.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0])))
}
var ok bool
ops.Hash, ok = s2k.HashIdToHash(buf[2])
if !ok {
- return error.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2])))
+ return error_.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2])))
}
ops.SigType = SignatureType(buf[1])
}
// Serialize marshals the given OnePassSignature to w.
-func (ops *OnePassSignature) Serialize(w io.Writer) os.Error {
+func (ops *OnePassSignature) Serialize(w io.Writer) error {
var buf [13]byte
buf[0] = onePassSignatureVersion
buf[1] = uint8(ops.SigType)
var ok bool
buf[2], ok = s2k.HashToHashId(ops.Hash)
if !ok {
- return error.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash)))
+ return error_.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash)))
}
buf[3] = uint8(ops.PubKeyAlgo)
binary.BigEndian.PutUint64(buf[4:12], ops.KeyId)
"crypto/aes"
"crypto/cast5"
"crypto/cipher"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"io"
- "os"
)
// readFull is the same as io.ReadFull except that reading zero bytes returns
// ErrUnexpectedEOF rather than EOF.
-func readFull(r io.Reader, buf []byte) (n int, err os.Error) {
+func readFull(r io.Reader, buf []byte) (n int, err error) {
n, err = io.ReadFull(r, buf)
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return
}
// readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2.
-func readLength(r io.Reader) (length int64, isPartial bool, err os.Error) {
+func readLength(r io.Reader) (length int64, isPartial bool, err error) {
var buf [4]byte
_, err = readFull(r, buf[:1])
if err != nil {
isPartial bool
}
-func (r *partialLengthReader) Read(p []byte) (n int, err os.Error) {
+func (r *partialLengthReader) Read(p []byte) (n int, err error) {
for r.remaining == 0 {
if !r.isPartial {
- return 0, os.EOF
+ return 0, io.EOF
}
r.remaining, r.isPartial, err = readLength(r.r)
if err != nil {
n, err = r.r.Read(p[:int(toRead)])
r.remaining -= int64(n)
- if n < int(toRead) && err == os.EOF {
+ if n < int(toRead) && err == io.EOF {
err = io.ErrUnexpectedEOF
}
return
lengthByte [1]byte
}
-func (w *partialLengthWriter) Write(p []byte) (n int, err os.Error) {
+func (w *partialLengthWriter) Write(p []byte) (n int, err error) {
for len(p) > 0 {
for power := uint(14); power < 32; power-- {
l := 1 << power
return
}
-func (w *partialLengthWriter) Close() os.Error {
+func (w *partialLengthWriter) Close() error {
w.lengthByte[0] = 0
_, err := w.w.Write(w.lengthByte[:])
if err != nil {
n int64
}
-func (l *spanReader) Read(p []byte) (n int, err os.Error) {
+func (l *spanReader) Read(p []byte) (n int, err error) {
if l.n <= 0 {
- return 0, os.EOF
+ return 0, io.EOF
}
if int64(len(p)) > l.n {
p = p[0:l.n]
}
n, err = l.r.Read(p)
l.n -= int64(n)
- if l.n > 0 && err == os.EOF {
+ if l.n > 0 && err == io.EOF {
err = io.ErrUnexpectedEOF
}
return
// readHeader parses a packet header and returns an io.Reader which will return
// the contents of the packet. See RFC 4880, section 4.2.
-func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err os.Error) {
+func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) {
var buf [4]byte
_, err = io.ReadFull(r, buf[:1])
if err != nil {
return
}
if buf[0]&0x80 == 0 {
- err = error.StructuralError("tag byte does not have MSB set")
+ err = error_.StructuralError("tag byte does not have MSB set")
return
}
if buf[0]&0x40 == 0 {
// serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section
// 4.2.
-func serializeHeader(w io.Writer, ptype packetType, length int) (err os.Error) {
+func serializeHeader(w io.Writer, ptype packetType, length int) (err error) {
var buf [6]byte
var n int
// serializeStreamHeader writes an OpenPGP packet header to w where the
// length of the packet is unknown. It returns a io.WriteCloser which can be
// used to write the contents of the packet. See RFC 4880, section 4.2.
-func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err os.Error) {
+func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) {
var buf [1]byte
buf[0] = 0x80 | 0x40 | byte(ptype)
_, err = w.Write(buf[:])
// Packet represents an OpenPGP packet. Users are expected to try casting
// instances of this interface to specific packet types.
type Packet interface {
- parse(io.Reader) os.Error
+ parse(io.Reader) error
}
// consumeAll reads from the given Reader until error, returning the number of
// bytes read.
-func consumeAll(r io.Reader) (n int64, err os.Error) {
+func consumeAll(r io.Reader) (n int64, err error) {
var m int
var buf [1024]byte
for {
m, err = r.Read(buf[:])
n += int64(m)
- if err == os.EOF {
+ if err == io.EOF {
err = nil
return
}
// Read reads a single OpenPGP packet from the given io.Reader. If there is an
// error parsing a packet, the whole packet is consumed from the input.
-func Read(r io.Reader) (p Packet, err os.Error) {
+func Read(r io.Reader) (p Packet, err error) {
tag, _, contents, err := readHeader(r)
if err != nil {
return
se.MDC = true
p = se
default:
- err = error.UnknownPacketTypeError(tag)
+ err = error_.UnknownPacketTypeError(tag)
}
if p != nil {
err = p.parse(contents)
// readMPI reads a big integer from r. The bit length returned is the bit
// length that was specified in r. This is preserved so that the integer can be
// reserialized exactly.
-func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err os.Error) {
+func readMPI(r io.Reader) (mpi []byte, bitLength uint16, err error) {
var buf [2]byte
_, err = readFull(r, buf[0:])
if err != nil {
}
// writeMPI serializes a big integer to w.
-func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err os.Error) {
+func writeMPI(w io.Writer, bitLength uint16, mpiBytes []byte) (err error) {
_, err = w.Write([]byte{byte(bitLength >> 8), byte(bitLength)})
if err == nil {
_, err = w.Write(mpiBytes)
}
// writeBig serializes a *big.Int to w.
-func writeBig(w io.Writer, i *big.Int) os.Error {
+func writeBig(w io.Writer, i *big.Int) error {
return writeMPI(w, uint16(i.BitLen()), i.Bytes())
}
import (
"bytes"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
- "os"
"testing"
)
hexInput string
length int64
isPartial bool
- err os.Error
+ err error
}{
{"", 0, false, io.ErrUnexpectedEOF},
{"1f", 31, false, nil},
var partialLengthReaderTests = []struct {
hexInput string
- err os.Error
+ err error
hexOutput string
}{
{"e0", io.ErrUnexpectedEOF, ""},
for i, test := range readHeaderTests {
tag, length, contents, err := readHeader(readerFromHex(test.hexInput))
if test.structuralError {
- if _, ok := err.(error.StructuralError); ok {
+ if _, ok := err.(error_.StructuralError); ok {
continue
}
t.Errorf("%d: expected StructuralError, got:%s", i, err)
continue
}
if err != nil {
- if len(test.hexInput) == 0 && err == os.EOF {
+ if len(test.hexInput) == 0 && err == io.EOF {
continue
}
if !test.unexpectedEOF || err != io.ErrUnexpectedEOF {
"crypto/cipher"
"crypto/dsa"
"crypto/openpgp/elgamal"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/s2k"
"crypto/rsa"
"crypto/sha1"
"io"
"io/ioutil"
- "os"
"strconv"
)
return pk
}
-func (pk *PrivateKey) parse(r io.Reader) (err os.Error) {
+func (pk *PrivateKey) parse(r io.Reader) (err error) {
err = (&pk.PublicKey).parse(r)
if err != nil {
return
pk.sha1Checksum = true
}
default:
- return error.UnsupportedError("deprecated s2k function in private key")
+ return error_.UnsupportedError("deprecated s2k function in private key")
}
if pk.Encrypted {
blockSize := pk.cipher.blockSize()
if blockSize == 0 {
- return error.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
+ return error_.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
}
pk.iv = make([]byte, blockSize)
_, err = readFull(r, pk.iv)
return h
}
-func (pk *PrivateKey) Serialize(w io.Writer) (err os.Error) {
+func (pk *PrivateKey) Serialize(w io.Writer) (err error) {
// TODO(agl): support encrypted private keys
buf := bytes.NewBuffer(nil)
err = pk.PublicKey.serializeWithoutHeaders(buf)
case *rsa.PrivateKey:
err = serializeRSAPrivateKey(privateKeyBuf, priv)
default:
- err = error.InvalidArgumentError("non-RSA private key")
+ err = error_.InvalidArgumentError("non-RSA private key")
}
if err != nil {
return
return
}
-func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) os.Error {
+func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error {
err := writeBig(w, priv.D)
if err != nil {
return err
}
// Decrypt decrypts an encrypted private key using a passphrase.
-func (pk *PrivateKey) Decrypt(passphrase []byte) os.Error {
+func (pk *PrivateKey) Decrypt(passphrase []byte) error {
if !pk.Encrypted {
return nil
}
if pk.sha1Checksum {
if len(data) < sha1.Size {
- return error.StructuralError("truncated private key data")
+ return error_.StructuralError("truncated private key data")
}
h := sha1.New()
h.Write(data[:len(data)-sha1.Size])
sum := h.Sum()
if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
- return error.StructuralError("private key checksum failure")
+ return error_.StructuralError("private key checksum failure")
}
data = data[:len(data)-sha1.Size]
} else {
if len(data) < 2 {
- return error.StructuralError("truncated private key data")
+ return error_.StructuralError("truncated private key data")
}
var sum uint16
for i := 0; i < len(data)-2; i++ {
}
if data[len(data)-2] != uint8(sum>>8) ||
data[len(data)-1] != uint8(sum) {
- return error.StructuralError("private key checksum failure")
+ return error_.StructuralError("private key checksum failure")
}
data = data[:len(data)-2]
}
return pk.parsePrivateKey(data)
}
-func (pk *PrivateKey) parsePrivateKey(data []byte) (err os.Error) {
+func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) {
switch pk.PublicKey.PubKeyAlgo {
case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly:
return pk.parseRSAPrivateKey(data)
panic("impossible")
}
-func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err os.Error) {
+func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) {
rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
rsaPriv := new(rsa.PrivateKey)
rsaPriv.PublicKey = *rsaPub
return nil
}
-func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err os.Error) {
+func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) {
dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey)
dsaPriv := new(dsa.PrivateKey)
dsaPriv.PublicKey = *dsaPub
return nil
}
-func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err os.Error) {
+func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) {
pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey)
priv := new(elgamal.PrivateKey)
priv.PublicKey = *pub
"big"
"crypto/dsa"
"crypto/openpgp/elgamal"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/rsa"
"crypto/sha1"
"encoding/binary"
"fmt"
"hash"
"io"
- "os"
"strconv"
)
return pk
}
-func (pk *PublicKey) parse(r io.Reader) (err os.Error) {
+func (pk *PublicKey) parse(r io.Reader) (err error) {
// RFC 4880, section 5.5.2
var buf [6]byte
_, err = readFull(r, buf[:])
return
}
if buf[0] != 4 {
- return error.UnsupportedError("public key version")
+ return error_.UnsupportedError("public key version")
}
pk.CreationTime = uint32(buf[1])<<24 | uint32(buf[2])<<16 | uint32(buf[3])<<8 | uint32(buf[4])
pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5])
case PubKeyAlgoElGamal:
err = pk.parseElGamal(r)
default:
- err = error.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
+ err = error_.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
}
if err != nil {
return
// parseRSA parses RSA public key material from the given Reader. See RFC 4880,
// section 5.5.2.
-func (pk *PublicKey) parseRSA(r io.Reader) (err os.Error) {
+func (pk *PublicKey) parseRSA(r io.Reader) (err error) {
pk.n.bytes, pk.n.bitLength, err = readMPI(r)
if err != nil {
return
}
if len(pk.e.bytes) > 3 {
- err = error.UnsupportedError("large public exponent")
+ err = error_.UnsupportedError("large public exponent")
return
}
rsa := &rsa.PublicKey{
// parseDSA parses DSA public key material from the given Reader. See RFC 4880,
// section 5.5.2.
-func (pk *PublicKey) parseDSA(r io.Reader) (err os.Error) {
+func (pk *PublicKey) parseDSA(r io.Reader) (err error) {
pk.p.bytes, pk.p.bitLength, err = readMPI(r)
if err != nil {
return
// parseElGamal parses ElGamal public key material from the given Reader. See
// RFC 4880, section 5.5.2.
-func (pk *PublicKey) parseElGamal(r io.Reader) (err os.Error) {
+func (pk *PublicKey) parseElGamal(r io.Reader) (err error) {
pk.p.bytes, pk.p.bitLength, err = readMPI(r)
if err != nil {
return
return
}
-func (pk *PublicKey) Serialize(w io.Writer) (err os.Error) {
+func (pk *PublicKey) Serialize(w io.Writer) (err error) {
length := 6 // 6 byte header
switch pk.PubKeyAlgo {
// serializeWithoutHeaders marshals the PublicKey to w in the form of an
// OpenPGP public key packet, not including the packet header.
-func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err os.Error) {
+func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) {
var buf [6]byte
buf[0] = 4
buf[1] = byte(pk.CreationTime >> 24)
case PubKeyAlgoElGamal:
return writeMPIs(w, pk.p, pk.g, pk.y)
}
- return error.InvalidArgumentError("bad public-key algorithm")
+ return error_.InvalidArgumentError("bad public-key algorithm")
}
// CanSign returns true iff this public key can generate signatures
// VerifySignature returns nil iff sig is a valid signature, made by this
// public key, of the data hashed into signed. signed is mutated by this call.
-func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err os.Error) {
+func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
if !pk.CanSign() {
- return error.InvalidArgumentError("public key cannot generate signatures")
+ return error_.InvalidArgumentError("public key cannot generate signatures")
}
signed.Write(sig.HashSuffix)
hashBytes := signed.Sum()
if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
- return error.SignatureError("hash tag doesn't match")
+ return error_.SignatureError("hash tag doesn't match")
}
if pk.PubKeyAlgo != sig.PubKeyAlgo {
- return error.InvalidArgumentError("public key and signature use different algorithms")
+ return error_.InvalidArgumentError("public key and signature use different algorithms")
}
switch pk.PubKeyAlgo {
rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
if err != nil {
- return error.SignatureError("RSA verification failure")
+ return error_.SignatureError("RSA verification failure")
}
return nil
case PubKeyAlgoDSA:
dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
- return error.SignatureError("DSA verification failure")
+ return error_.SignatureError("DSA verification failure")
}
return nil
default:
// keySignatureHash returns a Hash of the message that needs to be signed for
// pk to assert a subkey relationship to signed.
-func keySignatureHash(pk, signed *PublicKey, sig *Signature) (h hash.Hash, err os.Error) {
+func keySignatureHash(pk, signed *PublicKey, sig *Signature) (h hash.Hash, err error) {
h = sig.Hash.New()
if h == nil {
- return nil, error.UnsupportedError("hash function")
+ return nil, error_.UnsupportedError("hash function")
}
// RFC 4880, section 5.2.4
// VerifyKeySignature returns nil iff sig is a valid signature, made by this
// public key, of signed.
-func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) (err os.Error) {
+func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) (err error) {
h, err := keySignatureHash(pk, signed, sig)
if err != nil {
return err
// userIdSignatureHash returns a Hash of the message that needs to be signed
// to assert that pk is a valid key for id.
-func userIdSignatureHash(id string, pk *PublicKey, sig *Signature) (h hash.Hash, err os.Error) {
+func userIdSignatureHash(id string, pk *PublicKey, sig *Signature) (h hash.Hash, err error) {
h = sig.Hash.New()
if h == nil {
- return nil, error.UnsupportedError("hash function")
+ return nil, error_.UnsupportedError("hash function")
}
// RFC 4880, section 5.2.4
// VerifyUserIdSignature returns nil iff sig is a valid signature, made by this
// public key, of id.
-func (pk *PublicKey) VerifyUserIdSignature(id string, sig *Signature) (err os.Error) {
+func (pk *PublicKey) VerifyUserIdSignature(id string, sig *Signature) (err error) {
h, err := userIdSignatureHash(id, pk, sig)
if err != nil {
return err
// writeMPIs is a utility function for serializing several big integers to the
// given Writer.
-func writeMPIs(w io.Writer, mpis ...parsedMPI) (err os.Error) {
+func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) {
for _, mpi := range mpis {
err = writeMPI(w, mpi.bitLength, mpi.bytes)
if err != nil {
package packet
import (
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"io"
- "os"
)
// Reader reads packets from an io.Reader and allows packets to be 'unread' so
// Next returns the most recently unread Packet, or reads another packet from
// the top-most io.Reader. Unknown packet types are skipped.
-func (r *Reader) Next() (p Packet, err os.Error) {
+func (r *Reader) Next() (p Packet, err error) {
if len(r.q) > 0 {
p = r.q[len(r.q)-1]
r.q = r.q[:len(r.q)-1]
if err == nil {
return
}
- if err == os.EOF {
+ if err == io.EOF {
r.readers = r.readers[:len(r.readers)-1]
continue
}
- if _, ok := err.(error.UnknownPacketTypeError); !ok {
+ if _, ok := err.(error_.UnknownPacketTypeError); !ok {
return nil, err
}
}
- return nil, os.EOF
+ return nil, io.EOF
}
// Push causes the Reader to start reading from a new io.Reader. When an EOF
import (
"crypto"
"crypto/dsa"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/s2k"
"crypto/rand"
"crypto/rsa"
"encoding/binary"
"hash"
"io"
- "os"
"strconv"
)
outSubpackets []outputSubpacket
}
-func (sig *Signature) parse(r io.Reader) (err os.Error) {
+func (sig *Signature) parse(r io.Reader) (err error) {
// RFC 4880, section 5.2.3
var buf [5]byte
_, err = readFull(r, buf[:1])
return
}
if buf[0] != 4 {
- err = error.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
+ err = error_.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
return
}
switch sig.PubKeyAlgo {
case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA:
default:
- err = error.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
+ err = error_.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
return
}
var ok bool
sig.Hash, ok = s2k.HashIdToHash(buf[2])
if !ok {
- return error.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
+ return error_.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
}
hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4])
// parseSignatureSubpackets parses subpackets of the main signature packet. See
// RFC 4880, section 5.2.3.1.
-func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err os.Error) {
+func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
for len(subpackets) > 0 {
subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
if err != nil {
}
if sig.CreationTime == 0 {
- err = error.StructuralError("no creation time in signature")
+ err = error_.StructuralError("no creation time in signature")
}
return
)
// parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1.
-func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err os.Error) {
+func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
// RFC 4880, section 5.2.3.1
var (
length uint32
rest = subpacket[length:]
subpacket = subpacket[:length]
if len(subpacket) == 0 {
- err = error.StructuralError("zero length signature subpacket")
+ err = error_.StructuralError("zero length signature subpacket")
return
}
packetType = signatureSubpacketType(subpacket[0] & 0x7f)
switch packetType {
case creationTimeSubpacket:
if !isHashed {
- err = error.StructuralError("signature creation time in non-hashed area")
+ err = error_.StructuralError("signature creation time in non-hashed area")
return
}
if len(subpacket) != 4 {
- err = error.StructuralError("signature creation time not four bytes")
+ err = error_.StructuralError("signature creation time not four bytes")
return
}
sig.CreationTime = binary.BigEndian.Uint32(subpacket)
return
}
if len(subpacket) != 4 {
- err = error.StructuralError("expiration subpacket with bad length")
+ err = error_.StructuralError("expiration subpacket with bad length")
return
}
sig.SigLifetimeSecs = new(uint32)
return
}
if len(subpacket) != 4 {
- err = error.StructuralError("key expiration subpacket with bad length")
+ err = error_.StructuralError("key expiration subpacket with bad length")
return
}
sig.KeyLifetimeSecs = new(uint32)
case issuerSubpacket:
// Issuer, section 5.2.3.5
if len(subpacket) != 8 {
- err = error.StructuralError("issuer subpacket with bad length")
+ err = error_.StructuralError("issuer subpacket with bad length")
return
}
sig.IssuerKeyId = new(uint64)
return
}
if len(subpacket) != 1 {
- err = error.StructuralError("primary user id subpacket with bad length")
+ err = error_.StructuralError("primary user id subpacket with bad length")
return
}
sig.IsPrimaryId = new(bool)
return
}
if len(subpacket) == 0 {
- err = error.StructuralError("empty key flags subpacket")
+ err = error_.StructuralError("empty key flags subpacket")
return
}
sig.FlagsValid = true
default:
if isCritical {
- err = error.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
+ err = error_.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
return
}
}
return
Truncated:
- err = error.StructuralError("signature subpacket truncated")
+ err = error_.StructuralError("signature subpacket truncated")
return
}
}
// buildHashSuffix constructs the HashSuffix member of sig in preparation for signing.
-func (sig *Signature) buildHashSuffix() (err os.Error) {
+func (sig *Signature) buildHashSuffix() (err error) {
hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
var ok bool
sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash)
if !ok {
sig.HashSuffix = nil
- return error.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
+ return error_.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
}
sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8)
sig.HashSuffix[5] = byte(hashedSubpacketsLen)
return
}
-func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err os.Error) {
+func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) {
err = sig.buildHashSuffix()
if err != nil {
return
// Sign signs a message with a private key. The hash, h, must contain
// the hash of the message to be signed and will be mutated by this function.
// On success, the signature is stored in sig. Call Serialize to write it out.
-func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err os.Error) {
+func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey) (err error) {
sig.outSubpackets = sig.buildSubpackets()
digest, err := sig.signPrepareHash(h)
if err != nil {
sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes))
}
default:
- err = error.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
+ err = error_.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
}
return
// SignUserId computes a signature from priv, asserting that pub is a valid
// key for the identity id. On success, the signature is stored in sig. Call
// Serialize to write it out.
-func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey) os.Error {
+func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey) error {
h, err := userIdSignatureHash(id, pub, sig)
if err != nil {
return nil
// SignKey computes a signature from priv, asserting that pub is a subkey. On
// success, the signature is stored in sig. Call Serialize to write it out.
-func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey) os.Error {
+func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey) error {
h, err := keySignatureHash(&priv.PublicKey, pub, sig)
if err != nil {
return err
}
// Serialize marshals sig to w. SignRSA or SignDSA must have been called first.
-func (sig *Signature) Serialize(w io.Writer) (err os.Error) {
+func (sig *Signature) Serialize(w io.Writer) (err error) {
if len(sig.outSubpackets) == 0 {
sig.outSubpackets = sig.rawSubpackets
}
if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil {
- return error.InvalidArgumentError("Signature: need to call SignRSA or SignDSA before Serialize")
+ return error_.InvalidArgumentError("Signature: need to call SignRSA or SignDSA before Serialize")
}
sigLength := 0
import (
"bytes"
"crypto/cipher"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/s2k"
"io"
- "os"
"strconv"
)
const symmetricKeyEncryptedVersion = 4
-func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err os.Error) {
+func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err error) {
// RFC 4880, section 5.3.
var buf [2]byte
_, err = readFull(r, buf[:])
return
}
if buf[0] != symmetricKeyEncryptedVersion {
- return error.UnsupportedError("SymmetricKeyEncrypted version")
+ return error_.UnsupportedError("SymmetricKeyEncrypted version")
}
ske.CipherFunc = CipherFunction(buf[1])
if ske.CipherFunc.KeySize() == 0 {
- return error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1])))
+ return error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1])))
}
ske.s2k, err = s2k.Parse(r)
err = nil
if n != 0 {
if n == maxSessionKeySizeInBytes {
- return error.UnsupportedError("oversized encrypted session key")
+ return error_.UnsupportedError("oversized encrypted session key")
}
ske.encryptedKey = encryptedKey[:n]
}
// Decrypt attempts to decrypt an encrypted session key. If it returns nil,
// ske.Key will contain the session key.
-func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) os.Error {
+func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) error {
if !ske.Encrypted {
return nil
}
c.XORKeyStream(ske.encryptedKey, ske.encryptedKey)
ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
if ske.CipherFunc.blockSize() == 0 {
- return error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc)))
+ return error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc)))
}
ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
ske.Key = ske.encryptedKey[1:]
if len(ske.Key)%ske.CipherFunc.blockSize() != 0 {
ske.Key = nil
- return error.StructuralError("length of decrypted key not a multiple of block size")
+ return error_.StructuralError("length of decrypted key not a multiple of block size")
}
}
// packet contains a random session key, encrypted by a key derived from the
// given passphrase. The session key is returned and must be passed to
// SerializeSymmetricallyEncrypted.
-func SerializeSymmetricKeyEncrypted(w io.Writer, rand io.Reader, passphrase []byte, cipherFunc CipherFunction) (key []byte, err os.Error) {
+func SerializeSymmetricKeyEncrypted(w io.Writer, rand io.Reader, passphrase []byte, cipherFunc CipherFunction) (key []byte, err error) {
keySize := cipherFunc.KeySize()
if keySize == 0 {
- return nil, error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
+ return nil, error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
}
s2kBuf := new(bytes.Buffer)
"bytes"
"crypto/rand"
"encoding/hex"
+ "io"
"io/ioutil"
- "os"
"testing"
)
}
contents, err := ioutil.ReadAll(r)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
t.Error(err)
return
}
import (
"crypto/cipher"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/rand"
"crypto/sha1"
"crypto/subtle"
"hash"
"io"
- "os"
"strconv"
)
const symmetricallyEncryptedVersion = 1
-func (se *SymmetricallyEncrypted) parse(r io.Reader) os.Error {
+func (se *SymmetricallyEncrypted) parse(r io.Reader) error {
if se.MDC {
// See RFC 4880, section 5.13.
var buf [1]byte
return err
}
if buf[0] != symmetricallyEncryptedVersion {
- return error.UnsupportedError("unknown SymmetricallyEncrypted version")
+ return error_.UnsupportedError("unknown SymmetricallyEncrypted version")
}
}
se.contents = r
// Decrypt returns a ReadCloser, from which the decrypted contents of the
// packet can be read. An incorrect key can, with high probability, be detected
// immediately and this will result in a KeyIncorrect error being returned.
-func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, os.Error) {
+func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, error) {
keySize := c.KeySize()
if keySize == 0 {
- return nil, error.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c)))
+ return nil, error_.UnsupportedError("unknown cipher: " + strconv.Itoa(int(c)))
}
if len(key) != keySize {
- return nil, error.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length")
+ return nil, error_.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length")
}
if se.prefix == nil {
return nil, err
}
} else if len(se.prefix) != c.blockSize()+2 {
- return nil, error.InvalidArgumentError("can't try ciphers with different block lengths")
+ return nil, error_.InvalidArgumentError("can't try ciphers with different block lengths")
}
ocfbResync := cipher.OCFBResync
s := cipher.NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync)
if s == nil {
- return nil, error.KeyIncorrectError
+ return nil, error_.KeyIncorrectError
}
plaintext := cipher.StreamReader{S: s, R: se.contents}
in io.Reader
}
-func (ser seReader) Read(buf []byte) (int, os.Error) {
+func (ser seReader) Read(buf []byte) (int, error) {
return ser.in.Read(buf)
}
-func (ser seReader) Close() os.Error {
+func (ser seReader) Close() error {
return nil
}
eof bool
}
-func (ser *seMDCReader) Read(buf []byte) (n int, err os.Error) {
+func (ser *seMDCReader) Read(buf []byte) (n int, err error) {
if ser.error {
err = io.ErrUnexpectedEOF
return
}
if ser.eof {
- err = os.EOF
+ err = io.EOF
return
}
for ser.trailerUsed < mdcTrailerSize {
n, err = ser.in.Read(ser.trailer[ser.trailerUsed:])
ser.trailerUsed += n
- if err == os.EOF {
+ if err == io.EOF {
if ser.trailerUsed != mdcTrailerSize {
n = 0
err = io.ErrUnexpectedEOF
copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:])
if n < len(buf) {
ser.eof = true
- err = os.EOF
+ err = io.EOF
}
return
}
ser.h.Write(buf[:n])
copy(ser.trailer[:], buf[n:])
- if err == os.EOF {
+ if err == io.EOF {
ser.eof = true
}
return
// This is a new-format packet tag byte for a type 19 (MDC) packet.
const mdcPacketTagByte = byte(0x80) | 0x40 | 19
-func (ser *seMDCReader) Close() os.Error {
+func (ser *seMDCReader) Close() error {
if ser.error {
- return error.SignatureError("error during reading")
+ return error_.SignatureError("error during reading")
}
for !ser.eof {
// We haven't seen EOF so we need to read to the end
var buf [1024]byte
_, err := ser.Read(buf[:])
- if err == os.EOF {
+ if err == io.EOF {
break
}
if err != nil {
- return error.SignatureError("error during reading")
+ return error_.SignatureError("error during reading")
}
}
if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size {
- return error.SignatureError("MDC packet not found")
+ return error_.SignatureError("MDC packet not found")
}
ser.h.Write(ser.trailer[:2])
final := ser.h.Sum()
if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 {
- return error.SignatureError("hash mismatch")
+ return error_.SignatureError("hash mismatch")
}
return nil
}
h hash.Hash
}
-func (w *seMDCWriter) Write(buf []byte) (n int, err os.Error) {
+func (w *seMDCWriter) Write(buf []byte) (n int, err error) {
w.h.Write(buf)
return w.w.Write(buf)
}
-func (w *seMDCWriter) Close() (err os.Error) {
+func (w *seMDCWriter) Close() (err error) {
var buf [mdcTrailerSize]byte
buf[0] = mdcPacketTagByte
w io.Writer
}
-func (c noOpCloser) Write(data []byte) (n int, err os.Error) {
+func (c noOpCloser) Write(data []byte) (n int, err error) {
return c.w.Write(data)
}
-func (c noOpCloser) Close() os.Error {
+func (c noOpCloser) Close() error {
return nil
}
// SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet
// to w and returns a WriteCloser to which the to-be-encrypted packets can be
// written.
-func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte) (contents io.WriteCloser, err os.Error) {
+func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, key []byte) (contents io.WriteCloser, err error) {
if c.KeySize() != len(key) {
- return nil, error.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length")
+ return nil, error_.InvalidArgumentError("SymmetricallyEncrypted.Serialize: bad key length")
}
writeCloser := noOpCloser{w}
ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedMDC)
import (
"bytes"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/sha1"
"encoding/hex"
"io"
"io/ioutil"
- "os"
"testing"
)
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
}
err = mdcReader.Close()
if err == nil {
t.Error("corruption: no error")
- } else if _, ok := err.(*error.SignatureError); !ok {
+ } else if _, ok := err.(*error_.SignatureError); !ok {
t.Errorf("corruption: expected SignatureError, got: %s", err)
}
}
import (
"io"
"io/ioutil"
- "os"
"strings"
)
return uid
}
-func (uid *UserId) parse(r io.Reader) (err os.Error) {
+func (uid *UserId) parse(r io.Reader) (err error) {
// RFC 4880, section 5.11
b, err := ioutil.ReadAll(r)
if err != nil {
// Serialize marshals uid to w in the form of an OpenPGP packet, including
// header.
-func (uid *UserId) Serialize(w io.Writer) os.Error {
+func (uid *UserId) Serialize(w io.Writer) error {
err := serializeHeader(w, packetTypeUserId, len(uid.Id))
if err != nil {
return err
import (
"crypto"
"crypto/openpgp/armor"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/packet"
_ "crypto/sha256"
"hash"
"io"
- "os"
"strconv"
)
var SignatureType = "PGP SIGNATURE"
// readArmored reads an armored block with the given type.
-func readArmored(r io.Reader, expectedType string) (body io.Reader, err os.Error) {
+func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) {
block, err := armor.Decode(r)
if err != nil {
return
}
if block.Type != expectedType {
- return nil, error.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
+ return nil, error_.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
}
return block.Body, nil
// been consumed. Once EOF has been seen, the following fields are
// valid. (An authentication code failure is reported as a
// SignatureError error when reading from UnverifiedBody.)
- SignatureError os.Error // nil if the signature is good.
+ SignatureError error // nil if the signature is good.
Signature *packet.Signature // the signature packet itself.
decrypted io.ReadCloser
// passphrase to try. If the decrypted private key or given passphrase isn't
// correct, the function will be called again, forever. Any error returned will
// be passed up.
-type PromptFunction func(keys []Key, symmetric bool) ([]byte, os.Error)
+type PromptFunction func(keys []Key, symmetric bool) ([]byte, error)
// A keyEnvelopePair is used to store a private key with the envelope that
// contains a symmetric key, encrypted with that key.
// ReadMessage parses an OpenPGP message that may be signed and/or encrypted.
// The given KeyRing should contain both public keys (for signature
// verification) and, possibly encrypted, private keys for decrypting.
-func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction) (md *MessageDetails, err os.Error) {
+func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction) (md *MessageDetails, err error) {
var p packet.Packet
var symKeys []*packet.SymmetricKeyEncrypted
case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature:
// This message isn't encrypted.
if len(symKeys) != 0 || len(pubKeys) != 0 {
- return nil, error.StructuralError("key material not followed by encrypted message")
+ return nil, error_.StructuralError("key material not followed by encrypted message")
}
packets.Unread(p)
return readSignedMessage(packets, nil, keyring)
continue
}
decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key)
- if err != nil && err != error.KeyIncorrectError {
+ if err != nil && err != error_.KeyIncorrectError {
return nil, err
}
if decrypted != nil {
}
if len(candidates) == 0 && len(symKeys) == 0 {
- return nil, error.KeyIncorrectError
+ return nil, error_.KeyIncorrectError
}
if prompt == nil {
- return nil, error.KeyIncorrectError
+ return nil, error_.KeyIncorrectError
}
passphrase, err := prompt(candidates, len(symKeys) != 0)
err = s.Decrypt(passphrase)
if err == nil && !s.Encrypted {
decrypted, err = se.Decrypt(s.CipherFunc, s.Key)
- if err != nil && err != error.KeyIncorrectError {
+ if err != nil && err != error_.KeyIncorrectError {
return nil, err
}
if decrypted != nil {
// readSignedMessage reads a possibly signed message if mdin is non-zero then
// that structure is updated and returned. Otherwise a fresh MessageDetails is
// used.
-func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err os.Error) {
+func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) {
if mdin == nil {
mdin = new(MessageDetails)
}
packets.Push(p.Body)
case *packet.OnePassSignature:
if !p.IsLast {
- return nil, error.UnsupportedError("nested signatures")
+ return nil, error_.UnsupportedError("nested signatures")
}
h, wrappedHash, err = hashForSignature(p.Hash, p.SigType)
// should be preprocessed (i.e. to normalize line endings). Thus this function
// returns two hashes. The second should be used to hash the message itself and
// performs any needed preprocessing.
-func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, os.Error) {
+func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) {
h := hashId.New()
if h == nil {
- return nil, nil, error.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId)))
+ return nil, nil, error_.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId)))
}
switch sigType {
return h, NewCanonicalTextHash(h), nil
}
- return nil, nil, error.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
+ return nil, nil, error_.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
}
// checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
md *MessageDetails
}
-func (cr checkReader) Read(buf []byte) (n int, err os.Error) {
+func (cr checkReader) Read(buf []byte) (n int, err error) {
n, err = cr.md.LiteralData.Body.Read(buf)
- if err == os.EOF {
+ if err == io.EOF {
mdcErr := cr.md.decrypted.Close()
if mdcErr != nil {
err = mdcErr
md *MessageDetails
}
-func (scr *signatureCheckReader) Read(buf []byte) (n int, err os.Error) {
+func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) {
n, err = scr.md.LiteralData.Body.Read(buf)
scr.wrappedHash.Write(buf[:n])
- if err == os.EOF {
+ if err == io.EOF {
var p packet.Packet
p, scr.md.SignatureError = scr.packets.Next()
if scr.md.SignatureError != nil {
var ok bool
if scr.md.Signature, ok = p.(*packet.Signature); !ok {
- scr.md.SignatureError = error.StructuralError("LiteralData not followed by Signature")
+ scr.md.SignatureError = error_.StructuralError("LiteralData not followed by Signature")
return
}
// CheckDetachedSignature takes a signed file and a detached signature and
// returns the signer if the signature is valid. If the signer isn't know,
// UnknownIssuerError is returned.
-func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err os.Error) {
+func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
p, err := packet.Read(signature)
if err != nil {
return
sig, ok := p.(*packet.Signature)
if !ok {
- return nil, error.StructuralError("non signature packet found")
+ return nil, error_.StructuralError("non signature packet found")
}
if sig.IssuerKeyId == nil {
- return nil, error.StructuralError("signature doesn't have an issuer")
+ return nil, error_.StructuralError("signature doesn't have an issuer")
}
keys := keyring.KeysById(*sig.IssuerKeyId)
if len(keys) == 0 {
- return nil, error.UnknownIssuerError
+ return nil, error_.UnknownIssuerError
}
h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
}
_, err = io.Copy(wrappedHash, signed)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
return
}
return
}
- return nil, error.UnknownIssuerError
+ return nil, error_.UnknownIssuerError
}
// CheckArmoredDetachedSignature performs the same actions as
// CheckDetachedSignature but expects the signature to be armored.
-func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err os.Error) {
+func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
body, err := readArmored(signature, SignatureType)
if err != nil {
return
import (
"bytes"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"encoding/hex"
"io"
"io/ioutil"
- "os"
"testing"
)
for i, test := range signedEncryptedMessageTests {
expected := "Signed and encrypted message\n"
kring, _ := ReadKeyRing(readerFromHex(test.keyRingHex))
- prompt := func(keys []Key, symmetric bool) ([]byte, os.Error) {
+ prompt := func(keys []Key, symmetric bool) ([]byte, error) {
if symmetric {
t.Errorf("prompt: message was marked as symmetrically encrypted")
- return nil, error.KeyIncorrectError
+ return nil, error_.KeyIncorrectError
}
if len(keys) == 0 {
t.Error("prompt: no keys requested")
- return nil, error.KeyIncorrectError
+ return nil, error_.KeyIncorrectError
}
err := keys[0].PrivateKey.Decrypt([]byte("passphrase"))
if err != nil {
t.Errorf("prompt: error decrypting key: %s", err)
- return nil, error.KeyIncorrectError
+ return nil, error_.KeyIncorrectError
}
return nil, nil
func TestSymmetricallyEncrypted(t *testing.T) {
expected := "Symmetrically encrypted.\n"
- prompt := func(keys []Key, symmetric bool) ([]byte, os.Error) {
+ prompt := func(keys []Key, symmetric bool) ([]byte, error) {
if len(keys) != 0 {
t.Errorf("prompt: len(keys) = %d (want 0)", len(keys))
}
func TestNoArmoredData(t *testing.T) {
_, err := ReadArmoredKeyRing(bytes.NewBufferString("foo"))
- if _, ok := err.(error.InvalidArgumentError); !ok {
+ if _, ok := err.(error_.InvalidArgumentError); !ok {
t.Errorf("error was not an InvalidArgumentError: %s", err)
}
}
import (
"crypto"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"hash"
"io"
- "os"
"strconv"
)
// Parse reads a binary specification for a string-to-key transformation from r
// and returns a function which performs that transform.
-func Parse(r io.Reader) (f func(out, in []byte), err os.Error) {
+func Parse(r io.Reader) (f func(out, in []byte), err error) {
var buf [9]byte
_, err = io.ReadFull(r, buf[:2])
hash, ok := HashIdToHash(buf[1])
if !ok {
- return nil, error.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1])))
+ return nil, error_.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1])))
}
h := hash.New()
if h == nil {
- return nil, error.UnsupportedError("hash not available: " + strconv.Itoa(int(hash)))
+ return nil, error_.UnsupportedError("hash not available: " + strconv.Itoa(int(hash)))
}
switch buf[0] {
return f, nil
}
- return nil, error.UnsupportedError("S2K function")
+ return nil, error_.UnsupportedError("S2K function")
}
// Serialize salts and stretches the given passphrase and writes the resulting
// key into key. It also serializes an S2K descriptor to w.
-func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte) os.Error {
+func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte) error {
var buf [11]byte
buf[0] = 3 /* iterated and salted */
buf[1], _ = HashToHashId(crypto.SHA1)
import (
"crypto"
"crypto/openpgp/armor"
- "crypto/openpgp/error"
+ error_ "crypto/openpgp/error"
"crypto/openpgp/packet"
"crypto/openpgp/s2k"
"crypto/rand"
_ "crypto/sha256"
"hash"
"io"
- "os"
"strconv"
"time"
)
// DetachSign signs message with the private key from signer (which must
// already have been decrypted) and writes the signature to w.
-func DetachSign(w io.Writer, signer *Entity, message io.Reader) os.Error {
+func DetachSign(w io.Writer, signer *Entity, message io.Reader) error {
return detachSign(w, signer, message, packet.SigTypeBinary)
}
// ArmoredDetachSign signs message with the private key from signer (which
// must already have been decrypted) and writes an armored signature to w.
-func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader) (err os.Error) {
+func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader) (err error) {
return armoredDetachSign(w, signer, message, packet.SigTypeBinary)
}
// DetachSignText signs message (after canonicalising the line endings) with
// the private key from signer (which must already have been decrypted) and
// writes the signature to w.
-func DetachSignText(w io.Writer, signer *Entity, message io.Reader) os.Error {
+func DetachSignText(w io.Writer, signer *Entity, message io.Reader) error {
return detachSign(w, signer, message, packet.SigTypeText)
}
// ArmoredDetachSignText signs message (after canonicalising the line endings)
// with the private key from signer (which must already have been decrypted)
// and writes an armored signature to w.
-func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader) os.Error {
+func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader) error {
return armoredDetachSign(w, signer, message, packet.SigTypeText)
}
-func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err os.Error) {
+func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err error) {
out, err := armor.Encode(w, SignatureType, nil)
if err != nil {
return
return out.Close()
}
-func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err os.Error) {
+func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType) (err error) {
if signer.PrivateKey == nil {
- return error.InvalidArgumentError("signing key doesn't have a private key")
+ return error_.InvalidArgumentError("signing key doesn't have a private key")
}
if signer.PrivateKey.Encrypted {
- return error.InvalidArgumentError("signing key is encrypted")
+ return error_.InvalidArgumentError("signing key is encrypted")
}
sig := new(packet.Signature)
// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase.
// The resulting WriteCloser must be closed after the contents of the file have
// been written.
-func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints) (plaintext io.WriteCloser, err os.Error) {
+func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints) (plaintext io.WriteCloser, err error) {
if hints == nil {
hints = &FileHints{}
}
// it. hints contains optional information, that is also encrypted, that aids
// the recipients in processing the message. The resulting WriteCloser must
// be closed after the contents of the file have been written.
-func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints) (plaintext io.WriteCloser, err os.Error) {
+func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints) (plaintext io.WriteCloser, err error) {
var signer *packet.PrivateKey
if signed != nil {
signer = signed.signingKey().PrivateKey
if signer == nil || signer.Encrypted {
- return nil, error.InvalidArgumentError("signing key must be decrypted")
+ return nil, error_.InvalidArgumentError("signing key must be decrypted")
}
}
for i := range to {
encryptKeys[i] = to[i].encryptionKey()
if encryptKeys[i].PublicKey == nil {
- return nil, error.InvalidArgumentError("cannot encrypt a message to key id " + strconv.Uitob64(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
+ return nil, error_.InvalidArgumentError("cannot encrypt a message to key id " + strconv.Uitob64(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
}
sig := to[i].primaryIdentity().SelfSignature
}
if len(candidateCiphers) == 0 || len(candidateHashes) == 0 {
- return nil, error.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
+ return nil, error_.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
}
cipher := packet.CipherFunction(candidateCiphers[0])
signer *packet.PrivateKey
}
-func (s signatureWriter) Write(data []byte) (int, os.Error) {
+func (s signatureWriter) Write(data []byte) (int, error) {
s.h.Write(data)
return s.literalData.Write(data)
}
-func (s signatureWriter) Close() os.Error {
+func (s signatureWriter) Close() error {
sig := &packet.Signature{
SigType: packet.SigTypeBinary,
PubKeyAlgo: s.signer.PubKeyAlgo,
w io.Writer
}
-func (c noOpCloser) Write(data []byte) (n int, err os.Error) {
+func (c noOpCloser) Write(data []byte) (n int, err error) {
return c.w.Write(data)
}
-func (c noOpCloser) Close() os.Error {
+func (c noOpCloser) Close() error {
return nil
}
import (
"bytes"
"crypto/rand"
- "os"
"io"
"io/ioutil"
"testing"
t.Errorf("error closing plaintext writer: %s", err)
}
- md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, os.Error) {
+ md, err := ReadMessage(buf, nil, func(keys []Key, symmetric bool) ([]byte, error) {
return []byte("testing"), nil
})
if err != nil {
// pseudorandom number generator.
package rand
-import (
- "io"
- "os"
-)
+import "io"
// Reader is a global, shared instance of a cryptographically
// strong pseudo-random generator.
var Reader io.Reader
// Read is a helper function that calls Reader.Read.
-func Read(b []byte) (n int, err os.Error) { return Reader.Read(b) }
+func Read(b []byte) (n int, err error) { return Reader.Read(b) }
mu sync.Mutex
}
-func (r *devReader) Read(b []byte) (n int, err os.Error) {
+func (r *devReader) Read(b []byte) (n int, err error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.f == nil {
time, seed, dst, key [aes.BlockSize]byte
}
-func (r *reader) Read(b []byte) (n int, err os.Error) {
+func (r *reader) Read(b []byte) (n int, err error) {
r.mu.Lock()
defer r.mu.Unlock()
n = len(b)
mu sync.Mutex
}
-func (r *rngReader) Read(b []byte) (n int, err os.Error) {
+func (r *rngReader) Read(b []byte) (n int, err error) {
r.mu.Lock()
if r.prov == 0 {
const provType = syscall.PROV_RSA_FULL
// Prime returns a number, p, of the given size, such that p is prime
// with high probability.
-func Prime(rand io.Reader, bits int) (p *big.Int, err os.Error) {
+func Prime(rand io.Reader, bits int) (p *big.Int, err error) {
if bits < 1 {
err = os.EINVAL
}
}
// Int returns a uniform random value in [0, max).
-func Int(rand io.Reader, max *big.Int) (n *big.Int, err os.Error) {
+func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) {
k := (max.BitLen() + 7) / 8
// b is the number of bits in the most significant byte of max.
// BUG(agl): RC4 is in common use but has design weaknesses that make
// it a poor choice for new protocols.
-import (
- "os"
- "strconv"
-)
+import "strconv"
// A Cipher is an instance of RC4 using a particular key.
type Cipher struct {
type KeySizeError int
-func (k KeySizeError) String() string {
+func (k KeySizeError) Error() string {
return "crypto/rc4: invalid key size " + strconv.Itoa(int(k))
}
// NewCipher creates and returns a new Cipher. The key argument should be the
// RC4 key, at least 1 byte and at most 256 bytes.
-func NewCipher(key []byte) (*Cipher, os.Error) {
+func NewCipher(key []byte) (*Cipher, error) {
k := len(key)
if k < 1 || k > 256 {
return nil, KeySizeError(k)
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.tc += uint64(nn)
if d.nx > 0 {
"big"
"crypto"
"crypto/subtle"
+ "errors"
"io"
- "os"
)
// This file implements encryption and decryption using PKCS#1 v1.5 padding.
// The message must be no longer than the length of the public modulus minus 11 bytes.
// WARNING: use of this function to encrypt plaintexts other than session keys
// is dangerous. Use RSA OAEP in new protocols.
-func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err os.Error) {
+func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err error) {
k := (pub.N.BitLen() + 7) / 8
if len(msg) > k-11 {
err = MessageTooLongError{}
// DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
-func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err os.Error) {
+func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error) {
valid, out, err := decryptPKCS1v15(rand, priv, ciphertext)
if err == nil && valid == 0 {
err = DecryptionError{}
// See ``Chosen Ciphertext Attacks Against Protocols Based on the RSA
// Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
// (Crypto '98),
-func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err os.Error) {
+func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err error) {
k := (priv.N.BitLen() + 7) / 8
if k-(len(key)+3+8) < 0 {
err = DecryptionError{}
return
}
-func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, msg []byte, err os.Error) {
+func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, msg []byte, err error) {
k := (priv.N.BitLen() + 7) / 8
if k < 11 {
err = DecryptionError{}
}
// nonZeroRandomBytes fills the given slice with non-zero random octets.
-func nonZeroRandomBytes(s []byte, rand io.Reader) (err os.Error) {
+func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) {
_, err = io.ReadFull(rand, s)
if err != nil {
return
// SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5.
// Note that hashed must be the result of hashing the input message using the
// given hash function.
-func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err os.Error) {
+func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err error) {
hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
if err != nil {
return
// hashed is the result of hashing the input message using the given hash
// function and sig is the signature. A valid signature is indicated by
// returning a nil error.
-func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err os.Error) {
+func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error) {
hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed))
if err != nil {
return
return nil
}
-func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err os.Error) {
+func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) {
hashLen = hash.Size()
if inLen != hashLen {
- return 0, nil, os.NewError("input must be hashed message")
+ return 0, nil, errors.New("input must be hashed message")
}
prefix, ok := hashPrefixes[hash]
if !ok {
- return 0, nil, os.NewError("unsupported hash function")
+ return 0, nil, errors.New("unsupported hash function")
}
return
}
"big"
"crypto/rand"
"crypto/subtle"
+ "errors"
"hash"
"io"
- "os"
)
var bigZero = big.NewInt(0)
}
// Validate performs basic sanity checks on the key.
-// It returns nil if the key is valid, or else an os.Error describing a problem.
-
-func (priv *PrivateKey) Validate() os.Error {
+// It returns nil if the key is valid, or else an error describing a problem.
+func (priv *PrivateKey) Validate() error {
// Check that the prime factors are actually prime. Note that this is
// just a sanity check. Since the random witnesses chosen by
// ProbablyPrime are deterministic, given the candidate number, it's
// easy for an attack to generate composites that pass this test.
for _, prime := range priv.Primes {
if !big.ProbablyPrime(prime, 20) {
- return os.NewError("prime factor is composite")
+ return errors.New("prime factor is composite")
}
}
modulus.Mul(modulus, prime)
}
if modulus.Cmp(priv.N) != 0 {
- return os.NewError("invalid modulus")
+ return errors.New("invalid modulus")
}
// Check that e and totient(Πprimes) are coprime.
totient := new(big.Int).Set(bigOne)
y := new(big.Int)
big.GcdInt(gcd, x, y, totient, e)
if gcd.Cmp(bigOne) != 0 {
- return os.NewError("invalid public exponent E")
+ return errors.New("invalid public exponent E")
}
// Check that de ≡ 1 (mod totient(Πprimes))
de := new(big.Int).Mul(priv.D, e)
de.Mod(de, totient)
if de.Cmp(bigOne) != 0 {
- return os.NewError("invalid private exponent D")
+ return errors.New("invalid private exponent D")
}
return nil
}
// GenerateKey generates an RSA keypair of the given bit size.
-func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err os.Error) {
+func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error) {
return GenerateMultiPrimeKey(random, 2, bits)
}
//
// [1] US patent 4405829 (1972, expired)
// [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
-func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err os.Error) {
+func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error) {
priv = new(PrivateKey)
priv.E = 65537
if nprimes < 2 {
- return nil, os.NewError("rsa.GenerateMultiPrimeKey: nprimes must be >= 2")
+ return nil, errors.New("rsa.GenerateMultiPrimeKey: nprimes must be >= 2")
}
primes := make([]*big.Int, nprimes)
// is too large for the size of the public key.
type MessageTooLongError struct{}
-func (MessageTooLongError) String() string {
+func (MessageTooLongError) Error() string {
return "message too long for RSA public key size"
}
// EncryptOAEP encrypts the given message with RSA-OAEP.
// The message must be no longer than the length of the public modulus less
// twice the hash length plus 2.
-func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err os.Error) {
+func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err error) {
hash.Reset()
k := (pub.N.BitLen() + 7) / 8
if len(msg) > k-2*hash.Size()-2 {
// It is deliberately vague to avoid adaptive attacks.
type DecryptionError struct{}
-func (DecryptionError) String() string { return "RSA decryption error" }
+func (DecryptionError) Error() string { return "RSA decryption error" }
// A VerificationError represents a failure to verify a signature.
// It is deliberately vague to avoid adaptive attacks.
type VerificationError struct{}
-func (VerificationError) String() string { return "RSA verification error" }
+func (VerificationError) Error() string { return "RSA verification error" }
// modInverse returns ia, the inverse of a in the multiplicative group of prime
// order n. It requires that a be a member of the group (i.e. less than n).
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a
// random source is given, RSA blinding is used.
-func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) {
+func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) {
// TODO(agl): can we get away with reusing blinds?
if c.Cmp(priv.N) > 0 {
err = DecryptionError{}
// DecryptOAEP decrypts ciphertext using RSA-OAEP.
// If rand != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks.
-func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err os.Error) {
+func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error) {
k := (priv.N.BitLen() + 7) / 8
if len(ciphertext) > k ||
k < hash.Size()*2+2 {
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() {
return Size224
}
-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() {
return Size384
}
-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"
"hash"
- "os"
)
// a keyAgreement implements the client and server side of a TLS key agreement
// In the case that the key agreement protocol doesn't use a
// ServerKeyExchange message, generateServerKeyExchange can return nil,
// nil.
- generateServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, os.Error)
- processClientKeyExchange(*Config, *clientKeyExchangeMsg, uint16) ([]byte, os.Error)
+ generateServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
+ processClientKeyExchange(*Config, *clientKeyExchangeMsg, uint16) ([]byte, error)
// On the client side, the next two methods are called in order.
// This method may not be called if the server doesn't send a
// ServerKeyExchange message.
- processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) os.Error
- generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, os.Error)
+ processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
+ generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
}
// A cipherSuite is a specific combination of key agreement, cipher and MAC
"crypto/cipher"
"crypto/subtle"
"crypto/x509"
+ "errors"
"io"
"net"
- "os"
"sync"
)
// first permanent error
errMutex sync.Mutex
- err os.Error
+ err error
// input/output
in, out halfConn // in.Mutex < out.Mutex
tmp [16]byte
}
-func (c *Conn) setError(err os.Error) os.Error {
+func (c *Conn) setError(err error) error {
c.errMutex.Lock()
defer c.errMutex.Unlock()
return err
}
-func (c *Conn) error() os.Error {
+func (c *Conn) error() error {
c.errMutex.Lock()
defer c.errMutex.Unlock()
// SetTimeout sets the read deadline associated with the connection.
// There is no write deadline.
-func (c *Conn) SetTimeout(nsec int64) os.Error {
+func (c *Conn) SetTimeout(nsec int64) error {
return c.conn.SetTimeout(nsec)
}
// SetReadTimeout sets the time (in nanoseconds) that
// Read will wait for data before returning os.EAGAIN.
// Setting nsec == 0 (the default) disables the deadline.
-func (c *Conn) SetReadTimeout(nsec int64) os.Error {
+func (c *Conn) SetReadTimeout(nsec int64) error {
return c.conn.SetReadTimeout(nsec)
}
// SetWriteTimeout exists to satisfy the net.Conn interface
// but is not implemented by TLS. It always returns an error.
-func (c *Conn) SetWriteTimeout(nsec int64) os.Error {
- return os.NewError("TLS does not support SetWriteTimeout")
+func (c *Conn) SetWriteTimeout(nsec int64) error {
+ return errors.New("TLS does not support SetWriteTimeout")
}
// A halfConn represents one direction of the record layer
// changeCipherSpec changes the encryption and MAC states
// to the ones previously passed to prepareCipherSpec.
-func (hc *halfConn) changeCipherSpec() os.Error {
+func (hc *halfConn) changeCipherSpec() error {
if hc.nextCipher == nil {
return alertInternalError
}
// readFromUntil reads from r into b until b contains at least n bytes
// or else returns an error.
-func (b *block) readFromUntil(r io.Reader, n int) os.Error {
+func (b *block) readFromUntil(r io.Reader, n int) error {
// quick case
if len(b.data) >= n {
return nil
return nil
}
-func (b *block) Read(p []byte) (n int, err os.Error) {
+func (b *block) Read(p []byte) (n int, err error) {
n = copy(p, b.data[b.off:])
b.off += n
return
// readRecord reads the next TLS record from the connection
// and updates the record layer state.
// c.in.Mutex <= L; c.input == nil.
-func (c *Conn) readRecord(want recordType) os.Error {
+func (c *Conn) readRecord(want recordType) error {
// Caller must be in sync with connection:
// handshake data if handshake not yet completed,
// else application data. (We don't support renegotiation.)
}
}
if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
if e, ok := err.(net.Error); !ok || !e.Temporary() {
break
}
if alert(data[1]) == alertCloseNotify {
- c.setError(os.EOF)
+ c.setError(io.EOF)
break
}
switch data[0] {
c.in.freeBlock(b)
goto Again
case alertLevelError:
- c.setError(&net.OpError{Op: "remote error", Error: alert(data[1])})
+ c.setError(&net.OpError{Op: "remote error", Err: alert(data[1])})
default:
c.sendAlert(alertUnexpectedMessage)
}
// sendAlert sends a TLS alert message.
// c.out.Mutex <= L.
-func (c *Conn) sendAlertLocked(err alert) os.Error {
+func (c *Conn) sendAlertLocked(err alert) error {
c.tmp[0] = alertLevelError
if err == alertNoRenegotiation {
c.tmp[0] = alertLevelWarning
c.writeRecord(recordTypeAlert, c.tmp[0:2])
// closeNotify is a special case in that it isn't an error:
if err != alertCloseNotify {
- return c.setError(&net.OpError{Op: "local error", Error: err})
+ return c.setError(&net.OpError{Op: "local error", Err: err})
}
return nil
}
// sendAlert sends a TLS alert message.
// L < c.out.Mutex.
-func (c *Conn) sendAlert(err alert) os.Error {
+func (c *Conn) sendAlert(err alert) error {
c.out.Lock()
defer c.out.Unlock()
return c.sendAlertLocked(err)
// writeRecord writes a TLS record with the given type and payload
// to the connection and updates the record layer state.
// c.out.Mutex <= L.
-func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err os.Error) {
+func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) {
b := c.out.newBlock()
for len(data) > 0 {
m := len(data)
c.tmp[0] = alertLevelError
c.tmp[1] = byte(err.(alert))
c.writeRecord(recordTypeAlert, c.tmp[0:2])
- c.err = &net.OpError{Op: "local error", Error: err}
+ c.err = &net.OpError{Op: "local error", Err: err}
return n, c.err
}
}
// readHandshake reads the next handshake message from
// the record layer.
// c.in.Mutex < L; c.out.Mutex < L.
-func (c *Conn) readHandshake() (interface{}, os.Error) {
+func (c *Conn) readHandshake() (interface{}, error) {
for c.hand.Len() < 4 {
if c.err != nil {
return nil, c.err
}
// Write writes data to the connection.
-func (c *Conn) Write(b []byte) (n int, err os.Error) {
+func (c *Conn) Write(b []byte) (n int, err error) {
if err = c.Handshake(); err != nil {
return
}
// Read can be made to time out and return err == os.EAGAIN
// after a fixed time limit; see SetTimeout and SetReadTimeout.
-func (c *Conn) Read(b []byte) (n int, err os.Error) {
+func (c *Conn) Read(b []byte) (n int, err error) {
if err = c.Handshake(); err != nil {
return
}
}
// Close closes the connection.
-func (c *Conn) Close() os.Error {
- var alertErr os.Error
+func (c *Conn) Close() error {
+ var alertErr error
c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock()
// protocol if it has not yet been run.
// Most uses of this package need not call Handshake
// explicitly: the first Read or Write will call it automatically.
-func (c *Conn) Handshake() os.Error {
+func (c *Conn) Handshake() error {
c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock()
if err := c.error(); err != nil {
}
// VerifyHostname checks that the peer certificate chain is valid for
-// connecting to host. If so, it returns nil; if not, it returns an os.Error
+// connecting to host. If so, it returns nil; if not, it returns an error
// describing the problem.
-func (c *Conn) VerifyHostname(host string) os.Error {
+func (c *Conn) VerifyHostname(host string) error {
c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock()
if !c.isClient {
- return os.NewError("VerifyHostname called on TLS server connection")
+ return errors.New("VerifyHostname called on TLS server connection")
}
if !c.handshakeComplete {
- return os.NewError("TLS handshake has not yet been performed")
+ return errors.New("TLS handshake has not yet been performed")
}
return c.peerCertificates[0].VerifyHostname(host)
}
"crypto/rsa"
"crypto/subtle"
"crypto/x509"
+ "errors"
"io"
- "os"
)
-func (c *Conn) clientHandshake() os.Error {
+func (c *Conn) clientHandshake() error {
finishedHash := newFinishedHash(versionTLS10)
if c.config == nil {
_, err := io.ReadFull(c.config.rand(), hello.random[4:])
if err != nil {
c.sendAlert(alertInternalError)
- return os.NewError("short read from Rand")
+ return errors.New("short read from Rand")
}
finishedHash.Write(hello.marshal())
if !hello.nextProtoNeg && serverHello.nextProtoNeg {
c.sendAlert(alertHandshakeFailure)
- return os.NewError("server advertised unrequested NPN")
+ return errors.New("server advertised unrequested NPN")
}
suite, suiteId := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
cert, err := x509.ParseCertificate(asn1Data)
if err != nil {
c.sendAlert(alertBadCertificate)
- return os.NewError("failed to parse certificate from server: " + err.String())
+ return errors.New("failed to parse certificate from server: " + err.Error())
}
certs[i] = cert
}
"crypto/rsa"
"crypto/subtle"
"crypto/x509"
+ "errors"
"io"
- "os"
)
-func (c *Conn) serverHandshake() os.Error {
+func (c *Conn) serverHandshake() error {
config := c.config
msg, err := c.readHandshake()
if err != nil {
cert, err := x509.ParseCertificate(asn1Data)
if err != nil {
c.sendAlert(alertBadCertificate)
- return os.NewError("could not parse client's certificate: " + err.String())
+ return errors.New("could not parse client's certificate: " + err.Error())
}
certs[i] = cert
}
for i := 1; i < len(certs); i++ {
if err := certs[i-1].CheckSignatureFrom(certs[i]); err != nil {
c.sendAlert(alertBadCertificate)
- return os.NewError("could not validate certificate signature: " + err.String())
+ return errors.New("could not validate certificate signature: " + err.Error())
}
}
err = rsa.VerifyPKCS1v15(pub, crypto.MD5SHA1, digest, certVerify.signature)
if err != nil {
c.sendAlert(alertBadCertificate)
- return os.NewError("could not validate signature of connection nonces: " + err.String())
+ return errors.New("could not validate signature of connection nonces: " + err.Error())
}
finishedHash.Write(certVerify.marshal())
"flag"
"io"
"net"
- "os"
"strconv"
"strings"
"testing"
type zeroSource struct{}
-func (zeroSource) Read(b []byte) (n int, err os.Error) {
+func (zeroSource) Read(b []byte) (n int, err error) {
for i := range b {
b[i] = 0
}
testConfig.InsecureSkipVerify = true
}
-func testClientHelloFailure(t *testing.T, m handshakeMessage, expected os.Error) {
+func testClientHelloFailure(t *testing.T, m handshakeMessage, expected error) {
// Create in-memory network connection,
// send message to server. Should return
// expected error.
}()
err := Server(s, testConfig).Handshake()
s.Close()
- if e, ok := err.(*net.OpError); !ok || e.Error != expected {
+ if e, ok := err.(*net.OpError); !ok || e.Err != expected {
t.Errorf("Got error: %s; expected: %s", err, expected)
}
}
err := Server(s, testConfig).Handshake()
s.Close()
- if e, ok := err.(*net.OpError); !ok || e.Error != os.Error(alertUnknownCA) {
+ if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
t.Errorf("Got error: %s; expected: %s", err, alertUnknownCA)
}
}
err := Server(s, testConfig).Handshake()
s.Close()
- if err != os.EOF {
- t.Errorf("Got error: %s; expected: %s", err, os.EOF)
+ if err != io.EOF {
+ t.Errorf("Got error: %s; expected: %s", err, io.EOF)
}
}
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
+ "errors"
"io"
- "os"
)
// rsaKeyAgreement implements the standard TLS key agreement where the client
// encrypts the pre-master secret to the server's public key.
type rsaKeyAgreement struct{}
-func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, os.Error) {
+func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
return nil, nil
}
-func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg, version uint16) ([]byte, os.Error) {
+func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
preMasterSecret := make([]byte, 48)
_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
if err != nil {
}
if len(ckx.ciphertext) < 2 {
- return nil, os.NewError("bad ClientKeyExchange")
+ return nil, errors.New("bad ClientKeyExchange")
}
ciphertext := ckx.ciphertext
if version != versionSSL30 {
ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
if ciphertextLen != len(ckx.ciphertext)-2 {
- return nil, os.NewError("bad ClientKeyExchange")
+ return nil, errors.New("bad ClientKeyExchange")
}
ciphertext = ckx.ciphertext[2:]
}
return preMasterSecret, nil
}
-func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) os.Error {
- return os.NewError("unexpected ServerKeyExchange")
+func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
+ return errors.New("unexpected ServerKeyExchange")
}
-func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, os.Error) {
+func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
preMasterSecret := make([]byte, 48)
preMasterSecret[0] = byte(clientHello.vers >> 8)
preMasterSecret[1] = byte(clientHello.vers)
x, y *big.Int
}
-func (ka *ecdheRSAKeyAgreement) generateServerKeyExchange(config *Config, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, os.Error) {
+func (ka *ecdheRSAKeyAgreement) generateServerKeyExchange(config *Config, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
var curveid uint16
Curve:
}
var x, y *big.Int
- var err os.Error
+ var err error
ka.privateKey, x, y, err = ka.curve.GenerateKey(config.rand())
if err != nil {
return nil, err
md5sha1 := md5SHA1Hash(clientHello.random, hello.random, serverECDHParams)
sig, err := rsa.SignPKCS1v15(config.rand(), config.Certificates[0].PrivateKey, crypto.MD5SHA1, md5sha1)
if err != nil {
- return nil, os.NewError("failed to sign ECDHE parameters: " + err.String())
+ return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
}
skx := new(serverKeyExchangeMsg)
return skx, nil
}
-func (ka *ecdheRSAKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg, version uint16) ([]byte, os.Error) {
+func (ka *ecdheRSAKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
- return nil, os.NewError("bad ClientKeyExchange")
+ return nil, errors.New("bad ClientKeyExchange")
}
x, y := ka.curve.Unmarshal(ckx.ciphertext[1:])
if x == nil {
- return nil, os.NewError("bad ClientKeyExchange")
+ return nil, errors.New("bad ClientKeyExchange")
}
x, _ = ka.curve.ScalarMult(x, y, ka.privateKey)
preMasterSecret := make([]byte, (ka.curve.BitSize+7)>>3)
return preMasterSecret, nil
}
-var errServerKeyExchange = os.NewError("invalid ServerKeyExchange")
+var errServerKeyExchange = errors.New("invalid ServerKeyExchange")
-func (ka *ecdheRSAKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) os.Error {
+func (ka *ecdheRSAKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
if len(skx.key) < 4 {
return errServerKeyExchange
}
if skx.key[0] != 3 { // named curve
- return os.NewError("server selected unsupported curve")
+ return errors.New("server selected unsupported curve")
}
curveid := uint16(skx.key[1])<<8 | uint16(skx.key[2])
case curveP521:
ka.curve = elliptic.P521()
default:
- return os.NewError("server selected unsupported curve")
+ return errors.New("server selected unsupported curve")
}
publicLen := int(skx.key[3])
return rsa.VerifyPKCS1v15(cert.PublicKey.(*rsa.PublicKey), crypto.MD5SHA1, md5sha1, sig)
}
-func (ka *ecdheRSAKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, os.Error) {
+func (ka *ecdheRSAKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
if ka.curve == nil {
- return nil, nil, os.NewError("missing ServerKeyExchange message")
+ return nil, nil, errors.New("missing ServerKeyExchange message")
}
priv, mx, my, err := ka.curve.GenerateKey(config.rand())
if err != nil {
"crypto/md5"
"crypto/sha1"
"hash"
- "os"
)
// Split a premaster secret in two as specified in RFC 4346, section 5.
version uint16
}
-func (h finishedHash) Write(msg []byte) (n int, err os.Error) {
+func (h finishedHash) Write(msg []byte) (n int, err error) {
h.clientMD5.Write(msg)
h.clientSHA1.Write(msg)
h.serverMD5.Write(msg)
"crypto/rsa"
"crypto/x509"
"encoding/pem"
+ "errors"
"io/ioutil"
"net"
- "os"
"strings"
)
// Accept waits for and returns the next incoming TLS connection.
// The returned connection c is a *tls.Conn.
-func (l *Listener) Accept() (c net.Conn, err os.Error) {
+func (l *Listener) Accept() (c net.Conn, err error) {
c, err = l.listener.Accept()
if err != nil {
return
}
// Close closes the listener.
-func (l *Listener) Close() os.Error { return l.listener.Close() }
+func (l *Listener) Close() error { return l.listener.Close() }
// Addr returns the listener's network address.
func (l *Listener) Addr() net.Addr { return l.listener.Addr() }
// given network address using net.Listen.
// The configuration config must be non-nil and must have
// at least one certificate.
-func Listen(network, laddr string, config *Config) (*Listener, os.Error) {
+func Listen(network, laddr string, config *Config) (*Listener, error) {
if config == nil || len(config.Certificates) == 0 {
- return nil, os.NewError("tls.Listen: no certificates in configuration")
+ return nil, errors.New("tls.Listen: no certificates in configuration")
}
l, err := net.Listen(network, laddr)
if err != nil {
// Dial interprets a nil configuration as equivalent to
// the zero configuration; see the documentation of Config
// for the defaults.
-func Dial(network, addr string, config *Config) (*Conn, os.Error) {
+func Dial(network, addr string, config *Config) (*Conn, error) {
raddr := addr
c, err := net.Dial(network, raddr)
if err != nil {
// LoadX509KeyPair reads and parses a public/private key pair from a pair of
// files. The files must contain PEM encoded data.
-func LoadX509KeyPair(certFile string, keyFile string) (cert Certificate, err os.Error) {
+func LoadX509KeyPair(certFile string, keyFile string) (cert Certificate, err error) {
certPEMBlock, err := ioutil.ReadFile(certFile)
if err != nil {
return
// X509KeyPair parses a public/private key pair from a pair of
// PEM encoded data.
-func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err os.Error) {
+func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) {
var certDERBlock *pem.Block
for {
certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
}
if len(cert.Certificate) == 0 {
- err = os.NewError("crypto/tls: failed to parse certificate PEM data")
+ err = errors.New("crypto/tls: failed to parse certificate PEM data")
return
}
keyDERBlock, _ := pem.Decode(keyPEMBlock)
if keyDERBlock == nil {
- err = os.NewError("crypto/tls: failed to parse key PEM data")
+ err = errors.New("crypto/tls: failed to parse key PEM data")
return
}
key, err := x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes)
if err != nil {
- err = os.NewError("crypto/tls: failed to parse key: " + err.String())
+ err = errors.New("crypto/tls: failed to parse key: " + err.Error())
return
}
}
if x509Cert.PublicKeyAlgorithm != x509.RSA || x509Cert.PublicKey.(*rsa.PublicKey).N.Cmp(key.PublicKey.N) != 0 {
- err = os.NewError("crypto/tls: private key does not match public key")
+ err = errors.New("crypto/tls: private key does not match public key")
return
}
// LibTomCrypt is free for all purposes under the public domain.
// It was heavily inspired by the go blowfish package.
-import (
- "os"
- "strconv"
-)
+import "strconv"
// BlockSize is the constant block size of Twofish.
const BlockSize = 16
type KeySizeError int
-func (k KeySizeError) String() string {
+func (k KeySizeError) Error() string {
return "crypto/twofish: invalid key size " + strconv.Itoa(int(k))
}
// NewCipher creates and returns a Cipher.
// The key argument should be the Twofish key, 16, 24 or 32 bytes.
-func NewCipher(key []byte) (*Cipher, os.Error) {
+func NewCipher(key []byte) (*Cipher, error) {
keylen := len(key)
if keylen != 16 && keylen != 24 && keylen != 32 {
import (
"asn1"
"big"
- "os"
+ "errors"
"crypto/rsa"
)
}
// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
-func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
+func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error) {
var priv pkcs1PrivateKey
rest, err := asn1.Unmarshal(der, &priv)
if len(rest) > 0 {
}
if priv.Version > 1 {
- return nil, os.NewError("x509: unsupported private key version")
+ return nil, errors.New("x509: unsupported private key version")
}
if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 {
- return nil, os.NewError("private key contains zero or negative value")
+ return nil, errors.New("private key contains zero or negative value")
}
key = new(rsa.PrivateKey)
key.Primes[1] = priv.Q
for i, a := range priv.AdditionalPrimes {
if a.Prime.Sign() <= 0 {
- return nil, os.NewError("private key contains zero or negative prime")
+ return nil, errors.New("private key contains zero or negative prime")
}
key.Primes[i+2] = a.Prime
// We ignore the other two values because rsa will calculate
package x509
import (
- "os"
"strings"
"time"
)
Reason InvalidReason
}
-func (e CertificateInvalidError) String() string {
+func (e CertificateInvalidError) Error() string {
switch e.Reason {
case NotAuthorizedToSign:
return "x509: certificate is not authorized to sign other other certificates"
Host string
}
-func (h HostnameError) String() string {
+func (h HostnameError) Error() string {
var valid string
c := h.Certificate
if len(c.DNSNames) > 0 {
cert *Certificate
}
-func (e UnknownAuthorityError) String() string {
+func (e UnknownAuthorityError) Error() string {
return "x509: certificate signed by unknown authority"
}
)
// isValid performs validity checks on the c.
-func (c *Certificate) isValid(certType int, opts *VerifyOptions) os.Error {
+func (c *Certificate) isValid(certType int, opts *VerifyOptions) error {
if opts.CurrentTime < c.NotBefore.Seconds() ||
opts.CurrentTime > c.NotAfter.Seconds() {
return CertificateInvalidError{c, Expired}
// the chain is c and the last element is from opts.Roots.
//
// WARNING: this doesn't do any revocation checking.
-func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err os.Error) {
+func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) {
if opts.CurrentTime == 0 {
opts.CurrentTime = time.Seconds()
}
return n
}
-func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err os.Error) {
+func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) {
for _, rootNum := range opts.Roots.findVerifiedParents(c) {
root := opts.Roots.certs[rootNum]
err = root.isValid(rootCertificate, opts)
}
// VerifyHostname returns nil if c is a valid certificate for the named host.
-// Otherwise it returns an os.Error describing the mismatch.
-func (c *Certificate) VerifyHostname(h string) os.Error {
+// Otherwise it returns an error describing the mismatch.
+func (c *Certificate) VerifyHostname(h string) error {
if len(c.DNSNames) > 0 {
for _, match := range c.DNSNames {
if matchHostnames(match, h) {
import (
"crypto/x509/pkix"
"encoding/pem"
- "os"
+ "errors"
"strings"
"testing"
)
currentTime int64
dnsName string
- errorCallback func(*testing.T, int, os.Error) bool
+ errorCallback func(*testing.T, int, error) bool
expectedChains [][]string
}
},
}
-func expectHostnameError(t *testing.T, i int, err os.Error) (ok bool) {
+func expectHostnameError(t *testing.T, i int, err error) (ok bool) {
if _, ok := err.(HostnameError); !ok {
t.Errorf("#%d: error was not a HostnameError: %s", i, err)
return false
return true
}
-func expectExpired(t *testing.T, i int, err os.Error) (ok bool) {
+func expectExpired(t *testing.T, i int, err error) (ok bool) {
if inval, ok := err.(CertificateInvalidError); !ok || inval.Reason != Expired {
t.Errorf("#%d: error was not Expired: %s", i, err)
return false
return true
}
-func expectAuthorityUnknown(t *testing.T, i int, err os.Error) (ok bool) {
+func expectAuthorityUnknown(t *testing.T, i int, err error) (ok bool) {
if _, ok := err.(UnknownAuthorityError); !ok {
t.Errorf("#%d: error was not UnknownAuthorityError: %s", i, err)
return false
return true
}
-func certificateFromPEM(pemBytes string) (*Certificate, os.Error) {
+func certificateFromPEM(pemBytes string) (*Certificate, error) {
block, _ := pem.Decode([]byte(pemBytes))
if block == nil {
- return nil, os.NewError("failed to decode PEM")
+ return nil, errors.New("failed to decode PEM")
}
return ParseCertificate(block.Bytes)
}
"crypto/sha1"
"crypto/x509/pkix"
"encoding/pem"
+ "errors"
"io"
- "os"
"time"
)
// ParsePKIXPublicKey parses a DER encoded public key. These values are
// typically found in PEM blocks with "BEGIN PUBLIC KEY".
-func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err os.Error) {
+func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
var pki publicKeyInfo
if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
return
}
algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
if algo == UnknownPublicKeyAlgorithm {
- return nil, os.NewError("ParsePKIXPublicKey: unknown public key algorithm")
+ return nil, errors.New("ParsePKIXPublicKey: unknown public key algorithm")
}
return parsePublicKey(algo, &pki)
}
// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
-func MarshalPKIXPublicKey(pub interface{}) ([]byte, os.Error) {
+func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
var pubBytes []byte
switch pub := pub.(type) {
E: pub.E,
})
default:
- return nil, os.NewError("MarshalPKIXPublicKey: unknown public key type")
+ return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
}
pkix := pkixPublicKey{
// that involves algorithms that are not currently implemented.
type UnsupportedAlgorithmError struct{}
-func (UnsupportedAlgorithmError) String() string {
+func (UnsupportedAlgorithmError) Error() string {
return "cannot verify signature: algorithm unimplemented"
}
// certificate signing key.
type ConstraintViolationError struct{}
-func (ConstraintViolationError) String() string {
+func (ConstraintViolationError) Error() string {
return "invalid signature: parent certificate cannot sign this kind of certificate"
}
// CheckSignatureFrom verifies that the signature on c is a valid signature
// from parent.
-func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err os.Error) {
+func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
// RFC 5280, 4.2.1.9:
// "If the basic constraints extension is not present in a version 3
// certificate, or the extension is present but the cA boolean is not
// CheckSignature verifies that signature is a valid signature over signed from
// c's public key.
-func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err os.Error) {
+func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
var hashType crypto.Hash
switch algo {
return err
}
if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
- return os.NewError("DSA signature contained zero or negative values")
+ return errors.New("DSA signature contained zero or negative values")
}
if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
- return os.NewError("DSA verification failure")
+ return errors.New("DSA verification failure")
}
return
}
}
// CheckCRLSignature checks that the signature in crl is from c.
-func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err os.Error) {
+func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
}
type UnhandledCriticalExtension struct{}
-func (h UnhandledCriticalExtension) String() string {
+func (h UnhandledCriticalExtension) Error() string {
return "unhandled critical extension"
}
Max int `asn1:"optional,tag:1"`
}
-func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, os.Error) {
+func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
asn1Data := keyData.PublicKey.RightAlign()
switch algo {
case RSA:
return nil, err
}
if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
- return nil, os.NewError("zero or negative DSA parameter")
+ return nil, errors.New("zero or negative DSA parameter")
}
pub := &dsa.PublicKey{
Parameters: dsa.Parameters{
panic("unreachable")
}
-func parseCertificate(in *certificate) (*Certificate, os.Error) {
+func parseCertificate(in *certificate) (*Certificate, error) {
out := new(Certificate)
out.Raw = in.Raw
out.RawTBSCertificate = in.TBSCertificate.Raw
out.PublicKeyAlgorithm =
getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
- var err os.Error
+ var err error
out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
if err != nil {
return nil, err
}
if in.TBSCertificate.SerialNumber.Sign() < 0 {
- return nil, os.NewError("negative serial number")
+ return nil, errors.New("negative serial number")
}
out.Version = in.TBSCertificate.Version + 1
}
// ParseCertificate parses a single certificate from the given ASN.1 DER data.
-func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) {
+func ParseCertificate(asn1Data []byte) (*Certificate, error) {
var cert certificate
rest, err := asn1.Unmarshal(asn1Data, &cert)
if err != nil {
// ParseCertificates parses one or more certificates from the given ASN.1 DER
// data. The certificates must be concatenated with no intermediate padding.
-func ParseCertificates(asn1Data []byte) ([]*Certificate, os.Error) {
+func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
var v []*certificate
for len(asn1Data) > 0 {
cert := new(certificate)
- var err os.Error
+ var err error
asn1Data, err = asn1.Unmarshal(asn1Data, cert)
if err != nil {
return nil, err
oidExtensionNameConstraints = []int{2, 5, 29, 30}
)
-func buildExtensions(template *Certificate) (ret []pkix.Extension, err os.Error) {
+func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
ret = make([]pkix.Extension, 7 /* maximum number of elements. */ )
n := 0
// signee and priv is the private key of the signer.
//
// The returned slice is the certificate in DER encoding.
-func CreateCertificate(rand io.Reader, template, parent *Certificate, pub *rsa.PublicKey, priv *rsa.PrivateKey) (cert []byte, err os.Error) {
+func CreateCertificate(rand io.Reader, template, parent *Certificate, pub *rsa.PublicKey, priv *rsa.PrivateKey) (cert []byte, err error) {
asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
N: pub.N,
E: pub.E,
// encoded CRLs will appear where they should be DER encoded, so this function
// will transparently handle PEM encoding as long as there isn't any leading
// garbage.
-func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err os.Error) {
+func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
block, _ := pem.Decode(crlBytes)
if block != nil && block.Type == pemType {
}
// ParseDERCRL parses a DER encoded CRL from the given bytes.
-func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err os.Error) {
+func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
certList = new(pkix.CertificateList)
_, err = asn1.Unmarshal(derBytes, certList)
if err != nil {
// CreateCRL returns a DER encoded CRL, signed by this Certificate, that
// contains the given list of revoked certificates.
-func (c *Certificate) CreateCRL(rand io.Reader, priv *rsa.PrivateKey, revokedCerts []pkix.RevokedCertificate, now, expiry *time.Time) (crlBytes []byte, err os.Error) {
+func (c *Certificate) CreateCRL(rand io.Reader, priv *rsa.PrivateKey, revokedCerts []pkix.RevokedCertificate, now, expiry *time.Time) (crlBytes []byte, err error) {
tbsCertList := pkix.TBSCertificateList{
Version: 2,
Signature: pkix.AlgorithmIdentifier{
// For details, see http://www.cix.co.uk/~klockstone/xtea.pdf
-import (
- "os"
- "strconv"
-)
+import "strconv"
// The XTEA block size in bytes.
const BlockSize = 8
type KeySizeError int
-func (k KeySizeError) String() string {
+func (k KeySizeError) Error() string {
return "crypto/xtea: invalid key size " + strconv.Itoa(int(k))
}
// NewCipher creates and returns a new Cipher.
// The key argument should be the XTEA key.
// XTEA only supports 128 bit (16 byte) keys.
-func NewCipher(key []byte) (*Cipher, os.Error) {
+func NewCipher(key []byte) (*Cipher, error) {
k := len(key)
switch k {
default:
import (
"bufio"
"bytes"
+ "errors"
"fmt"
"io"
- "os"
"unicode"
)
// A ParseError is returned for parsing errors.
// The first line is 1. The first column is 0.
type ParseError struct {
- Line int // Line where the error occurred
- Column int // Column (rune index) where the error occurred
- Error os.Error // The actual error
+ Line int // Line where the error occurred
+ Column int // Column (rune index) where the error occurred
+ Err error // The actual error
}
-func (e *ParseError) String() string {
- return fmt.Sprintf("line %d, column %d: %s", e.Line, e.Column, e.Error)
+func (e *ParseError) Error() string {
+ return fmt.Sprintf("line %d, column %d: %s", e.Line, e.Column, e.Err)
}
// These are the errors that can be returned in ParseError.Error
var (
- ErrTrailingComma = os.NewError("extra delimiter at end of line")
- ErrBareQuote = os.NewError("bare \" in non-quoted-field")
- ErrQuote = os.NewError("extraneous \" in field")
- ErrFieldCount = os.NewError("wrong number of fields in line")
+ ErrTrailingComma = errors.New("extra delimiter at end of line")
+ ErrBareQuote = errors.New("bare \" in non-quoted-field")
+ ErrQuote = errors.New("extraneous \" in field")
+ ErrFieldCount = errors.New("wrong number of fields in line")
)
// A Reader reads records from a CSV-encoded file.
}
// error creates a new ParseError based on err.
-func (r *Reader) error(err os.Error) os.Error {
+func (r *Reader) error(err error) error {
return &ParseError{
Line: r.line,
Column: r.column,
- Error: err,
+ Err: err,
}
}
// Read reads one record from r. The record is a slice of strings with each
// string representing one field.
-func (r *Reader) Read() (record []string, err os.Error) {
+func (r *Reader) Read() (record []string, err error) {
for {
record, err = r.parseRecord()
if record != nil {
// ReadAll reads all the remaining records from r.
// Each record is a slice of fields.
-func (r *Reader) ReadAll() (records [][]string, err os.Error) {
+func (r *Reader) ReadAll() (records [][]string, err error) {
for {
record, err := r.Read()
- if err == os.EOF {
+ if err == io.EOF {
return records, nil
}
if err != nil {
// readRune reads one rune from r, folding \r\n to \n and keeping track
// of how far into the line we have read. r.column will point to the start
// of this rune, not the end of this rune.
-func (r *Reader) readRune() (rune, os.Error) {
+func (r *Reader) readRune() (rune, error) {
r1, _, err := r.r.ReadRune()
// Handle \r\n here. We make the simplifying assumption that
}
// skip reads runes up to and including the rune delim or until error.
-func (r *Reader) skip(delim rune) os.Error {
+func (r *Reader) skip(delim rune) error {
for {
r1, err := r.readRune()
if err != nil {
}
// parseRecord reads and parses a single csv record from r.
-func (r *Reader) parseRecord() (fields []string, err os.Error) {
+func (r *Reader) parseRecord() (fields []string, err error) {
// Each record starts on a new line. We increment our line
// number (lines start at 1, not 0) and set column to -1
// so as we increment in readRune it points to the character we read.
if haveField {
fields = append(fields, r.field.String())
}
- if delim == '\n' || err == os.EOF {
+ if delim == '\n' || err == io.EOF {
return fields, err
} else if err != nil {
return nil, err
// parseField parses the next field in the record. The read field is
// located in r.field. Delim is the first character not part of the field
// (r.Comma or '\n').
-func (r *Reader) parseField() (haveField bool, delim rune, err os.Error) {
+func (r *Reader) parseField() (haveField bool, delim rune, err error) {
r.field.Reset()
r1, err := r.readRune()
// If we have EOF and are not at the start of a line
// then we return the empty field. We have already
// checked for trailing commas if needed.
- if err == os.EOF && r.column != 0 {
+ if err == io.EOF && r.column != 0 {
return true, 0, err
}
return false, 0, err
for {
r1, err = r.readRune()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
if r.LazyQuotes {
return true, 0, err
}
}
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
return true, 0, err
}
return false, 0, err
}
}
}
- if err == os.EOF || r1 == '\n' {
+ if err == io.EOF || r1 == '\n' {
r.column = c // report the comma
return false, 0, r.error(ErrTrailingComma)
}
out, err := r.ReadAll()
perr, _ := err.(*ParseError)
if tt.Error != "" {
- if err == nil || !strings.Contains(err.String(), tt.Error) {
+ if err == nil || !strings.Contains(err.Error(), tt.Error) {
t.Errorf("%s: error %v, want error %q", tt.Name, err, tt.Error)
} else if tt.Line != 0 && (tt.Line != perr.Line || tt.Column != perr.Column) {
t.Errorf("%s: error at %d:%d expected %d:%d", tt.Name, perr.Line, perr.Column, tt.Line, tt.Column)
import (
"bufio"
"io"
- "os"
"strings"
"unicode"
"utf8"
// Writer writes a single CSV record to w along with any necessary quoting.
// A record is a slice of strings with each string being one field.
-func (w *Writer) Write(record []string) (err os.Error) {
+func (w *Writer) Write(record []string) (err error) {
for n, field := range record {
if n > 0 {
if _, err = w.w.WriteRune(w.Comma); err != nil {
}
// WriteAll writes multiple CSV records to w using Write and then calls Flush.
-func (w *Writer) WriteAll(records [][]string) (err os.Error) {
+func (w *Writer) WriteAll(records [][]string) (err error) {
for _, record := range records {
err = w.Write(record)
if err != nil {
import (
"encoding/binary"
- "os"
"strconv"
)
off Offset
data []byte
addrsize int
- err os.Error
+ err error
}
func makeBuf(d *Data, name string, off Offset, data []byte, addrsize int) buf {
type DecodeError struct {
Name string
Offset Offset
- Error string
+ Err string
}
-func (e DecodeError) String() string {
- return "decoding dwarf section " + e.Name + " at offset 0x" + strconv.Itob64(int64(e.Offset), 16) + ": " + e.Error
+func (e DecodeError) Error() string {
+ return "decoding dwarf section " + e.Name + " at offset 0x" + strconv.Itob64(int64(e.Offset), 16) + ": " + e.Err
}
package dwarf
-import "os"
+import "errors"
// a single entry's description: a sequence of attributes
type abbrev struct {
// ParseAbbrev returns the abbreviation table that starts at byte off
// in the .debug_abbrev section.
-func (d *Data) parseAbbrev(off uint32) (abbrevTable, os.Error) {
+func (d *Data) parseAbbrev(off uint32) (abbrevTable, error) {
if m, ok := d.abbrevCache[off]; ok {
return m, nil
}
type Reader struct {
b buf
d *Data
- err os.Error
+ err error
unit int
lastChildren bool // .Children of last entry returned by Next
lastSibling Offset // .Val(AttrSibling) of last entry returned by Next
return
}
}
- r.err = os.NewError("offset out of range")
+ r.err = errors.New("offset out of range")
}
// maybeNextUnit advances to the next unit if this one is finished.
// It returns nil, nil when it reaches the end of the section.
// It returns an error if the current offset is invalid or the data at the
// offset cannot be decoded as a valid Entry.
-func (r *Reader) Next() (*Entry, os.Error) {
+func (r *Reader) Next() (*Entry, error) {
if r.err != nil {
return nil, r.err
}
// http://dwarfstd.org/doc/dwarf-2.0.0.pdf
package dwarf
-import (
- "encoding/binary"
- "os"
-)
+import "encoding/binary"
// Data represents the DWARF debugging information
// loaded from an executable file (for example, an ELF or Mach-O executable).
// The []byte arguments are the data from the corresponding debug section
// in the object file; for example, for an ELF object, abbrev is the contents of
// the ".debug_abbrev" section.
-func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, os.Error) {
+func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error) {
d := &Data{
abbrev: abbrev,
aranges: aranges,
package dwarf
-import (
- "os"
- "strconv"
-)
+import "strconv"
// A Type conventionally represents a pointer to any of the
// specific Type structures (CharType, StructType, etc.).
func (t *TypedefType) Size() int64 { return t.Type.Size() }
-func (d *Data) Type(off Offset) (Type, os.Error) {
+func (d *Data) Type(off Offset) (Type, error) {
if t, ok := d.typeCache[off]; ok {
return t, nil
}
package dwarf
-import (
- "os"
- "strconv"
-)
+import "strconv"
// DWARF debug info is split into a sequence of compilation units.
// Each unit has its own abbreviation table and address size.
addrsize int
}
-func (d *Data) parseUnits() ([]unit, os.Error) {
+func (d *Data) parseUnits() ([]unit, error) {
// Count units.
nunit := 0
b := makeBuf(d, "info", 0, d.info, 0)
"bytes"
"debug/dwarf"
"encoding/binary"
+ "errors"
"fmt"
"io"
"os"
}
// Data reads and returns the contents of the ELF section.
-func (s *Section) Data() ([]byte, os.Error) {
+func (s *Section) Data() ([]byte, error) {
dat := make([]byte, s.sr.Size())
n, err := s.sr.ReadAt(dat, 0)
return dat[0:n], err
// stringTable reads and returns the string table given by the
// specified link value.
-func (f *File) stringTable(link uint32) ([]byte, os.Error) {
+func (f *File) stringTable(link uint32) ([]byte, error) {
if link <= 0 || link >= uint32(len(f.Sections)) {
- return nil, os.NewError("section has invalid string table link")
+ return nil, errors.New("section has invalid string table link")
}
return f.Sections[link].Data()
}
val interface{}
}
-func (e *FormatError) String() string {
+func (e *FormatError) Error() string {
msg := e.msg
if e.val != nil {
msg += fmt.Sprintf(" '%v' ", e.val)
}
// Open opens the named file using os.Open and prepares it for use as an ELF binary.
-func Open(name string) (*File, os.Error) {
+func Open(name string) (*File, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
// Close closes the File.
// If the File was created using NewFile directly instead of Open,
// Close has no effect.
-func (f *File) Close() os.Error {
- var err os.Error
+func (f *File) Close() error {
+ var err error
if f.closer != nil {
err = f.closer.Close()
f.closer = nil
// NewFile creates a new File for accessing an ELF binary in an underlying reader.
// The ELF binary is expected to start at position 0 in the ReaderAt.
-func NewFile(r io.ReaderAt) (*File, os.Error) {
+func NewFile(r io.ReaderAt) (*File, error) {
sr := io.NewSectionReader(r, 0, 1<<63-1)
// Read and decode ELF identifier
var ident [16]uint8
// getSymbols returns a slice of Symbols from parsing the symbol table
// with the given type, along with the associated string table.
-func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, os.Error) {
+func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, error) {
switch f.Class {
case ELFCLASS64:
return f.getSymbols64(typ)
return f.getSymbols32(typ)
}
- return nil, nil, os.NewError("not implemented")
+ return nil, nil, errors.New("not implemented")
}
-func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, os.Error) {
+func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, error) {
symtabSection := f.SectionByType(typ)
if symtabSection == nil {
- return nil, nil, os.NewError("no symbol section")
+ return nil, nil, errors.New("no symbol section")
}
data, err := symtabSection.Data()
if err != nil {
- return nil, nil, os.NewError("cannot load symbol section")
+ return nil, nil, errors.New("cannot load symbol section")
}
symtab := bytes.NewBuffer(data)
if symtab.Len()%Sym32Size != 0 {
- return nil, nil, os.NewError("length of symbol section is not a multiple of SymSize")
+ return nil, nil, errors.New("length of symbol section is not a multiple of SymSize")
}
strdata, err := f.stringTable(symtabSection.Link)
if err != nil {
- return nil, nil, os.NewError("cannot load string table section")
+ return nil, nil, errors.New("cannot load string table section")
}
// The first entry is all zeros.
return symbols, strdata, nil
}
-func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, os.Error) {
+func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, error) {
symtabSection := f.SectionByType(typ)
if symtabSection == nil {
- return nil, nil, os.NewError("no symbol section")
+ return nil, nil, errors.New("no symbol section")
}
data, err := symtabSection.Data()
if err != nil {
- return nil, nil, os.NewError("cannot load symbol section")
+ return nil, nil, errors.New("cannot load symbol section")
}
symtab := bytes.NewBuffer(data)
if symtab.Len()%Sym64Size != 0 {
- return nil, nil, os.NewError("length of symbol section is not a multiple of Sym64Size")
+ return nil, nil, errors.New("length of symbol section is not a multiple of Sym64Size")
}
strdata, err := f.stringTable(symtabSection.Link)
if err != nil {
- return nil, nil, os.NewError("cannot load string table section")
+ return nil, nil, errors.New("cannot load string table section")
}
// The first entry is all zeros.
// applyRelocations applies relocations to dst. rels is a relocations section
// in RELA format.
-func (f *File) applyRelocations(dst []byte, rels []byte) os.Error {
+func (f *File) applyRelocations(dst []byte, rels []byte) error {
if f.Class == ELFCLASS64 && f.Machine == EM_X86_64 {
return f.applyRelocationsAMD64(dst, rels)
}
- return os.NewError("not implemented")
+ return errors.New("not implemented")
}
-func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) os.Error {
+func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) error {
if len(rels)%Sym64Size != 0 {
- return os.NewError("length of relocation section is not a multiple of Sym64Size")
+ return errors.New("length of relocation section is not a multiple of Sym64Size")
}
symbols, _, err := f.getSymbols(SHT_SYMTAB)
return nil
}
-func (f *File) DWARF() (*dwarf.Data, os.Error) {
+func (f *File) DWARF() (*dwarf.Data, error) {
// There are many other DWARF sections, but these
// are the required ones, and the debug/dwarf package
// does not use the others, so don't bother loading them.
}
// Symbols returns the symbol table for f.
-func (f *File) Symbols() ([]Symbol, os.Error) {
+func (f *File) Symbols() ([]Symbol, error) {
sym, _, err := f.getSymbols(SHT_SYMTAB)
return sym, err
}
// referred to by the binary f that are expected to be
// satisfied by other libraries at dynamic load time.
// It does not return weak symbols.
-func (f *File) ImportedSymbols() ([]ImportedSymbol, os.Error) {
+func (f *File) ImportedSymbols() ([]ImportedSymbol, error) {
sym, str, err := f.getSymbols(SHT_DYNSYM)
if err != nil {
return nil, err
// ImportedLibraries returns the names of all libraries
// referred to by the binary f that are expected to be
// linked with the binary at dynamic link time.
-func (f *File) ImportedLibraries() ([]string, os.Error) {
+func (f *File) ImportedLibraries() ([]string, error) {
ds := f.SectionByType(SHT_DYNAMIC)
if ds == nil {
// not dynamic, so no libraries
import (
"encoding/binary"
"fmt"
- "os"
"strconv"
"strings"
)
name []byte
}
-func walksymtab(data []byte, fn func(sym) os.Error) os.Error {
+func walksymtab(data []byte, fn func(sym) error) error {
var s sym
p := data
for len(p) >= 6 {
// NewTable decodes the Go symbol table in data,
// returning an in-memory representation.
-func NewTable(symtab []byte, pcln *LineTable) (*Table, os.Error) {
+func NewTable(symtab []byte, pcln *LineTable) (*Table, error) {
var n int
- err := walksymtab(symtab, func(s sym) os.Error {
+ err := walksymtab(symtab, func(s sym) error {
n++
return nil
})
nf := 0
nz := 0
lasttyp := uint8(0)
- err = walksymtab(symtab, func(s sym) os.Error {
+ err = walksymtab(symtab, func(s sym) error {
n := len(t.Syms)
t.Syms = t.Syms[0 : n+1]
ts := &t.Syms[n]
// LineToPC looks up the first program counter on the given line in
// the named file. Returns UnknownPathError or UnknownLineError if
// there is an error looking up this line.
-func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err os.Error) {
+func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error) {
obj, ok := t.Files[file]
if !ok {
return 0, nil, UnknownFileError(file)
return tos.path, aline - tos.start - tos.offset + 1
}
-func (o *Obj) alineFromLine(path string, line int) (int, os.Error) {
+func (o *Obj) alineFromLine(path string, line int) (int, error) {
if line < 1 {
return 0, &UnknownLineError{path, line}
}
// the symbol table.
type UnknownFileError string
-func (e UnknownFileError) String() string { return "unknown file: " + string(e) }
+func (e UnknownFileError) Error() string { return "unknown file: " + string(e) }
// UnknownLineError represents a failure to map a line to a program
// counter, either because the line is beyond the bounds of the file
Line int
}
-func (e *UnknownLineError) String() string {
+func (e *UnknownLineError) Error() string {
return "no code at " + e.File + ":" + strconv.Itoa(e.Line)
}
val interface{}
}
-func (e *DecodingError) String() string {
+func (e *DecodingError) Error() string {
msg := e.msg
if e.val != nil {
msg += fmt.Sprintf(" '%v'", e.val)
"bytes"
"debug/dwarf"
"encoding/binary"
+ "errors"
"fmt"
"io"
"os"
}
// Data reads and returns the contents of the segment.
-func (s *Segment) Data() ([]byte, os.Error) {
+func (s *Segment) Data() ([]byte, error) {
dat := make([]byte, s.sr.Size())
n, err := s.sr.ReadAt(dat, 0)
return dat[0:n], err
}
// Data reads and returns the contents of the Mach-O section.
-func (s *Section) Data() ([]byte, os.Error) {
+func (s *Section) Data() ([]byte, error) {
dat := make([]byte, s.sr.Size())
n, err := s.sr.ReadAt(dat, 0)
return dat[0:n], err
val interface{}
}
-func (e *FormatError) String() string {
+func (e *FormatError) Error() string {
msg := e.msg
if e.val != nil {
msg += fmt.Sprintf(" '%v'", e.val)
}
// Open opens the named file using os.Open and prepares it for use as a Mach-O binary.
-func Open(name string) (*File, os.Error) {
+func Open(name string) (*File, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
// Close closes the File.
// If the File was created using NewFile directly instead of Open,
// Close has no effect.
-func (f *File) Close() os.Error {
- var err os.Error
+func (f *File) Close() error {
+ var err error
if f.closer != nil {
err = f.closer.Close()
f.closer = nil
// NewFile creates a new File for accessing a Mach-O binary in an underlying reader.
// The Mach-O binary is expected to start at position 0 in the ReaderAt.
-func NewFile(r io.ReaderAt) (*File, os.Error) {
+func NewFile(r io.ReaderAt) (*File, error) {
f := new(File)
sr := io.NewSectionReader(r, 0, 1<<63-1)
return f, nil
}
-func (f *File) parseSymtab(symdat, strtab, cmddat []byte, hdr *SymtabCmd, offset int64) (*Symtab, os.Error) {
+func (f *File) parseSymtab(symdat, strtab, cmddat []byte, hdr *SymtabCmd, offset int64) (*Symtab, error) {
bo := f.ByteOrder
symtab := make([]Symbol, hdr.Nsyms)
b := bytes.NewBuffer(symdat)
}
// DWARF returns the DWARF debug information for the Mach-O file.
-func (f *File) DWARF() (*dwarf.Data, os.Error) {
+func (f *File) DWARF() (*dwarf.Data, error) {
// There are many other DWARF sections, but these
// are the required ones, and the debug/dwarf package
// does not use the others, so don't bother loading them.
name = "__debug_" + name
s := f.Section(name)
if s == nil {
- return nil, os.NewError("missing Mach-O section " + name)
+ return nil, errors.New("missing Mach-O section " + name)
}
b, err := s.Data()
if err != nil && uint64(len(b)) < s.Size {
// ImportedSymbols returns the names of all symbols
// referred to by the binary f that are expected to be
// satisfied by other libraries at dynamic load time.
-func (f *File) ImportedSymbols() ([]string, os.Error) {
+func (f *File) ImportedSymbols() ([]string, error) {
if f.Dysymtab == nil || f.Symtab == nil {
return nil, &FormatError{0, "missing symbol table", nil}
}
// ImportedLibraries returns the paths of all libraries
// referred to by the binary f that are expected to be
// linked with the binary at dynamic link time.
-func (f *File) ImportedLibraries() ([]string, os.Error) {
+func (f *File) ImportedLibraries() ([]string, error) {
var all []string
for _, l := range f.Loads {
if lib, ok := l.(*Dylib); ok {
import (
"debug/dwarf"
"encoding/binary"
+ "errors"
"fmt"
"io"
"os"
}
// Data reads and returns the contents of the PE section.
-func (s *Section) Data() ([]byte, os.Error) {
+func (s *Section) Data() ([]byte, error) {
dat := make([]byte, s.sr.Size())
n, err := s.sr.ReadAt(dat, 0)
return dat[0:n], err
val interface{}
}
-func (e *FormatError) String() string {
+func (e *FormatError) Error() string {
msg := e.msg
if e.val != nil {
msg += fmt.Sprintf(" '%v'", e.val)
}
// Open opens the named file using os.Open and prepares it for use as a PE binary.
-func Open(name string) (*File, os.Error) {
+func Open(name string) (*File, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
// Close closes the File.
// If the File was created using NewFile directly instead of Open,
// Close has no effect.
-func (f *File) Close() os.Error {
- var err os.Error
+func (f *File) Close() error {
+ var err error
if f.closer != nil {
err = f.closer.Close()
f.closer = nil
}
// NewFile creates a new File for accessing a PE binary in an underlying reader.
-func NewFile(r io.ReaderAt) (*File, os.Error) {
+func NewFile(r io.ReaderAt) (*File, error) {
f := new(File)
sr := io.NewSectionReader(r, 0, 1<<63-1)
var sign [4]byte
r.ReadAt(sign[0:], int64(dosheader[0x3c]))
if !(sign[0] == 'P' && sign[1] == 'E' && sign[2] == 0 && sign[3] == 0) {
- return nil, os.NewError("Invalid PE File Format.")
+ return nil, errors.New("Invalid PE File Format.")
}
base = int64(dosheader[0x3c]) + 4
} else {
return nil, err
}
if f.FileHeader.Machine != IMAGE_FILE_MACHINE_UNKNOWN && f.FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64 && f.FileHeader.Machine != IMAGE_FILE_MACHINE_I386 {
- return nil, os.NewError("Invalid PE File Format.")
+ return nil, errors.New("Invalid PE File Format.")
}
// get symbol string table
sr.Seek(int64(f.FileHeader.PointerToSymbolTable+18*f.FileHeader.NumberOfSymbols), os.SEEK_SET)
return nil
}
-func (f *File) DWARF() (*dwarf.Data, os.Error) {
+func (f *File) DWARF() (*dwarf.Data, error) {
// There are many other DWARF sections, but these
// are the required ones, and the debug/dwarf package
// does not use the others, so don't bother loading them.
// referred to by the binary f that are expected to be
// satisfied by other libraries at dynamic load time.
// It does not return weak symbols.
-func (f *File) ImportedSymbols() ([]string, os.Error) {
+func (f *File) ImportedSymbols() ([]string, error) {
pe64 := f.Machine == IMAGE_FILE_MACHINE_AMD64
ds := f.Section(".idata")
if ds == nil {
// ImportedLibraries returns the names of all libraries
// referred to by the binary f that are expected to be
// linked with the binary at dynamic link time.
-func (f *File) ImportedLibraries() ([]string, os.Error) {
+func (f *File) ImportedLibraries() ([]string, error) {
// TODO
// cgo -dynimport don't use this for windows PE, so just return.
return nil, nil
import (
"io"
- "os"
"strconv"
)
func NewEncoder(w io.Writer) io.WriteCloser { return &encoder{w: w} }
type encoder struct {
- err os.Error
+ err error
w io.Writer
buf [4]byte // buffered data waiting to be encoded
nbuf int // number of bytes in buf
out [1024]byte // output buffer
}
-func (e *encoder) Write(p []byte) (n int, err os.Error) {
+func (e *encoder) Write(p []byte) (n int, err error) {
if e.err != nil {
return 0, e.err
}
// Close flushes any pending output from the encoder.
// It is an error to call Write after calling Close.
-func (e *encoder) Close() os.Error {
+func (e *encoder) Close() error {
// If there's anything left in the buffer, flush it out
if e.err == nil && e.nbuf > 0 {
nout := Encode(e.out[0:], e.buf[0:e.nbuf])
type CorruptInputError int64
-func (e CorruptInputError) String() string {
+func (e CorruptInputError) Error() string {
return "illegal ascii85 data at input byte " + strconv.Itoa64(int64(e))
}
//
// NewDecoder wraps an io.Reader interface around Decode.
//
-func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err os.Error) {
+func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error) {
var v uint32
var nb int
for i, b := range src {
func NewDecoder(r io.Reader) io.Reader { return &decoder{r: r} }
type decoder struct {
- err os.Error
- readErr os.Error
+ err error
+ readErr error
r io.Reader
end bool // saw end of message
buf [1024]byte // leftover input
outbuf [1024]byte
}
-func (d *decoder) Read(p []byte) (n int, err os.Error) {
+func (d *decoder) Read(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
import (
"bytes"
+ "io"
"io/ioutil"
- "os"
"testing"
)
end = len(input)
}
n, err := encoder.Write(input[pos:end])
- testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, os.Error(nil))
+ testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil))
testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos)
}
err := encoder.Close()
- testEqual(t, "Close gave error %v, want %v", err, os.Error(nil))
+ testEqual(t, "Close gave error %v, want %v", err, error(nil))
testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, strip85(bb.String()), strip85(bigtest.encoded))
}
}
for _, p := range pairs {
dbuf := make([]byte, 4*len(p.encoded))
ndst, nsrc, err := Decode(dbuf, []byte(p.encoded), true)
- testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
+ testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil))
testEqual(t, "Decode(%q) = nsrc %v, want %v", p.encoded, nsrc, len(p.encoded))
testEqual(t, "Decode(%q) = ndst %v, want %v", p.encoded, ndst, len(p.decoded))
testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:ndst]), p.decoded)
testEqual(t, "Read from %q = length %v, want %v", p.encoded, len(dbuf), len(p.decoded))
testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf), p.decoded)
if err != nil {
- testEqual(t, "Read from %q = %v, want %v", p.encoded, err, os.EOF)
+ testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF)
}
}
}
var total int
for total = 0; total < len(bigtest.decoded); {
n, err := decoder.Read(buf[total : total+bs])
- testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, os.Error(nil))
+ testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, error(nil))
total += n
}
testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded)
import (
"io"
- "os"
"strconv"
)
}
type encoder struct {
- err os.Error
+ err error
enc *Encoding
w io.Writer
buf [5]byte // buffered data waiting to be encoded
out [1024]byte // output buffer
}
-func (e *encoder) Write(p []byte) (n int, err os.Error) {
+func (e *encoder) Write(p []byte) (n int, err error) {
if e.err != nil {
return 0, e.err
}
// Close flushes any pending output from the encoder.
// It is an error to call Write after calling Close.
-func (e *encoder) Close() os.Error {
+func (e *encoder) Close() error {
// If there's anything left in the buffer, flush it out
if e.err == nil && e.nbuf > 0 {
e.enc.Encode(e.out[0:], e.buf[0:e.nbuf])
type CorruptInputError int64
-func (e CorruptInputError) String() string {
+func (e CorruptInputError) Error() string {
return "illegal base32 data at input byte " + strconv.Itoa64(int64(e))
}
// indicates if end-of-message padding was encountered and thus any
// additional data is an error. decode also assumes len(src)%8==0,
// since it is meant for internal use.
-func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err os.Error) {
+func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
for i := 0; i < len(src)/8 && !end; i++ {
// Decode quantum using the base32 alphabet
var dbuf [8]byte
// DecodedLen(len(src)) bytes to dst and returns the number of bytes
// written. If src contains invalid base32 data, it will return the
// number of bytes successfully written and CorruptInputError.
-func (enc *Encoding) Decode(dst, src []byte) (n int, err os.Error) {
+func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
if len(src)%8 != 0 {
return 0, CorruptInputError(len(src) / 8 * 8)
}
}
type decoder struct {
- err os.Error
+ err error
enc *Encoding
r io.Reader
end bool // saw end of message
outbuf [1024 / 8 * 5]byte
}
-func (d *decoder) Read(p []byte) (n int, err os.Error) {
+func (d *decoder) Read(p []byte) (n int, err error) {
if d.err != nil {
return 0, d.err
}
import (
"bytes"
+ "io"
"io/ioutil"
- "os"
"testing"
)
end = len(input)
}
n, err := encoder.Write(input[pos:end])
- testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, os.Error(nil))
+ testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil))
testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos)
}
err := encoder.Close()
- testEqual(t, "Close gave error %v, want %v", err, os.Error(nil))
+ testEqual(t, "Close gave error %v, want %v", err, error(nil))
testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, bb.String(), bigtest.encoded)
}
}
for _, p := range pairs {
dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded)))
count, end, err := StdEncoding.decode(dbuf, []byte(p.encoded))
- testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
+ testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil))
testEqual(t, "Decode(%q) = length %v, want %v", p.encoded, count, len(p.decoded))
if len(p.encoded) > 0 {
testEqual(t, "Decode(%q) = end %v, want %v", p.encoded, end, (p.encoded[len(p.encoded)-1] == '='))
decoder := NewDecoder(StdEncoding, bytes.NewBufferString(p.encoded))
dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded)))
count, err := decoder.Read(dbuf)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
t.Fatal("Read failed", err)
}
testEqual(t, "Read from %q = length %v, want %v", p.encoded, count, len(p.decoded))
testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded)
- if err != os.EOF {
+ if err != io.EOF {
count, err = decoder.Read(dbuf)
}
- testEqual(t, "Read from %q = %v, want %v", p.encoded, err, os.EOF)
+ testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF)
}
}
var total int
for total = 0; total < len(bigtest.decoded); {
n, err := decoder.Read(buf[total : total+bs])
- testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, os.Error(nil))
+ testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, error(nil))
total += n
}
testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded)
import (
"io"
- "os"
"strconv"
)
}
type encoder struct {
- err os.Error
+ err error
enc *Encoding
w io.Writer
buf [3]byte // buffered data waiting to be encoded
out [1024]byte // output buffer
}
-func (e *encoder) Write(p []byte) (n int, err os.Error) {
+func (e *encoder) Write(p []byte) (n int, err error) {
if e.err != nil {
return 0, e.err
}
// Close flushes any pending output from the encoder.
// It is an error to call Write after calling Close.
-func (e *encoder) Close() os.Error {
+func (e *encoder) Close() error {
// If there's anything left in the buffer, flush it out
if e.err == nil && e.nbuf > 0 {
e.enc.Encode(e.out[0:], e.buf[0:e.nbuf])
type CorruptInputError int64
-func (e CorruptInputError) String() string {
+func (e CorruptInputError) Error() string {
return "illegal base64 data at input byte " + strconv.Itoa64(int64(e))
}
// indicates if end-of-message padding was encountered and thus any
// additional data is an error. decode also assumes len(src)%4==0,
// since it is meant for internal use.
-func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err os.Error) {
+func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
for i := 0; i < len(src)/4 && !end; i++ {
// Decode quantum using the base64 alphabet
var dbuf [4]byte
// DecodedLen(len(src)) bytes to dst and returns the number of bytes
// written. If src contains invalid base64 data, it will return the
// number of bytes successfully written and CorruptInputError.
-func (enc *Encoding) Decode(dst, src []byte) (n int, err os.Error) {
+func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
if len(src)%4 != 0 {
return 0, CorruptInputError(len(src) / 4 * 4)
}
}
// DecodeString returns the bytes represented by the base64 string s.
-func (enc *Encoding) DecodeString(s string) ([]byte, os.Error) {
+func (enc *Encoding) DecodeString(s string) ([]byte, error) {
dbuf := make([]byte, enc.DecodedLen(len(s)))
n, err := enc.Decode(dbuf, []byte(s))
return dbuf[:n], err
}
type decoder struct {
- err os.Error
+ err error
enc *Encoding
r io.Reader
end bool // saw end of message
outbuf [1024 / 4 * 3]byte
}
-func (d *decoder) Read(p []byte) (n int, err os.Error) {
+func (d *decoder) Read(p []byte) (n int, err error) {
if d.err != nil {
return 0, d.err
}
import (
"bytes"
+ "io"
"io/ioutil"
- "os"
"testing"
)
end = len(input)
}
n, err := encoder.Write(input[pos:end])
- testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, os.Error(nil))
+ testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil))
testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos)
}
err := encoder.Close()
- testEqual(t, "Close gave error %v, want %v", err, os.Error(nil))
+ testEqual(t, "Close gave error %v, want %v", err, error(nil))
testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, bb.String(), bigtest.encoded)
}
}
for _, p := range pairs {
dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded)))
count, end, err := StdEncoding.decode(dbuf, []byte(p.encoded))
- testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
+ testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil))
testEqual(t, "Decode(%q) = length %v, want %v", p.encoded, count, len(p.decoded))
if len(p.encoded) > 0 {
testEqual(t, "Decode(%q) = end %v, want %v", p.encoded, end, (p.encoded[len(p.encoded)-1] == '='))
testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded)
dbuf, err = StdEncoding.DecodeString(p.encoded)
- testEqual(t, "DecodeString(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
+ testEqual(t, "DecodeString(%q) = error %v, want %v", p.encoded, err, error(nil))
testEqual(t, "DecodeString(%q) = %q, want %q", string(dbuf), p.decoded)
}
}
decoder := NewDecoder(StdEncoding, bytes.NewBufferString(p.encoded))
dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded)))
count, err := decoder.Read(dbuf)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
t.Fatal("Read failed", err)
}
testEqual(t, "Read from %q = length %v, want %v", p.encoded, count, len(p.decoded))
testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded)
- if err != os.EOF {
+ if err != io.EOF {
count, err = decoder.Read(dbuf)
}
- testEqual(t, "Read from %q = %v, want %v", p.encoded, err, os.EOF)
+ testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF)
}
}
var total int
for total = 0; total < len(bigtest.decoded); {
n, err := decoder.Read(buf[total : total+bs])
- testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, os.Error(nil))
+ testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, error(nil))
total += n
}
testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded)
package binary
import (
+ "errors"
"math"
"io"
- "os"
"reflect"
)
// or an array or struct containing only fixed-size values.
// Bytes read from r are decoded using the specified byte order
// and written to successive fields of the data.
-func Read(r io.Reader, order ByteOrder, data interface{}) os.Error {
+func Read(r io.Reader, order ByteOrder, data interface{}) error {
// Fast path for basic types.
if n := intDestSize(data); n != 0 {
var b [8]byte
case reflect.Slice:
v = d
default:
- return os.NewError("binary.Read: invalid type " + d.Type().String())
+ return errors.New("binary.Read: invalid type " + d.Type().String())
}
size := TotalSize(v)
if size < 0 {
- return os.NewError("binary.Read: invalid type " + v.Type().String())
+ return errors.New("binary.Read: invalid type " + v.Type().String())
}
d := &decoder{order: order, buf: make([]byte, size)}
if _, err := io.ReadFull(r, d.buf); err != nil {
// or an array or struct containing only fixed-size values.
// Bytes written to w are encoded using the specified byte order
// and read from successive fields of the data.
-func Write(w io.Writer, order ByteOrder, data interface{}) os.Error {
+func Write(w io.Writer, order ByteOrder, data interface{}) error {
// Fast path for basic types.
var b [8]byte
var bs []byte
v := reflect.Indirect(reflect.ValueOf(data))
size := TotalSize(v)
if size < 0 {
- return os.NewError("binary.Write: invalid type " + v.Type().String())
+ return errors.New("binary.Write: invalid type " + v.Type().String())
}
buf := make([]byte, size)
e := &encoder{order: order, buf: buf}
import (
"bytes"
"io"
+ "bytes"
"math"
- "os"
"reflect"
"testing"
)
var src = []byte{1, 2, 3, 4, 5, 6, 7, 8}
var res = []int32{0x01020304, 0x05060708}
-func checkResult(t *testing.T, dir string, order ByteOrder, err os.Error, have, want interface{}) {
+func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, want interface{}) {
if err != nil {
t.Errorf("%v %v: %v", dir, order, err)
return
remain []byte
}
-func (br *byteSliceReader) Read(p []byte) (int, os.Error) {
+func (br *byteSliceReader) Read(p []byte) (int, error) {
n := copy(p, br.remain)
br.remain = br.remain[n:]
return n, nil
// format incompatible with a varint encoding for larger numbers (say 128-bit).
import (
+ "errors"
"io"
- "os"
)
// MaxVarintLenN is the maximum length of a varint-encoded N-bit integer.
}
// WriteUvarint encodes x and writes the result to w.
-func WriteUvarint(w io.Writer, x uint64) os.Error {
+func WriteUvarint(w io.Writer, x uint64) error {
var buf [MaxVarintLen64]byte
n := PutUvarint(buf[:], x)
_, err := w.Write(buf[0:n])
return err
}
-var overflow = os.NewError("binary: varint overflows a 64-bit integer")
+var overflow = errors.New("binary: varint overflows a 64-bit integer")
// ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64.
-func ReadUvarint(r io.ByteReader) (uint64, os.Error) {
+func ReadUvarint(r io.ByteReader) (uint64, error) {
var x uint64
var s uint
for i := 0; ; i++ {
}
// WriteVarint encodes x and writes the result to w.
-func WriteVarint(w io.Writer, x int64) os.Error {
+func WriteVarint(w io.Writer, x int64) error {
ux := uint64(x) << 1
if x < 0 {
ux = ^ux
}
// ReadVarint reads an encoded unsigned integer from r and returns it as a uint64.
-func ReadVarint(r io.ByteReader) (int64, os.Error) {
+func ReadVarint(r io.ByteReader) (int64, error) {
ux, err := ReadUvarint(r) // ok to continue in presence of error
x := int64(ux >> 1)
if ux&1 != 0 {
import (
"bytes"
- "os"
+ "io"
"testing"
)
}
x, err := ReadUvarint(bytes.NewBuffer(buf))
- if x != 0 || err != os.EOF {
+ if x != 0 || err != io.EOF {
t.Errorf("ReadUvarint(%v): got x = %d, err = %s", buf, x, err)
}
}
}
-func testOverflow(t *testing.T, buf []byte, n0 int, err0 os.Error) {
+func testOverflow(t *testing.T, buf []byte, n0 int, err0 error) {
x, n := Uvarint(buf)
if x != 0 || n != n0 {
t.Errorf("Uvarint(%v): got x = %d, n = %d; want 0, %d", buf, x, n, n0)
import (
"bytes"
"io"
- "os"
"strconv"
)
type CorruptInputError int64
-func (e CorruptInputError) String() string {
+func (e CorruptInputError) Error() string {
return "illegal git85 data at input byte " + strconv.Itoa64(int64(e))
}
//
// If Decode encounters invalid input, it returns a CorruptInputError.
//
-func Decode(dst, src []byte) (n int, err os.Error) {
+func Decode(dst, src []byte) (n int, err error) {
ndst := 0
nsrc := 0
for nsrc < len(src) {
type encoder struct {
w io.Writer
- err os.Error
+ err error
buf [52]byte
nbuf int
out [1024]byte
nout int
}
-func (e *encoder) Write(p []byte) (n int, err os.Error) {
+func (e *encoder) Write(p []byte) (n int, err error) {
if e.err != nil {
return 0, e.err
}
return
}
-func (e *encoder) Close() os.Error {
+func (e *encoder) Close() error {
// If there's anything left in the buffer, flush it out
if e.err == nil && e.nbuf > 0 {
nout := Encode(e.out[0:], e.buf[0:e.nbuf])
type decoder struct {
r io.Reader
- err os.Error
- readErr os.Error
+ err error
+ readErr error
buf [1024]byte
nbuf int
out []byte
off int64
}
-func (d *decoder) Read(p []byte) (n int, err os.Error) {
+func (d *decoder) Read(p []byte) (n int, err error) {
if len(p) == 0 {
return 0, nil
}
import (
"bytes"
+ "io"
"io/ioutil"
- "os"
"testing"
)
end = len(input)
}
n, err := encoder.Write(input[pos:end])
- testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, os.Error(nil))
+ testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil))
testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos)
}
err := encoder.Close()
- testEqual(t, "Close gave error %v, want %v", err, os.Error(nil))
+ testEqual(t, "Close gave error %v, want %v", err, error(nil))
testEqual(t, "Encoding/%d of %q = %q, want %q", bs, gitBigtest.decoded, bb.String(), gitBigtest.encoded)
}
}
for _, p := range gitPairs {
dbuf := make([]byte, 4*len(p.encoded))
ndst, err := Decode(dbuf, []byte(p.encoded))
- testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, os.Error(nil))
+ testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil))
testEqual(t, "Decode(%q) = ndst %v, want %v", p.encoded, ndst, len(p.decoded))
testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:ndst]), p.decoded)
}
testEqual(t, "Read from %q = length %v, want %v", p.encoded, len(dbuf), len(p.decoded))
testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf), p.decoded)
if err != nil {
- testEqual(t, "Read from %q = %v, want %v", p.encoded, err, os.EOF)
+ testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF)
}
}
}
var total int
for total = 0; total < len(gitBigtest.decoded); {
n, err := decoder.Read(buf[total : total+bs])
- testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", gitBigtest.encoded, total, n, err, os.Error(nil))
+ testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", gitBigtest.encoded, total, n, err, error(nil))
total += n
}
testEqual(t, "Decoding/%d of %q = %q, want %q", bs, gitBigtest.encoded, string(buf[0:total]), gitBigtest.decoded)
import (
"bytes"
"io"
- "os"
"strconv"
)
// OddLengthInputError results from decoding an odd length slice.
type OddLengthInputError struct{}
-func (OddLengthInputError) String() string { return "odd length hex string" }
+func (OddLengthInputError) Error() string { return "odd length hex string" }
// InvalidHexCharError results from finding an invalid character in a hex string.
type InvalidHexCharError byte
-func (e InvalidHexCharError) String() string {
+func (e InvalidHexCharError) Error() string {
return "invalid hex char: " + strconv.Itoa(int(e))
}
//
// If Decode encounters invalid input, it returns an OddLengthInputError or an
// InvalidHexCharError.
-func Decode(dst, src []byte) (int, os.Error) {
+func Decode(dst, src []byte) (int, error) {
if len(src)%2 == 1 {
return 0, OddLengthInputError{}
}
}
// DecodeString returns the bytes represented by the hexadecimal string s.
-func DecodeString(s string) ([]byte, os.Error) {
+func DecodeString(s string) ([]byte, error) {
src := []byte(s)
dst := make([]byte, DecodedLen(len(src)))
_, err := Decode(dst, src)
return b
}
-func (h *dumper) Write(data []byte) (n int, err os.Error) {
+func (h *dumper) Write(data []byte) (n int, err error) {
// Output lines look like:
// 00000010 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=|
// ^ offset ^ extra space ^ ASCII of line.
return
}
-func (h *dumper) Close() (err os.Error) {
+func (h *dumper) Close() (err error) {
// See the comments in Write() for the details of this format.
if h.used == 0 {
return
"bytes"
"encoding/base64"
"io"
- "os"
)
// A Block represents a PEM encoded structure.
out io.Writer
}
-func (l *lineBreaker) Write(b []byte) (n int, err os.Error) {
+func (l *lineBreaker) Write(b []byte) (n int, err error) {
if l.used+len(b) < pemLineLength {
copy(l.line[l.used:], b)
l.used += len(b)
return l.Write(b[excess:])
}
-func (l *lineBreaker) Close() (err os.Error) {
+func (l *lineBreaker) Close() (err error) {
if l.used > 0 {
_, err = l.out.Write(l.line[0:l.used])
if err != nil {
return
}
-func Encode(out io.Writer, b *Block) (err os.Error) {
+func Encode(out io.Writer, b *Block) (err error) {
_, err = out.Write(pemStart[1:])
if err != nil {
return
--- /dev/null
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package errors implements functions to manipulate errors.
+package errors
+
+// New returns an error that formats as the given text.
+func New(text string) error {
+ return &errorString{text}
+}
+
+// errorString is a trivial implementation of error.
+type errorString struct {
+ s string
+}
+
+func (e *errorString) Error() string {
+ return e.s
+}
--- /dev/null
+// Copyright 2011 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package errors_test
+
+import (
+ . "errors"
+ "testing"
+)
+
+func TestNewEqual(t *testing.T) {
+ // Different allocations should not be equal.
+ if New("abc") == New("abc") {
+ t.Errorf(`New("abc") == New("abc")`)
+ }
+ if New("abc") == New("xyz") {
+ t.Errorf(`New("abc") == New("xyz")`)
+ }
+
+ // Same allocation should be equal to itself (not crash).
+ err := New("jkl")
+ if err != err {
+ t.Errorf(`err != err`)
+ }
+}
+
+func TestErrorMethod(t *testing.T) {
+ err := New("abc")
+ if err.Error() != "abc" {
+ t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc")
+ }
+}
import (
"bytes"
+ "errors"
"io"
"os"
"strconv"
// Error records the name of a binary that failed to be be executed
// and the reason it failed.
type Error struct {
- Name string
- Error os.Error
+ Name string
+ Err error
}
-func (e *Error) String() string {
- return "exec: " + strconv.Quote(e.Name) + ": " + e.Error.String()
+func (e *Error) Error() string {
+ return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error()
}
// Cmd represents an external command being prepared or run.
// Process is the underlying process, once started.
Process *os.Process
- err os.Error // last error (from LookPath, stdin, stdout, stderr)
- finished bool // when Wait was called
+ err error // last error (from LookPath, stdin, stdout, stderr)
+ finished bool // when Wait was called
childFiles []*os.File
closeAfterStart []io.Closer
closeAfterWait []io.Closer
- goroutine []func() os.Error
- errch chan os.Error // one send per goroutine
+ goroutine []func() error
+ errch chan error // one send per goroutine
}
// Command returns the Cmd struct to execute the named program with
return []string{c.Path}
}
-func (c *Cmd) stdin() (f *os.File, err os.Error) {
+func (c *Cmd) stdin() (f *os.File, err error) {
if c.Stdin == nil {
f, err = os.Open(os.DevNull)
c.closeAfterStart = append(c.closeAfterStart, f)
c.closeAfterStart = append(c.closeAfterStart, pr)
c.closeAfterWait = append(c.closeAfterWait, pw)
- c.goroutine = append(c.goroutine, func() os.Error {
+ c.goroutine = append(c.goroutine, func() error {
_, err := io.Copy(pw, c.Stdin)
if err1 := pw.Close(); err == nil {
err = err1
return pr, nil
}
-func (c *Cmd) stdout() (f *os.File, err os.Error) {
+func (c *Cmd) stdout() (f *os.File, err error) {
return c.writerDescriptor(c.Stdout)
}
-func (c *Cmd) stderr() (f *os.File, err os.Error) {
+func (c *Cmd) stderr() (f *os.File, err error) {
if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) {
return c.childFiles[1], nil
}
return c.writerDescriptor(c.Stderr)
}
-func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err os.Error) {
+func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err error) {
if w == nil {
f, err = os.OpenFile(os.DevNull, os.O_WRONLY, 0)
c.closeAfterStart = append(c.closeAfterStart, f)
c.closeAfterStart = append(c.closeAfterStart, pw)
c.closeAfterWait = append(c.closeAfterWait, pr)
- c.goroutine = append(c.goroutine, func() os.Error {
+ c.goroutine = append(c.goroutine, func() error {
_, err := io.Copy(w, pr)
return err
})
// status.
//
// If the command fails to run or doesn't complete successfully, the
-// error is of type *os.Waitmsg. Other error types may be
+// error is of type *ExitError. Other error types may be
// returned for I/O problems.
-func (c *Cmd) Run() os.Error {
+func (c *Cmd) Run() error {
if err := c.Start(); err != nil {
return err
}
}
// Start starts the specified command but does not wait for it to complete.
-func (c *Cmd) Start() os.Error {
+func (c *Cmd) Start() error {
if c.err != nil {
return c.err
}
if c.Process != nil {
- return os.NewError("exec: already started")
+ return errors.New("exec: already started")
}
- type F func(*Cmd) (*os.File, os.Error)
+ type F func(*Cmd) (*os.File, error)
for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
fd, err := setupFd(c)
if err != nil {
}
c.childFiles = append(c.childFiles, c.ExtraFiles...)
- var err os.Error
+ var err error
c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{
Dir: c.Dir,
Files: c.childFiles,
fd.Close()
}
- c.errch = make(chan os.Error, len(c.goroutine))
+ c.errch = make(chan error, len(c.goroutine))
for _, fn := range c.goroutine {
- go func(fn func() os.Error) {
+ go func(fn func() error) {
c.errch <- fn()
}(fn)
}
return nil
}
+// An ExitError reports an unsuccessful exit by a command.
+type ExitError struct {
+ *os.Waitmsg
+}
+
+func (e *ExitError) Error() string {
+ return e.Waitmsg.String()
+}
+
// Wait waits for the command to exit.
// It must have been started by Start.
//
// status.
//
// If the command fails to run or doesn't complete successfully, the
-// error is of type *os.Waitmsg. Other error types may be
+// error is of type *ExitError. Other error types may be
// returned for I/O problems.
-func (c *Cmd) Wait() os.Error {
+func (c *Cmd) Wait() error {
if c.Process == nil {
- return os.NewError("exec: not started")
+ return errors.New("exec: not started")
}
if c.finished {
- return os.NewError("exec: Wait was already called")
+ return errors.New("exec: Wait was already called")
}
c.finished = true
msg, err := c.Process.Wait(0)
- var copyError os.Error
+ var copyError error
for _ = range c.goroutine {
if err := <-c.errch; err != nil && copyError == nil {
copyError = err
if err != nil {
return err
} else if !msg.Exited() || msg.ExitStatus() != 0 {
- return msg
+ return &ExitError{msg}
}
return copyError
}
// Output runs the command and returns its standard output.
-func (c *Cmd) Output() ([]byte, os.Error) {
+func (c *Cmd) Output() ([]byte, error) {
if c.Stdout != nil {
- return nil, os.NewError("exec: Stdout already set")
+ return nil, errors.New("exec: Stdout already set")
}
var b bytes.Buffer
c.Stdout = &b
// CombinedOutput runs the command and returns its combined standard
// output and standard error.
-func (c *Cmd) CombinedOutput() ([]byte, os.Error) {
+func (c *Cmd) CombinedOutput() ([]byte, error) {
if c.Stdout != nil {
- return nil, os.NewError("exec: Stdout already set")
+ return nil, errors.New("exec: Stdout already set")
}
if c.Stderr != nil {
- return nil, os.NewError("exec: Stderr already set")
+ return nil, errors.New("exec: Stderr already set")
}
var b bytes.Buffer
c.Stdout = &b
// StdinPipe returns a pipe that will be connected to the command's
// standard input when the command starts.
-func (c *Cmd) StdinPipe() (io.WriteCloser, os.Error) {
+func (c *Cmd) StdinPipe() (io.WriteCloser, error) {
if c.Stdin != nil {
- return nil, os.NewError("exec: Stdin already set")
+ return nil, errors.New("exec: Stdin already set")
}
if c.Process != nil {
- return nil, os.NewError("exec: StdinPipe after process started")
+ return nil, errors.New("exec: StdinPipe after process started")
}
pr, pw, err := os.Pipe()
if err != nil {
// StdoutPipe returns a pipe that will be connected to the command's
// standard output when the command starts.
// The pipe will be closed automatically after Wait sees the command exit.
-func (c *Cmd) StdoutPipe() (io.ReadCloser, os.Error) {
+func (c *Cmd) StdoutPipe() (io.ReadCloser, error) {
if c.Stdout != nil {
- return nil, os.NewError("exec: Stdout already set")
+ return nil, errors.New("exec: Stdout already set")
}
if c.Process != nil {
- return nil, os.NewError("exec: StdoutPipe after process started")
+ return nil, errors.New("exec: StdoutPipe after process started")
}
pr, pw, err := os.Pipe()
if err != nil {
// StderrPipe returns a pipe that will be connected to the command's
// standard error when the command starts.
// The pipe will be closed automatically after Wait sees the command exit.
-func (c *Cmd) StderrPipe() (io.ReadCloser, os.Error) {
+func (c *Cmd) StderrPipe() (io.ReadCloser, error) {
if c.Stderr != nil {
- return nil, os.NewError("exec: Stderr already set")
+ return nil, errors.New("exec: Stderr already set")
}
if c.Process != nil {
- return nil, os.NewError("exec: StderrPipe after process started")
+ return nil, errors.New("exec: StderrPipe after process started")
}
pr, pw, err := os.Pipe()
if err != nil {
func TestCatGoodAndBadFile(t *testing.T) {
// Testing combined output and error values.
bs, err := helperCommand("cat", "/bogus/file.foo", "exec_test.go").CombinedOutput()
- if _, ok := err.(*os.Waitmsg); !ok {
- t.Errorf("expected Waitmsg from cat combined; got %T: %v", err, err)
+ if _, ok := err.(*ExitError); !ok {
+ t.Errorf("expected *ExitError from cat combined; got %T: %v", err, err)
}
s := string(bs)
sp := strings.SplitN(s, "\n", 2)
func TestExitStatus(t *testing.T) {
// Test that exit values are returned correctly
err := helperCommand("exit", "42").Run()
- if werr, ok := err.(*os.Waitmsg); ok {
- if s, e := werr.String(), "exit status 42"; s != e {
+ if werr, ok := err.(*ExitError); ok {
+ if s, e := werr.Error(), "exit status 42"; s != e {
t.Errorf("from exit 42 got exit %q, want %q", s, e)
}
} else {
- t.Fatalf("expected Waitmsg from exit 42; got %T: %v", err, err)
+ t.Fatalf("expected *ExitError from exit 42; got %T: %v", err, err)
}
}
func TestPipes(t *testing.T) {
- check := func(what string, err os.Error) {
+ check := func(what string, err error) {
if err != nil {
t.Fatalf("%s: %v", what, err)
}
bufr := bufio.NewReader(os.Stdin)
for {
line, _, err := bufr.ReadLine()
- if err == os.EOF {
+ if err == io.EOF {
break
} else if err != nil {
os.Exit(1)
package exec
import (
+ "errors"
"os"
"strings"
)
// ErrNotFound is the error resulting if a path search failed to find an executable file.
-var ErrNotFound = os.NewError("executable file not found in $path")
+var ErrNotFound = errors.New("executable file not found in $path")
-func findExecutable(file string) os.Error {
+func findExecutable(file string) error {
d, err := os.Stat(file)
if err != nil {
return err
// in the directories named by the path environment variable.
// If file begins with "/", "#", "./", or "../", it is tried
// directly and the path is not consulted.
-func LookPath(file string) (string, os.Error) {
+func LookPath(file string) (string, error) {
// skip the path lookup for these prefixes
skip := []string{"/", "#", "./", "../"}
package exec
import (
+ "errors"
"os"
"strings"
)
// ErrNotFound is the error resulting if a path search failed to find an executable file.
-var ErrNotFound = os.NewError("executable file not found in $PATH")
+var ErrNotFound = errors.New("executable file not found in $PATH")
-func findExecutable(file string) os.Error {
+func findExecutable(file string) error {
d, err := os.Stat(file)
if err != nil {
return err
// LookPath searches for an executable binary named file
// in the directories named by the PATH environment variable.
// If file contains a slash, it is tried directly and the PATH is not consulted.
-func LookPath(file string) (string, os.Error) {
+func LookPath(file string) (string, error) {
// NOTE(rsc): I wish we could use the Plan 9 behavior here
// (only bypass the path if file begins with / or ./ or ../)
// but that would not match all the Unix shells.
package exec
import (
+ "errors"
"os"
"strings"
)
// ErrNotFound is the error resulting if a path search failed to find an executable file.
-var ErrNotFound = os.NewError("executable file not found in %PATH%")
+var ErrNotFound = errors.New("executable file not found in %PATH%")
-func chkStat(file string) os.Error {
+func chkStat(file string) error {
d, err := os.Stat(file)
if err != nil {
return err
return os.EPERM
}
-func findExecutable(file string, exts []string) (string, os.Error) {
+func findExecutable(file string, exts []string) (string, error) {
if len(exts) == 0 {
return file, chkStat(file)
}
return ``, os.ENOENT
}
-func LookPath(file string) (f string, err os.Error) {
+func LookPath(file string) (f string, err error) {
x := os.Getenv(`PATHEXT`)
if x == `` {
x = `.COM;.EXE;.BAT;.CMD`
package ebnf
import (
+ "errors"
"fmt"
- "os"
"scanner"
"unicode"
"utf8"
// ----------------------------------------------------------------------------
// Error handling
-type errorList []os.Error
+type errorList []error
-func (list errorList) Error() os.Error {
+func (list errorList) Err() error {
if len(list) == 0 {
return nil
}
return list
}
-func (list errorList) String() string {
+func (list errorList) Error() string {
switch len(list) {
case 0:
return "no errors"
case 1:
- return list[0].String()
+ return list[0].Error()
}
return fmt.Sprintf("%s (and %d more errors)", list[0], len(list)-1)
}
-func newError(pos scanner.Position, msg string) os.Error {
- return os.NewError(fmt.Sprintf("%s: %s", pos, msg))
+func newError(pos scanner.Position, msg string) error {
+ return errors.New(fmt.Sprintf("%s: %s", pos, msg))
}
// ----------------------------------------------------------------------------
//
// Position information is interpreted relative to the file set fset.
//
-func Verify(grammar Grammar, start string) os.Error {
+func Verify(grammar Grammar, start string) error {
var v verifier
v.verify(grammar, start)
- return v.errors.Error()
+ return v.errors.Err()
}
import (
"io"
- "os"
"scanner"
"strconv"
)
// more than once; the filename is used only for error
// positions.
//
-func Parse(filename string, src io.Reader) (Grammar, os.Error) {
+func Parse(filename string, src io.Reader) (Grammar, error) {
var p parser
grammar := p.parse(filename, src)
- return grammar, p.errors.Error()
+ return grammar, p.errors.Err()
}
close = []byte(`</pre>`)
)
-func report(err os.Error) {
+func report(err error) {
scanner.PrintError(os.Stderr, err)
os.Exit(1)
}
var (
filename string
src []byte
- err os.Error
+ err error
)
switch flag.NArg() {
case 0:
package main
import (
+ "errors"
"exp/types"
"flag"
"fmt"
os.Exit(2)
}
-func report(err os.Error) {
+func report(err error) {
scanner.PrintError(os.Stderr, err)
exitCode = 2
}
}
if file := parse(fset, filename, src); file != nil {
if files[filename] != nil {
- report(os.NewError(fmt.Sprintf("%q: duplicate file", filename)))
+ report(errors.New(fmt.Sprintf("%q: duplicate file", filename)))
continue
}
files[filename] = file
import (
"image"
"image/draw"
- "os"
)
// A Window represents a single graphics window.
// mouse movements and window resizes.
EventChan() <-chan interface{}
// Close closes the window.
- Close() os.Error
+ Close() error
}
// A KeyEvent is sent for a key press or release.
// An ErrEvent is sent when an error occurs.
type ErrEvent struct {
- Err os.Error
+ Err error
}
import (
"bufio"
+ "errors"
"io"
"os"
)
// readU16BE reads a big-endian uint16 from r, using b as a scratch buffer.
-func readU16BE(r io.Reader, b []byte) (uint16, os.Error) {
+func readU16BE(r io.Reader, b []byte) (uint16, error) {
_, err := io.ReadFull(r, b[0:2])
if err != nil {
return 0, err
}
// readStr reads a length-prefixed string from r, using b as a scratch buffer.
-func readStr(r io.Reader, b []byte) (string, os.Error) {
+func readStr(r io.Reader, b []byte) (string, error) {
n, err := readU16BE(r, b)
if err != nil {
return "", err
}
if int(n) > len(b) {
- return "", os.NewError("Xauthority entry too long for buffer")
+ return "", errors.New("Xauthority entry too long for buffer")
}
_, err = io.ReadFull(r, b[0:n])
if err != nil {
// readAuth reads the X authority file and returns the name/data pair for the display.
// displayStr is the "12" out of a $DISPLAY like ":12.0".
-func readAuth(displayStr string) (name, data string, err os.Error) {
+func readAuth(displayStr string) (name, data string, err error) {
// b is a scratch buffer to use and should be at least 256 bytes long
// (i.e. it should be able to hold a hostname).
var b [256]byte
if fn == "" {
home := os.Getenv("HOME")
if home == "" {
- err = os.NewError("Xauthority not found: $XAUTHORITY, $HOME not set")
+ err = errors.New("Xauthority not found: $XAUTHORITY, $HOME not set")
return
}
fn = home + "/.Xauthority"
import (
"bufio"
+ "errors"
"exp/gui"
"image"
"image/draw"
for y := b.Min.Y; y < b.Max.Y; y++ {
setU32LE(c.flushBuf0[16:20], uint32(y<<16))
if _, err := c.w.Write(c.flushBuf0[:24]); err != nil {
- if err != os.EOF {
+ if err != io.EOF {
log.Println("x11:", err)
}
return
}
x += nx
if _, err := c.w.Write(c.flushBuf1[:nx]); err != nil {
- if err != os.EOF {
+ if err != io.EOF {
log.Println("x11:", err)
}
return
}
}
if err := c.w.Flush(); err != nil {
- if err != os.EOF {
+ if err != io.EOF {
log.Println("x11:", err)
}
return
}
}
-func (c *conn) Close() os.Error {
+func (c *conn) Close() error {
// Shut down the writeSocket goroutine. This will close the socket to the
// X11 server, which will cause c.eventc to close.
close(c.flush)
for {
// X events are always 32 bytes long.
if _, err := io.ReadFull(c.r, c.buf[:32]); err != nil {
- if err != os.EOF {
+ if err != io.EOF {
c.eventc <- gui.ErrEvent{err}
}
return
if cookie != 1 {
// We issued only one request (GetKeyboardMapping) with a cookie of 1,
// so we shouldn't get any other reply from the X server.
- c.eventc <- gui.ErrEvent{os.NewError("x11: unexpected cookie")}
+ c.eventc <- gui.ErrEvent{errors.New("x11: unexpected cookie")}
return
}
keysymsPerKeycode = int(c.buf[1])
for j := range m {
u, err := readU32LE(c.r, c.buf[:4])
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
c.eventc <- gui.ErrEvent{err}
}
return
// connect("/tmp/launch-123/:0") // calls net.Dial("unix", "", "/tmp/launch-123/:0"), displayStr="0"
// connect("hostname:2.1") // calls net.Dial("tcp", "", "hostname:6002"), displayStr="2"
// connect("tcp/hostname:1.0") // calls net.Dial("tcp", "", "hostname:6001"), displayStr="1"
-func connect(display string) (conn net.Conn, displayStr string, err os.Error) {
+func connect(display string) (conn net.Conn, displayStr string, err error) {
colonIdx := strings.LastIndex(display, ":")
if colonIdx < 0 {
- return nil, "", os.NewError("bad display: " + display)
+ return nil, "", errors.New("bad display: " + display)
}
// Parse the section before the colon.
var protocol, host, socket string
// Parse the section after the colon.
after := display[colonIdx+1:]
if after == "" {
- return nil, "", os.NewError("bad display: " + display)
+ return nil, "", errors.New("bad display: " + display)
}
if i := strings.LastIndex(after, "."); i < 0 {
displayStr = after
}
displayInt, err := strconv.Atoi(displayStr)
if err != nil || displayInt < 0 {
- return nil, "", os.NewError("bad display: " + display)
+ return nil, "", errors.New("bad display: " + display)
}
// Make the connection.
if socket != "" {
conn, err = net.Dial("unix", "/tmp/.X11-unix/X"+displayStr)
}
if err != nil {
- return nil, "", os.NewError("cannot connect to " + display + ": " + err.String())
+ return nil, "", errors.New("cannot connect to " + display + ": " + err.Error())
}
return
}
// authenticate authenticates ourselves with the X server.
// displayStr is the "12" out of ":12.0".
-func authenticate(w *bufio.Writer, displayStr string) os.Error {
+func authenticate(w *bufio.Writer, displayStr string) error {
key, value, err := readAuth(displayStr)
if err != nil {
return err
}
// Assume that the authentication protocol is "MIT-MAGIC-COOKIE-1".
if len(key) != 18 || len(value) != 16 {
- return os.NewError("unsupported Xauth")
+ return errors.New("unsupported Xauth")
}
// 0x006c means little-endian. 0x000b, 0x0000 means X major version 11, minor version 0.
// 0x0012 and 0x0010 means the auth key and value have lengths 18 and 16.
}
// readU8 reads a uint8 from r, using b as a scratch buffer.
-func readU8(r io.Reader, b []byte) (uint8, os.Error) {
+func readU8(r io.Reader, b []byte) (uint8, error) {
_, err := io.ReadFull(r, b[:1])
if err != nil {
return 0, err
}
// readU16LE reads a little-endian uint16 from r, using b as a scratch buffer.
-func readU16LE(r io.Reader, b []byte) (uint16, os.Error) {
+func readU16LE(r io.Reader, b []byte) (uint16, error) {
_, err := io.ReadFull(r, b[:2])
if err != nil {
return 0, err
}
// readU32LE reads a little-endian uint32 from r, using b as a scratch buffer.
-func readU32LE(r io.Reader, b []byte) (uint32, os.Error) {
+func readU32LE(r io.Reader, b []byte) (uint32, error) {
_, err := io.ReadFull(r, b[:4])
if err != nil {
return 0, err
}
// checkPixmapFormats checks that we have an agreeable X pixmap Format.
-func checkPixmapFormats(r io.Reader, b []byte, n int) (agree bool, err os.Error) {
+func checkPixmapFormats(r io.Reader, b []byte, n int) (agree bool, err error) {
for i := 0; i < n; i++ {
_, err = io.ReadFull(r, b[:8])
if err != nil {
}
// checkDepths checks that we have an agreeable X Depth (i.e. one that has an agreeable X VisualType).
-func checkDepths(r io.Reader, b []byte, n int, visual uint32) (agree bool, err os.Error) {
+func checkDepths(r io.Reader, b []byte, n int, visual uint32) (agree bool, err error) {
for i := 0; i < n; i++ {
var depth, visualsLen uint16
depth, err = readU16LE(r, b)
}
// checkScreens checks that we have an agreeable X Screen.
-func checkScreens(r io.Reader, b []byte, n int) (root, visual uint32, err os.Error) {
+func checkScreens(r io.Reader, b []byte, n int) (root, visual uint32, err error) {
for i := 0; i < n; i++ {
var root0, visual0, x uint32
root0, err = readU32LE(r, b)
// handshake performs the protocol handshake with the X server, and ensures
// that the server provides a compatible Screen, Depth, etc.
-func (c *conn) handshake() os.Error {
+func (c *conn) handshake() error {
_, err := io.ReadFull(c.r, c.buf[:8])
if err != nil {
return err
}
// Byte 0 should be 1 (success), bytes 2:6 should be 0xb0000000 (major/minor version 11.0).
if c.buf[0] != 1 || c.buf[2] != 11 || c.buf[3] != 0 || c.buf[4] != 0 || c.buf[5] != 0 {
- return os.NewError("unsupported X version")
+ return errors.New("unsupported X version")
}
// Ignore the release number.
_, err = io.ReadFull(c.r, c.buf[:4])
return err
}
if resourceIdMask < 256 {
- return os.NewError("X resource ID mask is too small")
+ return errors.New("X resource ID mask is too small")
}
// Ignore the motion buffer size.
_, err = io.ReadFull(c.r, c.buf[:4])
return err
}
if maxReqLen != 0xffff {
- return os.NewError("unsupported X maximum request length")
+ return errors.New("unsupported X maximum request length")
}
// Read the roots length.
rootsLen, err := readU8(c.r, c.buf[:1])
// imageByteOrder(1), bitmapFormatBitOrder(1), bitmapFormatScanlineUnit(1) bitmapFormatScanlinePad(1),
// minKeycode(1), maxKeycode(1), padding(4), vendor (vendorLen).
if 10+int(vendorLen) > cap(c.buf) {
- return os.NewError("unsupported X vendor")
+ return errors.New("unsupported X vendor")
}
_, err = io.ReadFull(c.r, c.buf[:10+int(vendorLen)])
if err != nil {
return err
}
if !agree {
- return os.NewError("unsupported X pixmap formats")
+ return errors.New("unsupported X pixmap formats")
}
// Check that we have an agreeable screen.
root, visual, err := checkScreens(c.r, c.buf[:24], int(rootsLen))
return err
}
if root == 0 || visual == 0 {
- return os.NewError("unsupported X screen")
+ return errors.New("unsupported X screen")
}
c.gc = resID(resourceIdBase)
c.window = resID(resourceIdBase + 1)
}
// NewWindow calls NewWindowDisplay with $DISPLAY.
-func NewWindow() (gui.Window, os.Error) {
+func NewWindow() (gui.Window, error) {
display := os.Getenv("DISPLAY")
if len(display) == 0 {
- return nil, os.NewError("$DISPLAY not set")
+ return nil, errors.New("$DISPLAY not set")
}
return NewWindowDisplay(display)
}
// NewWindowDisplay returns a new gui.Window, backed by a newly created and
// mapped X11 window. The X server to connect to is specified by the display
// string, such as ":1".
-func NewWindowDisplay(display string) (gui.Window, os.Error) {
+func NewWindowDisplay(display string) (gui.Window, error) {
socket, displayStr, err := connect(display)
if err != nil {
return nil, err
package inotify
import (
+ "errors"
"fmt"
"os"
"strings"
fd int // File descriptor (as returned by the inotify_init() syscall)
watches map[string]*watch // Map of inotify watches (key: path)
paths map[int]string // Map of watched paths (key: watch descriptor)
- Error chan os.Error // Errors are sent on this channel
+ Error chan error // Errors are sent on this channel
Event chan *Event // Events are returned on this channel
done chan bool // Channel for sending a "quit message" to the reader goroutine
isClosed bool // Set to true when Close() is first called
}
// NewWatcher creates and returns a new inotify instance using inotify_init(2)
-func NewWatcher() (*Watcher, os.Error) {
+func NewWatcher() (*Watcher, error) {
fd, errno := syscall.InotifyInit()
if fd == -1 {
return nil, os.NewSyscallError("inotify_init", errno)
watches: make(map[string]*watch),
paths: make(map[int]string),
Event: make(chan *Event),
- Error: make(chan os.Error),
+ Error: make(chan error),
done: make(chan bool, 1),
}
// Close closes an inotify watcher instance
// It sends a message to the reader goroutine to quit and removes all watches
// associated with the inotify instance
-func (w *Watcher) Close() os.Error {
+func (w *Watcher) Close() error {
if w.isClosed {
return nil
}
// AddWatch adds path to the watched file set.
// The flags are interpreted as described in inotify_add_watch(2).
-func (w *Watcher) AddWatch(path string, flags uint32) os.Error {
+func (w *Watcher) AddWatch(path string, flags uint32) error {
if w.isClosed {
- return os.NewError("inotify instance already closed")
+ return errors.New("inotify instance already closed")
}
watchEntry, found := w.watches[path]
}
// Watch adds path to the watched file set, watching all events.
-func (w *Watcher) Watch(path string) os.Error {
+func (w *Watcher) Watch(path string) error {
return w.AddWatch(path, IN_ALL_EVENTS)
}
// RemoveWatch removes path from the watched file set.
-func (w *Watcher) RemoveWatch(path string) os.Error {
+func (w *Watcher) RemoveWatch(path string) error {
watch, ok := w.watches[path]
if !ok {
- return os.NewError(fmt.Sprintf("can't remove non-existent inotify watch for: %s", path))
+ return errors.New(fmt.Sprintf("can't remove non-existent inotify watch for: %s", path))
}
success, errno := syscall.InotifyRmWatch(w.fd, watch.wd)
if success == -1 {
continue
}
if n < syscall.SizeofInotifyEvent {
- w.Error <- os.NewError("inotify: short read in readEvents()")
+ w.Error <- errors.New("inotify: short read in readEvents()")
continue
}
return
}
-func parseDecomposition(s string, skipfirst bool) (a []rune, e os.Error) {
+func parseDecomposition(s string, skipfirst bool) (a []rune, e error) {
decomp := strings.Split(s, " ")
if len(decomp) > 0 && skipfirst {
decomp = decomp[1:]
for {
line, err := input.ReadString('\n')
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
break
}
logger.Fatal(err)
for {
line, err := input.ReadString('\n')
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
break
}
logger.Fatal(err)
for {
line, err := input.ReadString('\n')
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
break
}
logger.Fatal(err)
"flag"
"fmt"
"http"
+ "io"
"log"
"os"
"path"
for {
line, err := input.ReadString('\n')
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
break
}
logger.Fatal(err)
package norm
-import (
- "io"
- "os"
-)
+import "io"
type normWriter struct {
rb reorderBuffer
// Write implements the standard write interface. If the last characters are
// not at a normalization boundary, the bytes will be buffered for the next
// write. The remaining bytes will be written on close.
-func (w *normWriter) Write(data []byte) (n int, err os.Error) {
+func (w *normWriter) Write(data []byte) (n int, err error) {
// Process data in pieces to keep w.buf size bounded.
const chunk = 4000
}
// Close forces data that remains in the buffer to be written.
-func (w *normWriter) Close() os.Error {
+func (w *normWriter) Close() error {
if len(w.buf) > 0 {
_, err := w.w.Write(w.buf)
if err != nil {
outbuf []byte
bufStart int
lastBoundary int
- err os.Error
+ err error
}
// Read implements the standard read interface.
-func (r *normReader) Read(p []byte) (int, os.Error) {
+func (r *normReader) Read(p []byte) (int, error) {
for {
if r.lastBoundary-r.bufStart > 0 {
n := copy(p, r.outbuf[r.bufStart:r.lastBoundary])
if n > 0 {
r.outbuf = doAppend(&r.rb, r.outbuf)
}
- if err == os.EOF {
+ if err == io.EOF {
r.lastBoundary = len(r.outbuf)
} else {
r.lastBoundary = lastBoundary(&r.rb.f, r.outbuf)
import (
"bytes"
"fmt"
- "os"
"strings"
"testing"
)
r := f.Reader(bytes.NewBuffer(out))
buf := make([]byte, size)
result := []byte{}
- for n, err := 0, os.Error(nil); err == nil; {
+ for n, err := 0, error(nil); err == nil; {
n, err = r.Read(buf)
result = append(result, buf[:n]...)
}
"encoding/binary"
"http"
"io"
- "os"
"strings"
)
-func (frame *SynStreamFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *SynStreamFrame) read(h ControlFrameHeader, f *Framer) error {
return f.readSynStreamFrame(h, frame)
}
-func (frame *SynReplyFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *SynReplyFrame) read(h ControlFrameHeader, f *Framer) error {
return f.readSynReplyFrame(h, frame)
}
-func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *RstStreamFrame) read(h ControlFrameHeader, f *Framer) error {
frame.CFHeader = h
if err := binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil {
return err
return nil
}
-func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *SettingsFrame) read(h ControlFrameHeader, f *Framer) error {
frame.CFHeader = h
var numSettings uint32
if err := binary.Read(f.r, binary.BigEndian, &numSettings); err != nil {
return nil
}
-func (frame *NoopFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *NoopFrame) read(h ControlFrameHeader, f *Framer) error {
frame.CFHeader = h
return nil
}
-func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *PingFrame) read(h ControlFrameHeader, f *Framer) error {
frame.CFHeader = h
if err := binary.Read(f.r, binary.BigEndian, &frame.Id); err != nil {
return err
return nil
}
-func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *GoAwayFrame) read(h ControlFrameHeader, f *Framer) error {
frame.CFHeader = h
if err := binary.Read(f.r, binary.BigEndian, &frame.LastGoodStreamId); err != nil {
return err
return nil
}
-func (frame *HeadersFrame) read(h ControlFrameHeader, f *Framer) os.Error {
+func (frame *HeadersFrame) read(h ControlFrameHeader, f *Framer) error {
return f.readHeadersFrame(h, frame)
}
-func newControlFrame(frameType ControlFrameType) (controlFrame, os.Error) {
+func newControlFrame(frameType ControlFrameType) (controlFrame, error) {
ctor, ok := cframeCtor[frameType]
if !ok {
return nil, &Error{Err: InvalidControlFrame}
// TODO(willchan): Add TypeWindowUpdate
}
-func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) os.Error {
+func (f *Framer) uncorkHeaderDecompressor(payloadSize int64) error {
if f.headerDecompressor != nil {
f.headerReader.N = payloadSize
return nil
}
// ReadFrame reads SPDY encoded data and returns a decompressed Frame.
-func (f *Framer) ReadFrame() (Frame, os.Error) {
+func (f *Framer) ReadFrame() (Frame, error) {
var firstWord uint32
if err := binary.Read(f.r, binary.BigEndian, &firstWord); err != nil {
return nil, err
return f.parseDataFrame(firstWord & 0x7fffffff)
}
-func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) (Frame, os.Error) {
+func (f *Framer) parseControlFrame(version uint16, frameType ControlFrameType) (Frame, error) {
var length uint32
if err := binary.Read(f.r, binary.BigEndian, &length); err != nil {
return nil, err
return cframe, nil
}
-func parseHeaderValueBlock(r io.Reader, streamId uint32) (http.Header, os.Error) {
+func parseHeaderValueBlock(r io.Reader, streamId uint32) (http.Header, error) {
var numHeaders uint16
if err := binary.Read(r, binary.BigEndian, &numHeaders); err != nil {
return nil, err
}
- var e os.Error
+ var e error
h := make(http.Header, int(numHeaders))
for i := 0; i < int(numHeaders); i++ {
var length uint16
return h, nil
}
-func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) os.Error {
+func (f *Framer) readSynStreamFrame(h ControlFrameHeader, frame *SynStreamFrame) error {
frame.CFHeader = h
- var err os.Error
+ var err error
if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil {
return err
}
}
frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId)
- if !f.headerCompressionDisabled && ((err == os.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) {
+ if !f.headerCompressionDisabled && ((err == io.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) {
err = &Error{WrongCompressedPayloadSize, 0}
}
if err != nil {
return nil
}
-func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) os.Error {
+func (f *Framer) readSynReplyFrame(h ControlFrameHeader, frame *SynReplyFrame) error {
frame.CFHeader = h
- var err os.Error
+ var err error
if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil {
return err
}
reader = f.headerDecompressor
}
frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId)
- if !f.headerCompressionDisabled && ((err == os.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) {
+ if !f.headerCompressionDisabled && ((err == io.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) {
err = &Error{WrongCompressedPayloadSize, 0}
}
if err != nil {
return nil
}
-func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) os.Error {
+func (f *Framer) readHeadersFrame(h ControlFrameHeader, frame *HeadersFrame) error {
frame.CFHeader = h
- var err os.Error
+ var err error
if err = binary.Read(f.r, binary.BigEndian, &frame.StreamId); err != nil {
return err
}
reader = f.headerDecompressor
}
frame.Headers, err = parseHeaderValueBlock(reader, frame.StreamId)
- if !f.headerCompressionDisabled && ((err == os.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) {
+ if !f.headerCompressionDisabled && ((err == io.EOF && f.headerReader.N == 0) || f.headerReader.N != 0) {
err = &Error{WrongCompressedPayloadSize, 0}
}
if err != nil {
return nil
}
-func (f *Framer) parseDataFrame(streamId uint32) (*DataFrame, os.Error) {
+func (f *Framer) parseDataFrame(streamId uint32) (*DataFrame, error) {
var length uint32
if err := binary.Read(f.r, binary.BigEndian, &length); err != nil {
return nil, err
"compress/zlib"
"http"
"io"
- "os"
)
// Data Frame Format
// Frame is a single SPDY frame in its unpacked in-memory representation. Use
// Framer to read and write it.
type Frame interface {
- write(f *Framer) os.Error
+ write(f *Framer) error
}
// ControlFrameHeader contains all the fields in a control frame header,
type controlFrame interface {
Frame
- read(h ControlFrameHeader, f *Framer) os.Error
+ read(h ControlFrameHeader, f *Framer) error
}
// SynStreamFrame is the unpacked, in-memory representation of a SYN_STREAM
StreamId uint32
}
-func (e *Error) String() string {
+func (e *Error) Error() string {
return string(e.Err)
}
// a io.Writer and io.Reader. Note that Framer will read and write individual fields
// from/to the Reader and Writer, so the caller should pass in an appropriately
// buffered implementation to optimize performance.
-func NewFramer(w io.Writer, r io.Reader) (*Framer, os.Error) {
+func NewFramer(w io.Writer, r io.Reader) (*Framer, error) {
compressBuf := new(bytes.Buffer)
compressor, err := zlib.NewWriterDict(compressBuf, zlib.BestCompression, []byte(HeaderDictionary))
if err != nil {
"encoding/binary"
"http"
"io"
- "os"
"strings"
)
-func (frame *SynStreamFrame) write(f *Framer) os.Error {
+func (frame *SynStreamFrame) write(f *Framer) error {
return f.writeSynStreamFrame(frame)
}
-func (frame *SynReplyFrame) write(f *Framer) os.Error {
+func (frame *SynReplyFrame) write(f *Framer) error {
return f.writeSynReplyFrame(frame)
}
-func (frame *RstStreamFrame) write(f *Framer) (err os.Error) {
+func (frame *RstStreamFrame) write(f *Framer) (err error) {
frame.CFHeader.version = Version
frame.CFHeader.frameType = TypeRstStream
frame.CFHeader.length = 8
return
}
-func (frame *SettingsFrame) write(f *Framer) (err os.Error) {
+func (frame *SettingsFrame) write(f *Framer) (err error) {
frame.CFHeader.version = Version
frame.CFHeader.frameType = TypeSettings
frame.CFHeader.length = uint32(len(frame.FlagIdValues)*8 + 4)
return
}
-func (frame *NoopFrame) write(f *Framer) os.Error {
+func (frame *NoopFrame) write(f *Framer) error {
frame.CFHeader.version = Version
frame.CFHeader.frameType = TypeNoop
return writeControlFrameHeader(f.w, frame.CFHeader)
}
-func (frame *PingFrame) write(f *Framer) (err os.Error) {
+func (frame *PingFrame) write(f *Framer) (err error) {
frame.CFHeader.version = Version
frame.CFHeader.frameType = TypePing
frame.CFHeader.length = 4
return
}
-func (frame *GoAwayFrame) write(f *Framer) (err os.Error) {
+func (frame *GoAwayFrame) write(f *Framer) (err error) {
frame.CFHeader.version = Version
frame.CFHeader.frameType = TypeGoAway
frame.CFHeader.length = 4
return nil
}
-func (frame *HeadersFrame) write(f *Framer) os.Error {
+func (frame *HeadersFrame) write(f *Framer) error {
return f.writeHeadersFrame(frame)
}
-func (frame *DataFrame) write(f *Framer) os.Error {
+func (frame *DataFrame) write(f *Framer) error {
return f.writeDataFrame(frame)
}
// WriteFrame writes a frame.
-func (f *Framer) WriteFrame(frame Frame) os.Error {
+func (f *Framer) WriteFrame(frame Frame) error {
return frame.write(f)
}
-func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) os.Error {
+func writeControlFrameHeader(w io.Writer, h ControlFrameHeader) error {
if err := binary.Write(w, binary.BigEndian, 0x8000|h.version); err != nil {
return err
}
return nil
}
-func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err os.Error) {
+func writeHeaderValueBlock(w io.Writer, h http.Header) (n int, err error) {
n = 0
if err = binary.Write(w, binary.BigEndian, uint16(len(h))); err != nil {
return
return
}
-func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err os.Error) {
+func (f *Framer) writeSynStreamFrame(frame *SynStreamFrame) (err error) {
// Marshal the headers.
var writer io.Writer = f.headerBuf
if !f.headerCompressionDisabled {
return nil
}
-func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err os.Error) {
+func (f *Framer) writeSynReplyFrame(frame *SynReplyFrame) (err error) {
// Marshal the headers.
var writer io.Writer = f.headerBuf
if !f.headerCompressionDisabled {
return
}
-func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err os.Error) {
+func (f *Framer) writeHeadersFrame(frame *HeadersFrame) (err error) {
// Marshal the headers.
var writer io.Writer = f.headerBuf
if !f.headerCompressionDisabled {
return
}
-func (f *Framer) writeDataFrame(frame *DataFrame) (err os.Error) {
+func (f *Framer) writeDataFrame(frame *DataFrame) (err error) {
// Validate DataFrame
if frame.StreamId&0x80000000 != 0 || len(frame.Data) >= 0x0f000000 {
return &Error{InvalidDataFrame, frame.StreamId}
package sql
import (
+ "errors"
"fmt"
- "os"
"reflect"
"strconv"
)
// convertAssign copies to dest the value in src, converting it if possible.
// An error is returned if the copy would result in loss of information.
// dest should be a pointer type.
-func convertAssign(dest, src interface{}) os.Error {
+func convertAssign(dest, src interface{}) error {
// Common cases, without reflect. Fall through.
switch s := src.(type) {
case string:
dpv := reflect.ValueOf(dest)
if dpv.Kind() != reflect.Ptr {
- return os.NewError("destination not a pointer")
+ return errors.New("destination not a pointer")
}
dv := reflect.Indirect(dpv)
err := convertAssign(ct.d, ct.s)
errstr := ""
if err != nil {
- errstr = err.String()
+ errstr = err.Error()
}
errf := func(format string, args ...interface{}) {
base := fmt.Sprintf("convertAssign #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d)
//
package driver
-import (
- "os"
-)
+import "errors"
// Driver is the interface that must be implemented by a database
// driver.
//
// The returned connection is only used by one goroutine at a
// time.
- Open(name string) (Conn, os.Error)
+ Open(name string) (Conn, error)
}
// Execer is an optional interface that may be implemented by a Driver
//
// All arguments are of a subset type as defined in the package docs.
type Execer interface {
- Exec(query string, args []interface{}) (Result, os.Error)
+ Exec(query string, args []interface{}) (Result, error)
}
// Conn is a connection to a database. It is not used concurrently
// Conn is assumed to be stateful.
type Conn interface {
// Prepare returns a prepared statement, bound to this connection.
- Prepare(query string) (Stmt, os.Error)
+ Prepare(query string) (Stmt, error)
// Close invalidates and potentially stops any current
// prepared statements and transactions, marking this
// connection as no longer in use. The driver may cache or
// close its underlying connection to its database.
- Close() os.Error
+ Close() error
// Begin starts and returns a new transaction.
- Begin() (Tx, os.Error)
+ Begin() (Tx, error)
}
// Result is the result of a query execution.
// LastInsertId returns the database's auto-generated ID
// after, for example, an INSERT into a table with primary
// key.
- LastInsertId() (int64, os.Error)
+ LastInsertId() (int64, error)
// RowsAffected returns the number of rows affected by the
// query.
- RowsAffected() (int64, os.Error)
+ RowsAffected() (int64, error)
}
// Stmt is a prepared statement. It is bound to a Conn and not
// used by multiple goroutines concurrently.
type Stmt interface {
// Close closes the statement.
- Close() os.Error
+ Close() error
// NumInput returns the number of placeholder parameters.
NumInput() int
// Exec executes a query that doesn't return rows, such
// as an INSERT or UPDATE. The args are all of a subset
// type as defined above.
- Exec(args []interface{}) (Result, os.Error)
+ Exec(args []interface{}) (Result, error)
// Exec executes a query that may return rows, such as a
// SELECT. The args of all of a subset type as defined above.
- Query(args []interface{}) (Rows, os.Error)
+ Query(args []interface{}) (Rows, error)
}
// ColumnConverter may be optionally implemented by Stmt if the
Columns() []string
// Close closes the rows iterator.
- Close() os.Error
+ Close() error
// Next is called to populate the next row of data into
// the provided slice. The provided slice will be the same
// The dest slice may be populated with only with values
// of subset types defined above, but excluding string.
// All string values must be converted to []byte.
- Next(dest []interface{}) os.Error
+ Next(dest []interface{}) error
}
// Tx is a transaction.
type Tx interface {
- Commit() os.Error
- Rollback() os.Error
+ Commit() error
+ Rollback() error
}
// RowsAffected implements Result for an INSERT or UPDATE operation
var _ Result = RowsAffected(0)
-func (RowsAffected) LastInsertId() (int64, os.Error) {
- return 0, os.NewError("no LastInsertId available")
+func (RowsAffected) LastInsertId() (int64, error) {
+ return 0, errors.New("no LastInsertId available")
}
-func (v RowsAffected) RowsAffected() (int64, os.Error) {
+func (v RowsAffected) RowsAffected() (int64, error) {
return int64(v), nil
}
var _ Result = ddlSuccess{}
-func (ddlSuccess) LastInsertId() (int64, os.Error) {
- return 0, os.NewError("no LastInsertId available after DDL statement")
+func (ddlSuccess) LastInsertId() (int64, error) {
+ return 0, errors.New("no LastInsertId available after DDL statement")
}
-func (ddlSuccess) RowsAffected() (int64, os.Error) {
- return 0, os.NewError("no RowsAffected available after DDL statement")
+func (ddlSuccess) RowsAffected() (int64, error) {
+ return 0, errors.New("no RowsAffected available after DDL statement")
}
import (
"fmt"
- "os"
"reflect"
"strconv"
)
// ValueConverter is the interface providing the ConvertValue method.
type ValueConverter interface {
// ConvertValue converts a value to a restricted subset type.
- ConvertValue(v interface{}) (interface{}, os.Error)
+ ConvertValue(v interface{}) (interface{}, error)
}
// Bool is a ValueConverter that converts input values to bools.
var _ ValueConverter = boolType{}
-func (boolType) ConvertValue(v interface{}) (interface{}, os.Error) {
+func (boolType) ConvertValue(v interface{}) (interface{}, error) {
return nil, fmt.Errorf("TODO(bradfitz): bool conversions")
}
var _ ValueConverter = int32Type{}
-func (int32Type) ConvertValue(v interface{}) (interface{}, os.Error) {
+func (int32Type) ConvertValue(v interface{}) (interface{}, error) {
rv := reflect.ValueOf(v)
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
type stringType struct{}
-func (stringType) ConvertValue(v interface{}) (interface{}, os.Error) {
+func (stringType) ConvertValue(v interface{}) (interface{}, error) {
switch v.(type) {
case string, []byte:
return v, nil
var _ ValueConverter = defaultConverter{}
-func (defaultConverter) ConvertValue(v interface{}) (interface{}, os.Error) {
+func (defaultConverter) ConvertValue(v interface{}) (interface{}, error) {
if IsParameterSubsetType(v) {
return v, nil
}
package sql
import (
+ "errors"
"fmt"
+ "io"
"log"
- "os"
"strconv"
"strings"
"sync"
// Supports dsn forms:
// <dbname>
// <dbname>;wipe
-func (d *fakeDriver) Open(dsn string) (driver.Conn, os.Error) {
+func (d *fakeDriver) Open(dsn string) (driver.Conn, error) {
d.mu.Lock()
defer d.mu.Unlock()
d.openCount++
}
parts := strings.Split(dsn, ";")
if len(parts) < 1 {
- return nil, os.NewError("fakedb: no database name")
+ return nil, errors.New("fakedb: no database name")
}
name := parts[0]
db, ok := d.dbs[name]
db.tables = nil
}
-func (db *fakeDB) createTable(name string, columnNames, columnTypes []string) os.Error {
+func (db *fakeDB) createTable(name string, columnNames, columnTypes []string) error {
db.mu.Lock()
defer db.mu.Unlock()
if db.tables == nil {
return "", false
}
-func (c *fakeConn) Begin() (driver.Tx, os.Error) {
+func (c *fakeConn) Begin() (driver.Tx, error) {
if c.currTx != nil {
- return nil, os.NewError("already in a transaction")
+ return nil, errors.New("already in a transaction")
}
c.currTx = &fakeTx{c: c}
return c.currTx, nil
}
-func (c *fakeConn) Close() os.Error {
+func (c *fakeConn) Close() error {
if c.currTx != nil {
- return os.NewError("can't close; in a Transaction")
+ return errors.New("can't close; in a Transaction")
}
if c.db == nil {
- return os.NewError("can't close; already closed")
+ return errors.New("can't close; already closed")
}
c.db = nil
return nil
}
-func errf(msg string, args ...interface{}) os.Error {
- return os.NewError("fakedb: " + fmt.Sprintf(msg, args...))
+func errf(msg string, args ...interface{}) error {
+ return errors.New("fakedb: " + fmt.Sprintf(msg, args...))
}
// parts are table|selectCol1,selectCol2|whereCol=?,whereCol2=?
// (note that where where columns must always contain ? marks,
// just a limitation for fakedb)
-func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (driver.Stmt, os.Error) {
+func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (driver.Stmt, error) {
if len(parts) != 3 {
return nil, errf("invalid SELECT syntax with %d parts; want 3", len(parts))
}
}
// parts are table|col=type,col2=type2
-func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (driver.Stmt, os.Error) {
+func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (driver.Stmt, error) {
if len(parts) != 2 {
return nil, errf("invalid CREATE syntax with %d parts; want 2", len(parts))
}
}
// parts are table|col=?,col2=val
-func (c *fakeConn) prepareInsert(stmt *fakeStmt, parts []string) (driver.Stmt, os.Error) {
+func (c *fakeConn) prepareInsert(stmt *fakeStmt, parts []string) (driver.Stmt, error) {
if len(parts) != 2 {
return nil, errf("invalid INSERT syntax with %d parts; want 2", len(parts))
}
return stmt, nil
}
-func (c *fakeConn) Prepare(query string) (driver.Stmt, os.Error) {
+func (c *fakeConn) Prepare(query string) (driver.Stmt, error) {
if c.db == nil {
panic("nil c.db; conn = " + fmt.Sprintf("%#v", c))
}
return s.placeholderConverter[idx]
}
-func (s *fakeStmt) Close() os.Error {
+func (s *fakeStmt) Close() error {
return nil
}
-func (s *fakeStmt) Exec(args []interface{}) (driver.Result, os.Error) {
+func (s *fakeStmt) Exec(args []interface{}) (driver.Result, error) {
db := s.c.db
switch s.cmd {
case "WIPE":
return nil, fmt.Errorf("unimplemented statement Exec command type of %q", s.cmd)
}
-func (s *fakeStmt) execInsert(args []interface{}) (driver.Result, os.Error) {
+func (s *fakeStmt) execInsert(args []interface{}) (driver.Result, error) {
db := s.c.db
if len(args) != s.placeholders {
panic("error in pkg db; should only get here if size is correct")
return driver.RowsAffected(1), nil
}
-func (s *fakeStmt) Query(args []interface{}) (driver.Rows, os.Error) {
+func (s *fakeStmt) Query(args []interface{}) (driver.Rows, error) {
db := s.c.db
if len(args) != s.placeholders {
panic("error in pkg db; should only get here if size is correct")
return s.placeholders
}
-func (tx *fakeTx) Commit() os.Error {
+func (tx *fakeTx) Commit() error {
tx.c.currTx = nil
return nil
}
-func (tx *fakeTx) Rollback() os.Error {
+func (tx *fakeTx) Rollback() error {
tx.c.currTx = nil
return nil
}
closed bool
}
-func (rc *rowsCursor) Close() os.Error {
+func (rc *rowsCursor) Close() error {
rc.closed = true
return nil
}
return rc.cols
}
-func (rc *rowsCursor) Next(dest []interface{}) os.Error {
+func (rc *rowsCursor) Next(dest []interface{}) error {
if rc.closed {
- return os.NewError("fakedb: cursor is closed")
+ return errors.New("fakedb: cursor is closed")
}
rc.pos++
if rc.pos >= len(rc.rows) {
- return os.EOF // per interface spec
+ return io.EOF // per interface spec
}
for i, v := range rc.rows[rc.pos].cols {
// TODO(bradfitz): convert to subset types? naah, I
package sql
import (
+ "errors"
"fmt"
- "os"
+ "io"
"runtime"
"sync"
}
// ScanInto implements the ScannerInto interface.
-func (ms *NullableString) ScanInto(value interface{}) os.Error {
+func (ms *NullableString) ScanInto(value interface{}) error {
if value == nil {
ms.String, ms.Valid = "", false
return nil
//
// An error should be returned if the value can not be stored
// without loss of information.
- ScanInto(value interface{}) os.Error
+ ScanInto(value interface{}) error
}
// ErrNoRows is returned by Scan when QueryRow doesn't return a
// row. In such a case, QueryRow returns a placeholder *Row value that
// defers this error until a Scan.
-var ErrNoRows = os.NewError("db: no rows in result set")
+var ErrNoRows = errors.New("db: no rows in result set")
// DB is a database handle. It's safe for concurrent use by multiple
// goroutines.
//
// Most users will open a database via a driver-specific connection
// helper function that returns a *DB.
-func Open(driverName, dataSourceName string) (*DB, os.Error) {
+func Open(driverName, dataSourceName string) (*DB, error) {
driver, ok := drivers[driverName]
if !ok {
return nil, fmt.Errorf("db: unknown driver %q (forgotten import?)", driverName)
}
// conn returns a newly-opened or cached driver.Conn
-func (db *DB) conn() (driver.Conn, os.Error) {
+func (db *DB) conn() (driver.Conn, error) {
db.mu.Lock()
if n := len(db.freeConn); n > 0 {
conn := db.freeConn[n-1]
}
// Prepare creates a prepared statement for later execution.
-func (db *DB) Prepare(query string) (*Stmt, os.Error) {
+func (db *DB) Prepare(query string) (*Stmt, error) {
// TODO: check if db.driver supports an optional
// driver.Preparer interface and call that instead, if so,
// otherwise we make a prepared statement that's bound
}
// Exec executes a query without returning any rows.
-func (db *DB) Exec(query string, args ...interface{}) (Result, os.Error) {
+func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
// Optional fast path, if the driver implements driver.Execer.
if execer, ok := db.driver.(driver.Execer); ok {
resi, err := execer.Exec(query, args)
}
// Query executes a query that returns rows, typically a SELECT.
-func (db *DB) Query(query string, args ...interface{}) (*Rows, os.Error) {
+func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
stmt, err := db.Prepare(query)
if err != nil {
return nil, err
// Begin starts a transaction. The isolation level is dependent on
// the driver.
-func (db *DB) Begin() (*Tx, os.Error) {
+func (db *DB) Begin() (*Tx, error) {
// TODO(bradfitz): add another method for beginning a transaction
// at a specific isolation level.
panic(todo())
}
// Commit commits the transaction.
-func (tx *Tx) Commit() os.Error {
+func (tx *Tx) Commit() error {
panic(todo())
}
// Rollback aborts the transaction.
-func (tx *Tx) Rollback() os.Error {
+func (tx *Tx) Rollback() error {
panic(todo())
}
// Prepare creates a prepared statement.
-func (tx *Tx) Prepare(query string) (*Stmt, os.Error) {
+func (tx *Tx) Prepare(query string) (*Stmt, error) {
panic(todo())
}
}
// Query executes a query that returns rows, typically a SELECT.
-func (tx *Tx) Query(query string, args ...interface{}) (*Rows, os.Error) {
+func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
panic(todo())
}
// Exec executes a prepared statement with the given arguments and
// returns a Result summarizing the effect of the statement.
-func (s *Stmt) Exec(args ...interface{}) (Result, os.Error) {
+func (s *Stmt) Exec(args ...interface{}) (Result, error) {
ci, si, err := s.connStmt()
if err != nil {
return nil, err
return result{resi}, nil
}
-func (s *Stmt) connStmt(args ...interface{}) (driver.Conn, driver.Stmt, os.Error) {
+func (s *Stmt) connStmt(args ...interface{}) (driver.Conn, driver.Stmt, error) {
s.mu.Lock()
if s.closed {
- return nil, nil, os.NewError("db: statement is closed")
+ return nil, nil, errors.New("db: statement is closed")
}
var cs connStmt
match := false
// Query executes a prepared query statement with the given arguments
// and returns the query results as a *Rows.
-func (s *Stmt) Query(args ...interface{}) (*Rows, os.Error) {
+func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
ci, si, err := s.connStmt(args...)
if err != nil {
return nil, err
}
// Close closes the statement.
-func (s *Stmt) Close() os.Error {
+func (s *Stmt) Close() error {
s.mu.Lock()
defer s.mu.Unlock() // TODO(bradfitz): move this unlock after 'closed = true'?
if s.closed {
closed bool
lastcols []interface{}
- lasterr os.Error
+ lasterr error
}
// Next prepares the next result row for reading with the Scan method.
}
// Error returns the error, if any, that was encountered during iteration.
-func (rs *Rows) Error() os.Error {
- if rs.lasterr == os.EOF {
+func (rs *Rows) Error() error {
+ if rs.lasterr == io.EOF {
return nil
}
return rs.lasterr
// at by dest. If dest contains pointers to []byte, the slices should
// not be modified and should only be considered valid until the next
// call to Next or Scan.
-func (rs *Rows) Scan(dest ...interface{}) os.Error {
+func (rs *Rows) Scan(dest ...interface{}) error {
if rs.closed {
- return os.NewError("db: Rows closed")
+ return errors.New("db: Rows closed")
}
if rs.lasterr != nil {
return rs.lasterr
}
if rs.lastcols == nil {
- return os.NewError("db: Scan called without calling Next")
+ return errors.New("db: Scan called without calling Next")
}
if len(dest) != len(rs.lastcols) {
return fmt.Errorf("db: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
// Close closes the Rows, preventing further enumeration. If the
// end is encountered, the Rows are closed automatically. Close
// is idempotent.
-func (rs *Rows) Close() os.Error {
+func (rs *Rows) Close() error {
if rs.closed {
return nil
}
// Row is the result of calling QueryRow to select a single row.
type Row struct {
// One of these two will be non-nil:
- err os.Error // deferred error for easy chaining
+ err error // deferred error for easy chaining
rows *Rows
}
// If dest contains pointers to []byte, the slices should not be
// modified and should only be considered valid until the next call to
// Next or Scan.
-func (r *Row) Scan(dest ...interface{}) os.Error {
+func (r *Row) Scan(dest ...interface{}) error {
if r.err != nil {
return r.err
}
// A Result summarizes an executed SQL command.
type Result interface {
- LastInsertId() (int64, os.Error)
- RowsAffected() (int64, os.Error)
+ LastInsertId() (int64, error)
+ RowsAffected() (int64, error)
}
type result struct {
var age int
err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age)
- if err == nil || !strings.Contains(err.String(), "expected 2 destination arguments") {
+ if err == nil || !strings.Contains(err.Error(), "expected 2 destination arguments") {
t.Errorf("expected error from wrong number of arguments; actually got: %v", err)
}
if err == nil {
t.Fatalf("expected error")
}
- if err.String() != `fakedb: invalid conversion to int32 from "bogusconversion"` {
+ if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` {
t.Errorf("unexpected error: %v", err)
}
}
_, err := stmt.Exec(et.args...)
errStr := ""
if err != nil {
- errStr = err.String()
+ errStr = err.Error()
}
if errStr != et.wantErr {
t.Errorf("stmt.Execute #%d: for %v, got error %q, want error %q",
package ssh
import (
- "os"
+ "errors"
+ "io"
"sync"
)
// SSH connection.
type Channel interface {
// Accept accepts the channel creation request.
- Accept() os.Error
+ Accept() error
// Reject rejects the channel creation request. After calling this, no
// other methods on the Channel may be called. If they are then the
// peer is likely to signal a protocol error and drop the connection.
- Reject(reason RejectionReason, message string) os.Error
+ Reject(reason RejectionReason, message string) error
- // Read may return a ChannelRequest as an os.Error.
- Read(data []byte) (int, os.Error)
- Write(data []byte) (int, os.Error)
- Close() os.Error
+ // Read may return a ChannelRequest as an error.
+ Read(data []byte) (int, error)
+ Write(data []byte) (int, error)
+ Close() error
// AckRequest either sends an ack or nack to the channel request.
- AckRequest(ok bool) os.Error
+ AckRequest(ok bool) error
// ChannelType returns the type of the channel, as supplied by the
// client.
Payload []byte
}
-func (c ChannelRequest) String() string {
+func (c ChannelRequest) Error() string {
return "channel request received"
}
myId, theirId uint32
myWindow, theirWindow uint32
maxPacketSize uint32
- err os.Error
+ err error
pendingRequests []ChannelRequest
pendingData []byte
cond *sync.Cond
}
-func (c *channel) Accept() os.Error {
+func (c *channel) Accept() error {
c.serverConn.lock.Lock()
defer c.serverConn.lock.Unlock()
return c.serverConn.writePacket(marshal(msgChannelOpenConfirm, confirm))
}
-func (c *channel) Reject(reason RejectionReason, message string) os.Error {
+func (c *channel) Reject(reason RejectionReason, message string) error {
c.serverConn.lock.Lock()
defer c.serverConn.lock.Unlock()
c.cond.Signal()
}
-func (c *channel) Read(data []byte) (n int, err os.Error) {
+func (c *channel) Read(data []byte) (n int, err error) {
c.lock.Lock()
defer c.lock.Unlock()
for {
if c.theySentEOF || c.theyClosed || c.dead {
- return 0, os.EOF
+ return 0, io.EOF
}
if len(c.pendingRequests) > 0 {
panic("unreachable")
}
-func (c *channel) Write(data []byte) (n int, err os.Error) {
+func (c *channel) Write(data []byte) (n int, err error) {
for len(data) > 0 {
c.lock.Lock()
if c.dead || c.weClosed {
- return 0, os.EOF
+ return 0, io.EOF
}
if c.theirWindow == 0 {
return
}
-func (c *channel) Close() os.Error {
+func (c *channel) Close() error {
c.serverConn.lock.Lock()
defer c.serverConn.lock.Unlock()
}
if c.weClosed {
- return os.NewError("ssh: channel already closed")
+ return errors.New("ssh: channel already closed")
}
c.weClosed = true
return c.serverConn.writePacket(marshal(msgChannelClose, closeMsg))
}
-func (c *channel) AckRequest(ok bool) os.Error {
+func (c *channel) AckRequest(ok bool) error {
c.serverConn.lock.Lock()
defer c.serverConn.lock.Unlock()
"big"
"crypto"
"crypto/rand"
+ "errors"
"fmt"
"io"
"net"
- "os"
"sync"
)
}
// Client returns a new SSH client connection using c as the underlying transport.
-func Client(c net.Conn, config *ClientConfig) (*ClientConn, os.Error) {
+func Client(c net.Conn, config *ClientConfig) (*ClientConn, error) {
conn := &ClientConn{
transport: newTransport(c, config.rand()),
config: config,
}
// handshake performs the client side key exchange. See RFC 4253 Section 7.
-func (c *ClientConn) handshake() os.Error {
+func (c *ClientConn) handshake() error {
var magics handshakeMagics
if _, err := c.Write(clientVersion); err != nil {
kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit)
if !ok {
- return os.NewError("ssh: no common algorithms")
+ return errors.New("ssh: no common algorithms")
}
if serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] {
// authenticate authenticates with the remote server. See RFC 4252.
// Only "password" authentication is supported.
-func (c *ClientConn) authenticate() os.Error {
+func (c *ClientConn) authenticate() error {
if err := c.writePacket(marshal(msgServiceRequest, serviceRequestMsg{serviceUserAuth})); err != nil {
return err
}
return nil
}
-func (c *ClientConn) sendUserAuthReq(method string) os.Error {
+func (c *ClientConn) sendUserAuthReq(method string) error {
length := stringLength([]byte(c.config.Password)) + 1
payload := make([]byte, length)
// always false for password auth, see RFC 4252 Section 8.
// kexDH performs Diffie-Hellman key agreement on a ClientConn. The
// returned values are given the same names as in RFC 4253, section 8.
-func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, os.Error) {
+func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, error) {
x, err := rand.Int(c.config.rand(), group.p)
if err != nil {
return nil, nil, err
}
if kexDHReply.Y.Sign() == 0 || kexDHReply.Y.Cmp(group.p) >= 0 {
- return nil, nil, os.NewError("server DH parameter out of bounds")
+ return nil, nil, errors.New("server DH parameter out of bounds")
}
kInt := new(big.Int).Exp(kexDHReply.Y, x, group.p)
// openChan opens a new client channel. The most common session type is "session".
// The full set of valid session types are listed in RFC 4250 4.9.1.
-func (c *ClientConn) openChan(typ string) (*clientChan, os.Error) {
+func (c *ClientConn) openChan(typ string) (*clientChan, error) {
ch := c.newChan(c.transport)
if err := c.writePacket(marshal(msgChannelOpen, channelOpenMsg{
ChanType: typ,
ch.peersId = msg.MyId
case *channelOpenFailureMsg:
c.chanlist.remove(ch.id)
- return nil, os.NewError(msg.Message)
+ return nil, errors.New(msg.Message)
default:
c.chanlist.remove(ch.id)
- return nil, os.NewError("Unexpected packet")
+ return nil, errors.New("Unexpected packet")
}
return ch, nil
}
// Dial connects to the given network address using net.Dial and
// then initiates a SSH handshake, returning the resulting client connection.
-func Dial(network, addr string, config *ClientConfig) (*ClientConn, os.Error) {
+func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
conn, err := net.Dial(network, addr)
if err != nil {
return nil, err
}
// Close closes the channel. This does not close the underlying connection.
-func (c *clientChan) Close() os.Error {
+func (c *clientChan) Close() error {
return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
PeersId: c.id,
}))
}
-func (c *clientChan) sendChanReq(req channelRequestMsg) os.Error {
+func (c *clientChan) sendChanReq(req channelRequestMsg) error {
if err := c.writePacket(marshal(msgChannelRequest, req)); err != nil {
return err
}
}
// Write writes data to the remote process's standard input.
-func (w *chanWriter) Write(data []byte) (n int, err os.Error) {
+func (w *chanWriter) Write(data []byte) (n int, err error) {
for {
if w.rwin == 0 {
win, ok := <-w.win
if !ok {
- return 0, os.EOF
+ return 0, io.EOF
}
w.rwin += win
continue
panic("unreachable")
}
-func (w *chanWriter) Close() os.Error {
+func (w *chanWriter) Close() error {
return w.writePacket(marshal(msgChannelEOF, channelEOFMsg{w.id}))
}
}
// Read reads data from the remote process's stdout or stderr.
-func (r *chanReader) Read(data []byte) (int, os.Error) {
+func (r *chanReader) Read(data []byte) (int, error) {
var ok bool
for {
if len(r.buf) > 0 {
}
r.buf, ok = <-r.data
if !ok {
- return 0, os.EOF
+ return 0, io.EOF
}
}
panic("unreachable")
}
-func (r *chanReader) Close() os.Error {
+func (r *chanReader) Close() error {
return r.writePacket(marshal(msgChannelEOF, channelEOFMsg{r.id}))
}
expected, got uint8
}
-func (u UnexpectedMessageError) String() string {
+func (u UnexpectedMessageError) Error() string {
return "ssh: unexpected message type " + strconv.Itoa(int(u.got)) + " (expected " + strconv.Itoa(int(u.expected)) + ")"
}
msgType uint8
}
-func (p ParseError) String() string {
+func (p ParseError) Error() string {
return "ssh: parse error in message type " + strconv.Itoa(int(p.msgType))
}
"big"
"bytes"
"io"
- "os"
"reflect"
)
// unmarshal parses the SSH wire data in packet into out using reflection.
// expectedType is the expected SSH message type. It either returns nil on
// success, or a ParseError or UnexpectedMessageError on error.
-func unmarshal(out interface{}, packet []byte, expectedType uint8) os.Error {
+func unmarshal(out interface{}, packet []byte, expectedType uint8) error {
if len(packet) == 0 {
return ParseError{expectedType}
}
"crypto/rsa"
"crypto/x509"
"encoding/pem"
+ "errors"
"io"
"net"
- "os"
"sync"
)
// private key configured in order to accept connections. The private key must
// be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa"
// typically contains such a key.
-func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) os.Error {
+func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error {
block, _ := pem.Decode(pemBytes)
if block == nil {
- return os.NewError("ssh: no key found")
+ return errors.New("ssh: no key found")
}
- var err os.Error
+ var err error
s.rsa, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return err
// lock protects err and also allows Channels to serialise their writes
// to out.
lock sync.RWMutex
- err os.Error
+ err error
// cachedPubKeys contains the cache results of tests for public keys.
// Since SSH clients will query whether a public key is acceptable
// kexDH performs Diffie-Hellman key agreement on a ServerConnection. The
// returned values are given the same names as in RFC 4253, section 8.
-func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err os.Error) {
+func (s *ServerConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) (H, K []byte, err error) {
packet, err := s.readPacket()
if err != nil {
return
}
if kexDHInit.X.Sign() == 0 || kexDHInit.X.Cmp(group.p) >= 0 {
- return nil, nil, os.NewError("client DH parameter out of bounds")
+ return nil, nil, errors.New("client DH parameter out of bounds")
}
y, err := rand.Int(s.config.rand(), group.p)
case hostAlgoRSA:
serializedHostKey = s.config.rsaSerialized
default:
- return nil, nil, os.NewError("internal error")
+ return nil, nil, errors.New("internal error")
}
h := hashFunc.New()
return
}
default:
- return nil, nil, os.NewError("internal error")
+ return nil, nil, errors.New("internal error")
}
serializedSig := serializeRSASignature(sig)
}
// Handshake performs an SSH transport and client authentication on the given ServerConn.
-func (s *ServerConn) Handshake() os.Error {
+func (s *ServerConn) Handshake() error {
var magics handshakeMagics
if _, err := s.Write(serverVersion); err != nil {
return err
kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(s.transport, &clientKexInit, &serverKexInit)
if !ok {
- return os.NewError("ssh: no common algorithms")
+ return errors.New("ssh: no common algorithms")
}
if clientKexInit.FirstKexFollows && kexAlgo != clientKexInit.KexAlgos[0] {
dhGroup14Once.Do(initDHGroup14)
H, K, err = s.kexDH(dhGroup14, hashFunc, &magics, hostKeyAlgo)
default:
- err = os.NewError("ssh: unexpected key exchange algorithm " + kexAlgo)
+ err = errors.New("ssh: unexpected key exchange algorithm " + kexAlgo)
}
if err != nil {
return err
return err
}
if serviceRequest.Service != serviceUserAuth {
- return os.NewError("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
+ return errors.New("ssh: requested service '" + serviceRequest.Service + "' before authenticating")
}
serviceAccept := serviceAcceptMsg{
Service: serviceUserAuth,
return result
}
-func (s *ServerConn) authenticate(H []byte) os.Error {
+func (s *ServerConn) authenticate(H []byte) error {
var userAuthReq userAuthRequestMsg
- var err os.Error
+ var err error
var packet []byte
userAuthLoop:
}
if userAuthReq.Service != serviceSSH {
- return os.NewError("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
+ return errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
}
switch userAuthReq.Method {
return ParseError{msgUserAuthRequest}
}
default:
- return os.NewError("ssh: isAcceptableAlgo incorrect")
+ return errors.New("ssh: isAcceptableAlgo incorrect")
}
if s.testPubKey(userAuthReq.User, algo, pubKey) {
break userAuthLoop
}
if len(failureMsg.Methods) == 0 {
- return os.NewError("ssh: no authentication methods configured but NoClientAuth is also false")
+ return errors.New("ssh: no authentication methods configured but NoClientAuth is also false")
}
if err = s.writePacket(marshal(msgUserAuthFailure, failureMsg)); err != nil {
// Accept reads and processes messages on a ServerConn. It must be called
// in order to demultiplex messages to any resulting Channels.
-func (s *ServerConn) Accept() (Channel, os.Error) {
+func (s *ServerConn) Accept() (Channel, error) {
if s.err != nil {
return nil, s.err
}
case UnexpectedMessageError:
return nil, msg
case *disconnectMsg:
- return nil, os.EOF
+ return nil, io.EOF
default:
// Unknown message. Ignore.
}
// Accept waits for and returns the next incoming SSH connection.
// The receiver should call Handshake() in another goroutine
// to avoid blocking the accepter.
-func (l *Listener) Accept() (*ServerConn, os.Error) {
+func (l *Listener) Accept() (*ServerConn, error) {
c, err := l.listener.Accept()
if err != nil {
return nil, err
}
// Close closes the listener.
-func (l *Listener) Close() os.Error {
+func (l *Listener) Close() error {
return l.listener.Close()
}
// Listen creates an SSH listener accepting connections on
// the given network address using net.Listen.
-func Listen(network, addr string, config *ServerConfig) (*Listener, os.Error) {
+func Listen(network, addr string, config *ServerConfig) (*Listener, error) {
l, err := net.Listen(network, addr)
if err != nil {
return nil, err
package ssh
-import (
- "os"
-)
+import "io"
// ServerShell contains the state for running a VT100 terminal that is capable
// of reading lines of input.
return
}
-func (ss *ServerShell) Write(buf []byte) (n int, err os.Error) {
+func (ss *ServerShell) Write(buf []byte) (n int, err error) {
return ss.c.Write(buf)
}
// ReadLine returns a line of input from the terminal.
-func (ss *ServerShell) ReadLine() (line string, err os.Error) {
+func (ss *ServerShell) ReadLine() (line string, err error) {
ss.writeLine([]byte(ss.prompt))
ss.c.Write(ss.outBuf)
ss.outBuf = ss.outBuf[:0]
break
}
if key == keyCtrlD {
- return "", os.EOF
+ return "", io.EOF
}
line, lineOk = ss.handleKey(key)
}
package ssh
import (
+ "io"
"testing"
- "os"
)
type MockChannel struct {
received []byte
}
-func (c *MockChannel) Accept() os.Error {
+func (c *MockChannel) Accept() error {
return nil
}
-func (c *MockChannel) Reject(RejectionReason, string) os.Error {
+func (c *MockChannel) Reject(RejectionReason, string) error {
return nil
}
-func (c *MockChannel) Read(data []byte) (n int, err os.Error) {
+func (c *MockChannel) Read(data []byte) (n int, err error) {
n = len(data)
if n == 0 {
return
n = len(c.toSend)
}
if n == 0 {
- return 0, os.EOF
+ return 0, io.EOF
}
if c.bytesPerRead > 0 && n > c.bytesPerRead {
n = c.bytesPerRead
return
}
-func (c *MockChannel) Write(data []byte) (n int, err os.Error) {
+func (c *MockChannel) Write(data []byte) (n int, err error) {
c.received = append(c.received, data...)
return len(data), nil
}
-func (c *MockChannel) Close() os.Error {
+func (c *MockChannel) Close() error {
return nil
}
-func (c *MockChannel) AckRequest(ok bool) os.Error {
+func (c *MockChannel) AckRequest(ok bool) error {
return nil
}
if line != "" {
t.Errorf("Expected empty line but got: %s", line)
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("Error should have been EOF but got: %s", err)
}
}
var keyPressTests = []struct {
in string
line string
- err os.Error
+ err error
}{
{
"",
"",
- os.EOF,
+ io.EOF,
},
{
"\r",
import (
"encoding/binary"
+ "errors"
"io"
- "os"
)
// A Session represents a connection to a remote command or shell.
// Setenv sets an environment variable that will be applied to any
// command executed by Shell or Exec.
-func (s *Session) Setenv(name, value string) os.Error {
+func (s *Session) Setenv(name, value string) error {
n, v := []byte(name), []byte(value)
nlen, vlen := stringLength(n), stringLength(v)
payload := make([]byte, nlen+vlen)
var emptyModeList = []byte{0, 0, 0, 1, 0}
// RequestPty requests the association of a pty with the session on the remote host.
-func (s *Session) RequestPty(term string, h, w int) os.Error {
+func (s *Session) RequestPty(term string, h, w int) error {
buf := make([]byte, 4+len(term)+16+len(emptyModeList))
b := marshalString(buf, []byte(term))
binary.BigEndian.PutUint32(b, uint32(h))
// Exec runs cmd on the remote host. Typically, the remote
// server passes cmd to the shell for interpretation.
// A Session only accepts one call to Exec or Shell.
-func (s *Session) Exec(cmd string) os.Error {
+func (s *Session) Exec(cmd string) error {
if s.started {
- return os.NewError("session already started")
+ return errors.New("session already started")
}
cmdLen := stringLength([]byte(cmd))
payload := make([]byte, cmdLen)
// Shell starts a login shell on the remote host. A Session only
// accepts one call to Exec or Shell.
-func (s *Session) Shell() os.Error {
+func (s *Session) Shell() error {
if s.started {
- return os.NewError("session already started")
+ return errors.New("session already started")
}
s.started = true
}
// NewSession returns a new interactive session on the remote host.
-func (c *ClientConn) NewSession() (*Session, os.Error) {
+func (c *ClientConn) NewSession() (*Session, error) {
ch, err := c.openChan("session")
if err != nil {
return nil, err
"crypto/cipher"
"crypto/hmac"
"crypto/subtle"
+ "errors"
"hash"
"io"
"net"
- "os"
"sync"
)
// TODO(dfc) suggestions for a better name will be warmly received.
type filteredConn interface {
// Close closes the connection.
- Close() os.Error
+ Close() error
// LocalAddr returns the local network address.
LocalAddr() net.Addr
// an SSH peer.
type packetWriter interface {
// Encrypt and send a packet of data to the remote peer.
- writePacket(packet []byte) os.Error
+ writePacket(packet []byte) error
}
// transport represents the SSH connection to the remote peer.
}
// Read and decrypt a single packet from the remote peer.
-func (r *reader) readOnePacket() ([]byte, os.Error) {
+func (r *reader) readOnePacket() ([]byte, error) {
var lengthBytes = make([]byte, 5)
var macSize uint32
paddingLength := uint32(lengthBytes[4])
if length <= paddingLength+1 {
- return nil, os.NewError("invalid packet length")
+ return nil, errors.New("invalid packet length")
}
if length > maxPacketSize {
- return nil, os.NewError("packet too large")
+ return nil, errors.New("packet too large")
}
packet := make([]byte, length-1+macSize)
if r.mac != nil {
r.mac.Write(packet[:length-1])
if subtle.ConstantTimeCompare(r.mac.Sum(), mac) != 1 {
- return nil, os.NewError("ssh: MAC failure")
+ return nil, errors.New("ssh: MAC failure")
}
}
}
// Read and decrypt next packet discarding debug and noop messages.
-func (t *transport) readPacket() ([]byte, os.Error) {
+func (t *transport) readPacket() ([]byte, error) {
for {
packet, err := t.readOnePacket()
if err != nil {
}
// Encrypt and send a packet of data to the remote peer.
-func (w *writer) writePacket(packet []byte) os.Error {
+func (w *writer) writePacket(packet []byte) error {
w.Mutex.Lock()
defer w.Mutex.Unlock()
}
// Send a message to the remote peer
-func (t *transport) sendMessage(typ uint8, msg interface{}) os.Error {
+func (t *transport) sendMessage(typ uint8, msg interface{}) error {
packet := marshal(typ, msg)
return t.writePacket(packet)
}
// setupKeys sets the cipher and MAC keys from K, H and sessionId, as
// described in RFC 4253, section 6.4. direction should either be serverKeys
// (to setup server->client keys) or clientKeys (for client->server keys).
-func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) os.Error {
+func (c *common) setupKeys(d direction, K, H, sessionId []byte, hashFunc crypto.Hash) error {
h := hashFunc.New()
blockSize := 16
hmac hash.Hash
}
-func (t truncatingMAC) Write(data []byte) (int, os.Error) {
+func (t truncatingMAC) Write(data []byte) (int, error) {
return t.hmac.Write(data)
}
const maxVersionStringBytes = 1024
// Read version string as specified by RFC 4253, section 4.2.
-func readVersion(r io.Reader) ([]byte, os.Error) {
+func readVersion(r io.Reader) ([]byte, error) {
versionString := make([]byte, 0, 64)
var ok, seenCR bool
var buf [1]byte
}
if !ok {
- return nil, os.NewError("failed to read version string")
+ return nil, errors.New("failed to read version string")
}
// We need to remove the CR from versionString
ErrSlashAmbig
)
-func (e *Error) String() string {
+func (e *Error) Error() string {
if e.Line != 0 {
return fmt.Sprintf("exp/template/html:%s:%d: %s", e.Name, e.Line, e.Description)
} else if e.Name != "" {
"bytes"
"fmt"
"html"
- "os"
"template"
"template/parse"
)
// Escape rewrites each action in the template to guarantee that the output is
// properly escaped.
-func Escape(t *template.Template) (*template.Template, os.Error) {
+func Escape(t *template.Template) (*template.Template, error) {
var s template.Set
s.Add(t)
if _, err := EscapeSet(&s, t.Name()); err != nil {
// need not include helper templates.
// If no error is returned, then the named templates have been modified.
// Otherwise the named templates have been rendered unusable.
-func EscapeSet(s *template.Set, names ...string) (*template.Set, os.Error) {
+func EscapeSet(s *template.Set, names ...string) (*template.Set, error) {
if len(names) == 0 {
// TODO: Maybe add a method to Set to enumerate template names
// and use those instead.
e := newEscaper(s)
for _, name := range names {
c, _ := e.escapeTree(context{}, name, 0)
- var err os.Error
+ var err error
if c.err != nil {
err, c.err.Name = c.err, name
} else if c.state != stateText {
"bytes"
"fmt"
"json"
- "os"
"strings"
"template"
"template/parse"
type badMarshaler struct{}
-func (x *badMarshaler) MarshalJSON() ([]byte, os.Error) {
+func (x *badMarshaler) MarshalJSON() ([]byte, error) {
// Keys in valid JSON must be double quoted as must all strings.
return []byte("{ foo: 'not quite valid JSON' }"), nil
}
type goodMarshaler struct{}
-func (x *goodMarshaler) MarshalJSON() ([]byte, os.Error) {
+func (x *goodMarshaler) MarshalJSON() ([]byte, error) {
return []byte(`{ "<foo>": "O'Reilly" }`), nil
}
// pred is a template function that returns the predecessor of a
// natural number for testing recursive templates.
- fns := template.FuncMap{"pred": func(a ...interface{}) (interface{}, os.Error) {
+ fns := template.FuncMap{"pred": func(a ...interface{}) (interface{}, error) {
if len(a) == 1 {
if i, _ := a[0].(int); i > 0 {
return i - 1, nil
var b bytes.Buffer
if err := s.Execute(&b, "main", data); err != nil {
- t.Errorf("%q executing %v", err.String(), s.Template("main"))
+ t.Errorf("%q executing %v", err.Error(), s.Template("main"))
continue
}
if got := b.String(); test.want != got {
}
for _, test := range tests {
- var err os.Error
+ var err error
if strings.HasPrefix(test.input, "{{define") {
var s template.Set
_, err = s.Parse(test.input)
}
var got string
if err != nil {
- got = err.String()
+ got = err.Error()
}
if test.err == "" {
if got != "" {
}
}
-func expectExecuteFailure(t *testing.T, b *bytes.Buffer, err os.Error) {
+func expectExecuteFailure(t *testing.T, b *bytes.Buffer, err error) {
if err != nil {
if b.Len() != 0 {
t.Errorf("output on buffer: %q", b.String())
// turning into
// x//* error marshalling y:
// second line of error message */null
- return fmt.Sprintf(" /* %s */null ", strings.Replace(err.String(), "*/", "* /", -1))
+ return fmt.Sprintf(" /* %s */null ", strings.Replace(err.Error(), "*/", "* /", -1))
}
// TODO: maybe post-process output to prevent it from containing
package terminal
-import (
- "os"
- "io"
-)
+import "io"
// Shell contains the state for running a VT100 terminal that is capable of
// reading lines of input.
}
}
-func (ss *Shell) Write(buf []byte) (n int, err os.Error) {
+func (ss *Shell) Write(buf []byte) (n int, err error) {
return ss.c.Write(buf)
}
// ReadLine returns a line of input from the terminal.
-func (ss *Shell) ReadLine() (line string, err os.Error) {
+func (ss *Shell) ReadLine() (line string, err error) {
ss.writeLine([]byte(ss.prompt))
ss.c.Write(ss.outBuf)
ss.outBuf = ss.outBuf[:0]
break
}
if key == keyCtrlD {
- return "", os.EOF
+ return "", io.EOF
}
line, lineOk = ss.handleKey(key)
}
package terminal
import (
+ "io"
"testing"
- "os"
)
type MockTerminal struct {
received []byte
}
-func (c *MockTerminal) Read(data []byte) (n int, err os.Error) {
+func (c *MockTerminal) Read(data []byte) (n int, err error) {
n = len(data)
if n == 0 {
return
n = len(c.toSend)
}
if n == 0 {
- return 0, os.EOF
+ return 0, io.EOF
}
if c.bytesPerRead > 0 && n > c.bytesPerRead {
n = c.bytesPerRead
return
}
-func (c *MockTerminal) Write(data []byte) (n int, err os.Error) {
+func (c *MockTerminal) Write(data []byte) (n int, err error) {
c.received = append(c.received, data...)
return len(data), nil
}
if line != "" {
t.Errorf("Expected empty line but got: %s", line)
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("Error should have been EOF but got: %s", err)
}
}
var keyPressTests = []struct {
in string
line string
- err os.Error
+ err error
}{
{
"",
"",
- os.EOF,
+ io.EOF,
},
{
"\r",
package terminal
import (
+ "io"
"os"
"syscall"
)
// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
-func MakeRaw(fd int) (*State, os.Error) {
+func MakeRaw(fd int) (*State, error) {
var oldState State
if e := syscall.Tcgetattr(fd, &oldState.termios); e != 0 {
return nil, os.Errno(e)
// Restore restores the terminal connected to the given file descriptor to a
// previous state.
-func Restore(fd int, state *State) os.Error {
+func Restore(fd int, state *State) error {
e := syscall.Tcsetattr(fd, syscall.TCSANOW, &state.termios)
return os.Errno(e)
}
// ReadPassword reads a line of input from a terminal without local echo. This
// is commonly used for inputting passwords and other sensitive data. The slice
// returned does not include the \n.
-func ReadPassword(fd int) ([]byte, os.Error) {
+func ReadPassword(fd int) ([]byte, error) {
var oldState syscall.Termios
if e := syscall.Tcgetattr(fd, &oldState); e != 0 {
return nil, os.Errno(e)
}
if n == 0 {
if len(ret) == 0 {
- return nil, os.EOF
+ return nil, io.EOF
}
break
}
"go/ast"
"go/scanner"
"go/token"
- "os"
"strconv"
)
// of types for all expression nodes in statements, and a scanner.ErrorList if
// there are errors.
//
-func Check(fset *token.FileSet, pkg *ast.Package) (types map[ast.Expr]Type, err os.Error) {
+func Check(fset *token.FileSet, pkg *ast.Package) (types map[ast.Expr]Type, err error) {
var c checker
c.fset = fset
c.types = make(map[ast.Expr]Type)
// TODO(gri) Need to revisit parser interface. We should be able to use parser.ParseFiles
// or a similar function instead.
-func parseFiles(t *testing.T, testname string, filenames []string) (map[string]*ast.File, os.Error) {
+func parseFiles(t *testing.T, testname string, filenames []string) (map[string]*ast.File, error) {
files := make(map[string]*ast.File)
var errors scanner.ErrorList
for _, filename := range filenames {
return errors
}
-func eliminate(t *testing.T, expected map[token.Pos]string, errors os.Error) {
+func eliminate(t *testing.T, expected map[token.Pos]string, errors error) {
if errors == nil {
return
}
import (
"bufio"
+ "errors"
"fmt"
"io"
"os"
"strings"
)
-func readGopackHeader(buf *bufio.Reader) (name string, size int, err os.Error) {
+func readGopackHeader(buf *bufio.Reader) (name string, size int, err error) {
// See $GOROOT/include/ar.h.
hdr := make([]byte, 16+12+6+6+8+10+2)
_, err = io.ReadFull(buf, hdr)
s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10]))
size, err = strconv.Atoi(s)
if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' {
- err = os.NewError("invalid archive header")
+ err = errors.New("invalid archive header")
return
}
name = strings.TrimSpace(string(hdr[:16]))
// export data section of the given object/archive file, or an error.
// It is the caller's responsibility to close the readCloser.
//
-func ExportData(filename string) (rc io.ReadCloser, err os.Error) {
+func ExportData(filename string) (rc io.ReadCloser, err error) {
file, err := os.Open(filename)
if err != nil {
return
return
}
if name != "__.SYMDEF" {
- err = os.NewError("go archive does not begin with __.SYMDEF")
+ err = errors.New("go archive does not begin with __.SYMDEF")
return
}
const block = 4096
return
}
if name != "__.PKGDEF" {
- err = os.NewError("go archive is missing __.PKGDEF")
+ err = errors.New("go archive is missing __.PKGDEF")
return
}
// Now at __.PKGDEF in archive or still at beginning of file.
// Either way, line should begin with "go object ".
if !strings.HasPrefix(string(line), "go object ") {
- err = os.NewError("not a go object file")
+ err = errors.New("not a go object file")
return
}
import (
"big"
+ "errors"
"fmt"
"go/ast"
"go/token"
}
// GcImporter implements the ast.Importer signature.
-func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, err os.Error) {
+func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, err error) {
if path == "unsafe" {
return Unsafe, nil
}
filename, id := findPkg(path)
if filename == "" {
- err = os.NewError("can't find import: " + id)
+ err = errors.New("can't find import: " + id)
return
}
// Internal errors are boxed as importErrors.
type importError struct {
pos scanner.Position
- err os.Error
+ err error
}
-func (e importError) String() string {
+func (e importError) Error() string {
return fmt.Sprintf("import error %s (byte offset = %d): %s", e.pos, e.pos.Offset, e.err)
}
func (p *gcParser) error(err interface{}) {
if s, ok := err.(string); ok {
- err = os.NewError(s)
+ err = errors.New(s)
}
- // panic with a runtime.Error if err is not an os.Error
- panic(importError{p.scanner.Pos(), err.(os.Error)})
+ // panic with a runtime.Error if err is not an error
+ panic(importError{p.scanner.Pos(), err.(error)})
}
func (p *gcParser) errorf(format string, args ...interface{}) {
defType("rune") // TODO(gri) should be an alias for int
defType("complex64")
Complex128 = defType("complex128")
+ defType("error")
defType("float32")
Float64 = defType("float64")
defType("int8")
package winfsnotify
import (
+ "errors"
"fmt"
"os"
"path/filepath"
op int
path string
flags uint32
- reply chan os.Error
+ reply chan error
}
type inode struct {
watches watchMap // Map of watches (key: i-number)
input chan *input // Inputs to the reader are sent on this channel
Event chan *Event // Events are returned on this channel
- Error chan os.Error // Errors are sent on this channel
+ Error chan error // Errors are sent on this channel
isClosed bool // Set to true when Close() is first called
- quit chan chan<- os.Error
+ quit chan chan<- error
cookie uint32
}
// NewWatcher creates and returns a Watcher.
-func NewWatcher() (*Watcher, os.Error) {
+func NewWatcher() (*Watcher, error) {
port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)
if e != 0 {
return nil, os.NewSyscallError("CreateIoCompletionPort", e)
watches: make(watchMap),
input: make(chan *input, 1),
Event: make(chan *Event, 50),
- Error: make(chan os.Error),
- quit: make(chan chan<- os.Error, 1),
+ Error: make(chan error),
+ quit: make(chan chan<- error, 1),
}
go w.readEvents()
return w, nil
// Close closes a Watcher.
// It sends a message to the reader goroutine to quit and removes all watches
// associated with the watcher.
-func (w *Watcher) Close() os.Error {
+func (w *Watcher) Close() error {
if w.isClosed {
return nil
}
w.isClosed = true
// Send "quit" message to the reader goroutine
- ch := make(chan os.Error)
+ ch := make(chan error)
w.quit <- ch
if err := w.wakeupReader(); err != nil {
return err
}
// AddWatch adds path to the watched file set.
-func (w *Watcher) AddWatch(path string, flags uint32) os.Error {
+func (w *Watcher) AddWatch(path string, flags uint32) error {
if w.isClosed {
- return os.NewError("watcher already closed")
+ return errors.New("watcher already closed")
}
in := &input{
op: opAddWatch,
path: filepath.Clean(path),
flags: flags,
- reply: make(chan os.Error),
+ reply: make(chan error),
}
w.input <- in
if err := w.wakeupReader(); err != nil {
}
// Watch adds path to the watched file set, watching all events.
-func (w *Watcher) Watch(path string) os.Error {
+func (w *Watcher) Watch(path string) error {
return w.AddWatch(path, FS_ALL_EVENTS)
}
// RemoveWatch removes path from the watched file set.
-func (w *Watcher) RemoveWatch(path string) os.Error {
+func (w *Watcher) RemoveWatch(path string) error {
in := &input{
op: opRemoveWatch,
path: filepath.Clean(path),
- reply: make(chan os.Error),
+ reply: make(chan error),
}
w.input <- in
if err := w.wakeupReader(); err != nil {
return <-in.reply
}
-func (w *Watcher) wakeupReader() os.Error {
+func (w *Watcher) wakeupReader() error {
e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil)
if e != 0 {
return os.NewSyscallError("PostQueuedCompletionStatus", e)
return nil
}
-func getDir(pathname string) (dir string, err os.Error) {
+func getDir(pathname string) (dir string, err error) {
attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname))
if e != 0 {
return "", os.NewSyscallError("GetFileAttributes", e)
return
}
-func getIno(path string) (ino *inode, err os.Error) {
+func getIno(path string) (ino *inode, err error) {
h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path),
syscall.FILE_LIST_DIRECTORY,
syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
}
// Must run within the I/O thread.
-func (w *Watcher) addWatch(pathname string, flags uint64) os.Error {
+func (w *Watcher) addWatch(pathname string, flags uint64) error {
dir, err := getDir(pathname)
if err != nil {
return err
}
// Must run within the I/O thread.
-func (w *Watcher) removeWatch(pathname string) os.Error {
+func (w *Watcher) removeWatch(pathname string) error {
dir, err := getDir(pathname)
if err != nil {
return err
}
// Must run within the I/O thread.
-func (w *Watcher) startRead(watch *watch) os.Error {
+func (w *Watcher) startRead(watch *watch) error {
if e := syscall.CancelIo(watch.ino.handle); e != 0 {
w.Error <- os.NewSyscallError("CancelIo", e)
w.deleteWatch(watch)
w.startRead(watch)
}
}
- var err os.Error
+ var err error
if e := syscall.CloseHandle(w.port); e != 0 {
err = os.NewSyscallError("CloseHandle", e)
}
for {
if n == 0 {
w.Event <- &Event{Mask: FS_Q_OVERFLOW}
- w.Error <- os.NewError("short read in readEvents()")
+ w.Error <- errors.New("short read in readEvents()")
break
}
package flag
import (
+ "errors"
"fmt"
"os"
"sort"
)
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
-var ErrHelp = os.NewError("flag: help requested")
+var ErrHelp = errors.New("flag: help requested")
// -- Bool Value
type boolValue bool
// failf prints to standard error a formatted error and usage message and
// returns the error.
-func (f *FlagSet) failf(format string, a ...interface{}) os.Error {
+func (f *FlagSet) failf(format string, a ...interface{}) error {
err := fmt.Errorf(format, a...)
fmt.Fprintln(os.Stderr, err)
f.usage()
}
// parseOne parses one flag. It returns whether a flag was seen.
-func (f *FlagSet) parseOne() (bool, os.Error) {
+func (f *FlagSet) parseOne() (bool, error) {
if len(f.args) == 0 {
return false, nil
}
// include the command name. Must be called after all flags in the FlagSet
// are defined and before flags are accessed by the program.
// The return value will be ErrHelp if -help was set but not defined.
-func (f *FlagSet) Parse(arguments []string) os.Error {
+func (f *FlagSet) Parse(arguments []string) error {
f.parsed = true
f.args = arguments
for {
import (
"bytes"
+ "errors"
"io"
"os"
"reflect"
// the flags and options for the operand's format specifier.
type State interface {
// Write is the function to call to emit formatted output to be printed.
- Write(b []byte) (ret int, err os.Error)
+ Write(b []byte) (ret int, err error)
// Width returns the value of the width option and whether it has been set.
Width() (wid int, ok bool)
// Precision returns the value of the precision option and whether it has been set.
// Implement Write so we can call Fprintf on a pp (through State), for
// recursive use in custom verbs.
-func (p *pp) Write(b []byte) (ret int, err os.Error) {
+func (p *pp) Write(b []byte) (ret int, err error) {
return p.buf.Write(b)
}
// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
-func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err os.Error) {
+func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
n64, err := p.buf.WriteTo(w)
// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
-func Printf(format string, a ...interface{}) (n int, err os.Error) {
+func Printf(format string, a ...interface{}) (n int, err error) {
return Fprintf(os.Stdout, format, a...)
}
}
// Errorf formats according to a format specifier and returns the string
-// as a value that satisfies os.Error.
-func Errorf(format string, a ...interface{}) os.Error {
- return os.NewError(Sprintf(format, a...))
+// as a value that satisfies error.
+func Errorf(format string, a ...interface{}) error {
+ return errors.New(Sprintf(format, a...))
}
// These routines do not take a format string
// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
-func Fprint(w io.Writer, a ...interface{}) (n int, err os.Error) {
+func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrint(a, false, false)
n64, err := p.buf.WriteTo(w)
// Print formats using the default formats for its operands and writes to standard output.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
-func Print(a ...interface{}) (n int, err os.Error) {
+func Print(a ...interface{}) (n int, err error) {
return Fprint(os.Stdout, a...)
}
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
-func Fprintln(w io.Writer, a ...interface{}) (n int, err os.Error) {
+func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrint(a, true, true)
n64, err := p.buf.WriteTo(w)
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
-func Println(a ...interface{}) (n int, err os.Error) {
+func Println(a ...interface{}) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
// setting wasString and handled and deferring catchPanic
// must happen before calling the method.
switch v := p.field.(type) {
- case os.Error:
+ case error:
wasString = false
handled = true
defer p.catchPanic(p.field, verb)
- p.printField(v.String(), verb, plus, false, depth)
+ p.printField(v.Error(), verb, plus, false, depth)
return
case Stringer:
import (
"bytes"
+ "errors"
"io"
"math"
"os"
// a local buffer will be used to back up the input, but its contents
// will be lost when Scan returns.
type runeUnreader interface {
- UnreadRune() os.Error
+ UnreadRune() error
}
// ScanState represents the scanner state passed to custom scanners.
// If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
// return EOF after returning the first '\n' or when reading beyond
// the specified width.
- ReadRune() (r rune, size int, err os.Error)
+ ReadRune() (r rune, size int, err error)
// UnreadRune causes the next call to ReadRune to return the same rune.
- UnreadRune() os.Error
+ UnreadRune() error
// SkipSpace skips space in the input. Newlines are treated as space
// unless the scan operation is Scanln, Fscanln or Sscanln, in which case
// a newline is treated as EOF.
// EOF. The returned slice points to shared data that may be overwritten
// by the next call to Token, a call to a Scan function using the ScanState
// as input, or when the calling Scan method returns.
- Token(skipSpace bool, f func(rune) bool) (token []byte, err os.Error)
+ Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
// Width returns the value of the width option and whether it has been set.
// The unit is Unicode code points.
Width() (wid int, ok bool)
// Because ReadRune is implemented by the interface, Read should never be
// called by the scanning routines and a valid implementation of
// ScanState may choose always to return an error from Read.
- Read(buf []byte) (n int, err os.Error)
+ Read(buf []byte) (n int, err error)
}
// Scanner is implemented by any value that has a Scan method, which scans
// receiver, which must be a pointer to be useful. The Scan method is called
// for any argument to Scan, Scanf, or Scanln that implements it.
type Scanner interface {
- Scan(state ScanState, verb rune) os.Error
+ Scan(state ScanState, verb rune) error
}
// Scan scans text read from standard input, storing successive
// space-separated values into successive arguments. Newlines count
// as space. It returns the number of items successfully scanned.
// If that is less than the number of arguments, err will report why.
-func Scan(a ...interface{}) (n int, err os.Error) {
+func Scan(a ...interface{}) (n int, err error) {
return Fscan(os.Stdin, a...)
}
// Scanln is similar to Scan, but stops scanning at a newline and
// after the final item there must be a newline or EOF.
-func Scanln(a ...interface{}) (n int, err os.Error) {
+func Scanln(a ...interface{}) (n int, err error) {
return Fscanln(os.Stdin, a...)
}
// Scanf scans text read from standard input, storing successive
// space-separated values into successive arguments as determined by
// the format. It returns the number of items successfully scanned.
-func Scanf(format string, a ...interface{}) (n int, err os.Error) {
+func Scanf(format string, a ...interface{}) (n int, err error) {
return Fscanf(os.Stdin, format, a...)
}
// values into successive arguments. Newlines count as space. It
// returns the number of items successfully scanned. If that is less
// than the number of arguments, err will report why.
-func Sscan(str string, a ...interface{}) (n int, err os.Error) {
+func Sscan(str string, a ...interface{}) (n int, err error) {
return Fscan(strings.NewReader(str), a...)
}
// Sscanln is similar to Sscan, but stops scanning at a newline and
// after the final item there must be a newline or EOF.
-func Sscanln(str string, a ...interface{}) (n int, err os.Error) {
+func Sscanln(str string, a ...interface{}) (n int, err error) {
return Fscanln(strings.NewReader(str), a...)
}
// Sscanf scans the argument string, storing successive space-separated
// values into successive arguments as determined by the format. It
// returns the number of items successfully parsed.
-func Sscanf(str string, format string, a ...interface{}) (n int, err os.Error) {
+func Sscanf(str string, format string, a ...interface{}) (n int, err error) {
return Fscanf(strings.NewReader(str), format, a...)
}
// values into successive arguments. Newlines count as space. It
// returns the number of items successfully scanned. If that is less
// than the number of arguments, err will report why.
-func Fscan(r io.Reader, a ...interface{}) (n int, err os.Error) {
+func Fscan(r io.Reader, a ...interface{}) (n int, err error) {
s, old := newScanState(r, true, false)
n, err = s.doScan(a)
s.free(old)
// Fscanln is similar to Fscan, but stops scanning at a newline and
// after the final item there must be a newline or EOF.
-func Fscanln(r io.Reader, a ...interface{}) (n int, err os.Error) {
+func Fscanln(r io.Reader, a ...interface{}) (n int, err error) {
s, old := newScanState(r, false, true)
n, err = s.doScan(a)
s.free(old)
// Fscanf scans text read from r, storing successive space-separated
// values into successive arguments as determined by the format. It
// returns the number of items successfully parsed.
-func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err os.Error) {
+func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error) {
s, old := newScanState(r, false, false)
n, err = s.doScanf(format, a)
s.free(old)
// scanError represents an error generated by the scanning software.
// It's used as a unique signature to identify such errors when recovering.
type scanError struct {
- err os.Error
+ err error
}
const eof = -1
// The Read method is only in ScanState so that ScanState
// satisfies io.Reader. It will never be called when used as
// intended, so there is no need to make it actually work.
-func (s *ss) Read(buf []byte) (n int, err os.Error) {
- return 0, os.NewError("ScanState's Read should not be called. Use ReadRune")
+func (s *ss) Read(buf []byte) (n int, err error) {
+ return 0, errors.New("ScanState's Read should not be called. Use ReadRune")
}
-func (s *ss) ReadRune() (r rune, size int, err os.Error) {
+func (s *ss) ReadRune() (r rune, size int, err error) {
if s.peekRune >= 0 {
s.count++
r = s.peekRune
return
}
if s.atEOF || s.nlIsEnd && s.prevRune == '\n' || s.count >= s.fieldLimit {
- err = os.EOF
+ err = io.EOF
return
}
if err == nil {
s.count++
s.prevRune = r
- } else if err == os.EOF {
+ } else if err == io.EOF {
s.atEOF = true
}
return
func (s *ss) getRune() (r rune) {
r, _, err := s.ReadRune()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
return eof
}
s.error(err)
return
}
-func (s *ss) UnreadRune() os.Error {
+func (s *ss) UnreadRune() error {
if u, ok := s.rr.(runeUnreader); ok {
u.UnreadRune()
} else {
return nil
}
-func (s *ss) error(err os.Error) {
+func (s *ss) error(err error) {
panic(scanError{err})
}
func (s *ss) errorString(err string) {
- panic(scanError{os.NewError(err)})
+ panic(scanError{errors.New(err)})
}
-func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err os.Error) {
+func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err error) {
defer func() {
if e := recover(); e != nil {
if se, ok := e.(scanError); ok {
// readByte returns the next byte from the input, which may be
// left over from a previous read if the UTF-8 was ill-formed.
-func (r *readRune) readByte() (b byte, err os.Error) {
+func (r *readRune) readByte() (b byte, err error) {
if r.pending > 0 {
b = r.pendBuf[0]
copy(r.pendBuf[0:], r.pendBuf[1:])
// ReadRune returns the next UTF-8 encoded code point from the
// io.Reader inside r.
-func (r *readRune) ReadRune() (rr rune, size int, err os.Error) {
+func (r *readRune) ReadRune() (rr rune, size int, err error) {
r.buf[0], err = r.readByte()
if err != nil {
return 0, 0, err
for n = 1; !utf8.FullRune(r.buf[0:n]); n++ {
r.buf[n], err = r.readByte()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = nil
break
}
s.errorString("expected field of type pointer to " + expected + "; found " + reflect.TypeOf(field).String())
}
-var complexError = os.NewError("syntax error scanning complex number")
-var boolError = os.NewError("syntax error scanning boolean")
+var complexError = errors.New("syntax error scanning complex number")
+var boolError = errors.New("syntax error scanning boolean")
// consume reads the next rune in the input and reports whether it is in the ok string.
// If accept is true, it puts the character into the input token.
func (s *ss) notEOF() {
// Guarantee there is data to be read.
if r := s.getRune(); r == eof {
- panic(os.EOF)
+ panic(io.EOF)
}
s.UnreadRune()
}
// scanOne scans a single value, deriving the scanner from the type of the argument.
func (s *ss) scanOne(verb rune, field interface{}) {
s.buf.Reset()
- var err os.Error
+ var err error
// If the parameter has its own Scan method, use that.
if v, ok := field.(Scanner); ok {
err = v.Scan(s, verb)
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
s.error(err)
}
// errorHandler turns local panics into error returns.
-func errorHandler(errp *os.Error) {
+func errorHandler(errp *error) {
if e := recover(); e != nil {
if se, ok := e.(scanError); ok { // catch local error
*errp = se.err
- } else if eof, ok := e.(os.Error); ok && eof == os.EOF { // out of input
+ } else if eof, ok := e.(error); ok && eof == io.EOF { // out of input
*errp = eof
} else {
panic(e)
}
// doScan does the real work for scanning without a format string.
-func (s *ss) doScan(a []interface{}) (numProcessed int, err os.Error) {
+func (s *ss) doScan(a []interface{}) (numProcessed int, err error) {
defer errorHandler(&err)
for _, field := range a {
s.scanOne('v', field)
// doScanf does the real work when scanning with a format string.
// At the moment, it handles only pointers to basic types.
-func (s *ss) doScanf(format string, a []interface{}) (numProcessed int, err os.Error) {
+func (s *ss) doScanf(format string, a []interface{}) (numProcessed int, err error) {
defer errorHandler(&err)
end := len(format) - 1
// We process one item per non-trivial format
import (
"bufio"
"bytes"
+ "errors"
. "fmt"
"io"
"math"
- "os"
"reflect"
"regexp"
"strings"
// Xs accepts any non-empty run of the verb character
type Xs string
-func (x *Xs) Scan(state ScanState, verb rune) os.Error {
+func (x *Xs) Scan(state ScanState, verb rune) error {
tok, err := state.Token(true, func(r rune) bool { return r == verb })
if err != nil {
return err
}
s := string(tok)
if !regexp.MustCompile("^" + string(verb) + "+$").MatchString(s) {
- return os.NewError("syntax error for xs")
+ return errors.New("syntax error for xs")
}
*x = Xs(s)
return nil
s string
}
-func (s *IntString) Scan(state ScanState, verb rune) os.Error {
+func (s *IntString) Scan(state ScanState, verb rune) error {
if _, err := Fscan(state, &s.i); err != nil {
return err
}
r *strings.Reader
}
-func (s *myStringReader) Read(p []byte) (n int, err os.Error) {
+func (s *myStringReader) Read(p []byte) (n int, err error) {
return s.r.Read(p)
}
{"%c%c%c", "\xc2X\xc2", args(&i, &j, &k), args(utf8.RuneError, 'X', utf8.RuneError), ""},
}
-func testScan(name string, t *testing.T, scan func(r io.Reader, a ...interface{}) (int, os.Error)) {
+func testScan(name string, t *testing.T, scan func(r io.Reader, a ...interface{}) (int, error)) {
for _, test := range scanTests {
var r io.Reader
if name == "StringReader" {
t.Errorf("expected overflow scanning %q", test.text)
continue
}
- if !re.MatchString(err.String()) {
+ if !re.MatchString(err.Error()) {
t.Errorf("expected overflow error scanning %q: %s", test.text, err)
}
}
if err != nil {
if test.err == "" {
t.Errorf("got error scanning (%q, %q): %q", test.format, test.text, err)
- } else if strings.Index(err.String(), test.err) < 0 {
+ } else if strings.Index(err.Error(), test.err) < 0 {
t.Errorf("got wrong error scanning (%q, %q): %q; expected %q", test.format, test.text, err, test.err)
}
continue
_, err := Fscan(r, a)
if err == nil {
t.Error("expected error scanning non-pointer")
- } else if strings.Index(err.String(), "pointer") < 0 {
+ } else if strings.Index(err.Error(), "pointer") < 0 {
t.Errorf("expected pointer error scanning non-pointer, got: %s", err)
}
}
_, err := Sscanln("1 x\n", &a)
if err == nil {
t.Error("expected error scanning string missing newline")
- } else if strings.Index(err.String(), "newline") < 0 {
+ } else if strings.Index(err.Error(), "newline") < 0 {
t.Errorf("expected newline error scanning string missing newline, got: %s", err)
}
}
_, err := Fscanln(r, &a, &b)
if err == nil {
t.Error("expected error scanning string with extra newline")
- } else if strings.Index(err.String(), "newline") < 0 {
+ } else if strings.Index(err.Error(), "newline") < 0 {
t.Errorf("expected newline error scanning string with extra newline, got: %s", err)
}
}
eofCount int
}
-func (ec *eofCounter) Read(b []byte) (n int, err os.Error) {
+func (ec *eofCounter) Read(b []byte) (n int, err error) {
n, err = ec.reader.Read(b)
if n == 0 {
ec.eofCount++
if n != 1 || i != 23 {
t.Errorf("Sscanf expected one value of 23; got %d %d", n, i)
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("Sscanf expected EOF; got %q", err)
}
n, err = Sscan("234", &i, &j)
if n != 1 || i != 234 {
t.Errorf("Sscan expected one value of 234; got %d %d", n, i)
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("Sscan expected EOF; got %q", err)
}
// Trailing space is tougher.
if n != 1 || i != 234 {
t.Errorf("Sscan expected one value of 234; got %d %d", n, i)
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("Sscan expected EOF; got %q", err)
}
}
func TestEOFAllTypes(t *testing.T) {
for i, test := range eofTests {
- if _, err := Sscanf("", test.format, test.v); err != os.EOF {
+ if _, err := Sscanf("", test.format, test.v); err != io.EOF {
t.Errorf("#%d: %s %T not eof on empty string: %s", i, test.format, test.v, err)
}
- if _, err := Sscanf(" ", test.format, test.v); err != os.EOF {
+ if _, err := Sscanf(" ", test.format, test.v); err != io.EOF {
t.Errorf("#%d: %s %T not eof on trailing blanks: %s", i, test.format, test.v, err)
}
}
// Attempt to read two lines into the object. Scanln should prevent this
// because it stops at newline; Scan and Scanf should be fine.
-func (t *TwoLines) Scan(state ScanState, verb rune) os.Error {
+func (t *TwoLines) Scan(state ScanState, verb rune) error {
chars := make([]rune, 0, 100)
for nlCount := 0; nlCount < 2; {
c, _, err := state.ReadRune()
next *RecursiveInt
}
-func (r *RecursiveInt) Scan(state ScanState, verb rune) (err os.Error) {
+func (r *RecursiveInt) Scan(state ScanState, verb rune) (err error) {
_, err = Fscan(state, &r.i)
if err != nil {
return
next := new(RecursiveInt)
_, err = Fscanf(state, ".%v", next)
if err != nil {
- if err == os.NewError("input does not match format") || err == io.ErrUnexpectedEOF {
+ if err == errors.New("input does not match format") || err == io.ErrUnexpectedEOF {
err = nil
}
return
// Perform the same scanning task as RecursiveInt.Scan
// but without recurring through scanner, so we can compare
// performance more directly.
-func scanInts(r *RecursiveInt, b *bytes.Buffer) (err os.Error) {
+func scanInts(r *RecursiveInt, b *bytes.Buffer) (err error) {
r.next = nil
_, err = Fscan(b, &r.i)
if err != nil {
}
c, _, err := b.ReadRune()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = nil
}
return
func TestScanInts(t *testing.T) {
testScanInts(t, scanInts)
- testScanInts(t, func(r *RecursiveInt, b *bytes.Buffer) (err os.Error) {
+ testScanInts(t, func(r *RecursiveInt, b *bytes.Buffer) (err error) {
_, err = Fscan(b, r)
return
})
// platform that does not support split stack.
const intCount = 800
-func testScanInts(t *testing.T, scan func(*RecursiveInt, *bytes.Buffer) os.Error) {
+func testScanInts(t *testing.T, scan func(*RecursiveInt, *bytes.Buffer) error) {
r := new(RecursiveInt)
ints := makeInts(intCount)
buf := bytes.NewBuffer(ints)
// struct fields for which f(fieldname, fieldvalue) is true are
// are printed; all others are filtered from the output.
//
-func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) (n int, err os.Error) {
+func Fprint(w io.Writer, fset *token.FileSet, x interface{}, f FieldFilter) (n int, err error) {
// setup printer
p := printer{
output: w,
// Print prints x to standard output, skipping nil fields.
// Print(fset, x) is the same as Fprint(os.Stdout, fset, x, NotNilFilter).
-func Print(fset *token.FileSet, x interface{}) (int, os.Error) {
+func Print(fset *token.FileSet, x interface{}) (int, error) {
return Fprint(os.Stdout, fset, x, NotNilFilter)
}
var indent = []byte(". ")
-func (p *printer) Write(data []byte) (n int, err os.Error) {
+func (p *printer) Write(data []byte) (n int, err error) {
var m int
for i, b := range data {
// invariant: data[0:n] has been written
return
}
-// localError wraps locally caught os.Errors so we can distinguish
+// localError wraps locally caught errors so we can distinguish
// them from genuine panics which we don't want to return as errors.
type localError struct {
- err os.Error
+ err error
}
// printf is a convenience wrapper that takes care of print errors.
"fmt"
"go/scanner"
"go/token"
- "os"
"strconv"
)
// Importer should load the package data for the given path into
// a new *Object (pkg), record pkg in the imports map, and then
// return pkg.
-type Importer func(imports map[string]*Object, path string) (pkg *Object, err os.Error)
+type Importer func(imports map[string]*Object, path string) (pkg *Object, err error)
// NewPackage creates a new Package node from a set of File nodes. It resolves
// unresolved identifiers across files and updates each file's Unresolved list
// different package names are reported and then ignored.
// The result is a package node and a scanner.ErrorList if there were errors.
//
-func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, os.Error) {
+func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) {
var p pkgBuilder
p.fset = fset
import (
"bytes"
+ "errors"
"exec"
"fmt"
"os"
)
// Build produces a build Script for the given package.
-func Build(tree *Tree, pkg string, info *DirInfo) (*Script, os.Error) {
+func Build(tree *Tree, pkg string, info *DirInfo) (*Script, error) {
s := &Script{}
b := &build{
script: s,
if g := os.Getenv("GOARCH"); g != "" {
b.goarch = g
}
- var err os.Error
+ var err error
b.arch, err = ArchChar(b.goarch)
if err != nil {
return nil, err
// FindTree should always be able to suggest an import
// path and tree. The path must be malformed
// (for example, an absolute or relative path).
- return nil, os.NewError("build: invalid import: " + pkg)
+ return nil, errors.New("build: invalid import: " + pkg)
}
s.addInput(filepath.Join(t.PkgDir(), p+".a"))
}
}
if len(ofiles) == 0 {
- return nil, os.NewError("make: no object files to build")
+ return nil, errors.New("make: no object files to build")
}
// choose target file
}
// Run runs the Script's Cmds in order.
-func (s *Script) Run() os.Error {
+func (s *Script) Run() error {
for _, c := range s.Cmd {
if err := c.Run(); err != nil {
return err
// Clean removes the Script's Intermediate files.
// It tries to remove every file and returns the first error it encounters.
-func (s *Script) Clean() (err os.Error) {
+func (s *Script) Clean() (err error) {
// Reverse order so that directories get removed after the files they contain.
for i := len(s.Intermediate) - 1; i >= 0; i-- {
if e := os.Remove(s.Intermediate[i]); err == nil {
// Nuke removes the Script's Intermediate and Output files.
// It tries to remove every file and returns the first error it encounters.
-func (s *Script) Nuke() (err os.Error) {
+func (s *Script) Nuke() (err error) {
// Reverse order so that directories get removed after the files they contain.
for i := len(s.Output) - 1; i >= 0; i-- {
if e := os.Remove(s.Output[i]); err == nil {
}
// Run executes the Cmd.
-func (c *Cmd) Run() os.Error {
+func (c *Cmd) Run() error {
if c.Args[0] == "mkdir" {
for _, p := range c.Output {
if err := os.MkdirAll(p, 0777); err != nil {
// ArchChar returns the architecture character for the given goarch.
// For example, ArchChar("amd64") returns "6".
-func ArchChar(goarch string) (string, os.Error) {
+func ArchChar(goarch string) (string, error) {
switch goarch {
case "386":
return "8", nil
case "arm":
return "5", nil
}
- return "", os.NewError("unsupported GOARCH " + goarch)
+ return "", errors.New("unsupported GOARCH " + goarch)
}
type build struct {
import (
"bytes"
+ "errors"
"fmt"
"go/ast"
"go/doc"
// describing the content of the named directory.
// The dir argument is the argument to ScanDir.
// If ReadDir is nil, ScanDir uses io.ReadDir.
- ReadDir func(dir string) (fi []*os.FileInfo, err os.Error)
+ ReadDir func(dir string) (fi []*os.FileInfo, err error)
// ReadFile returns the content of the file named file
// in the directory named dir. The dir argument is the
//
// If ReadFile is nil, ScanDir uses filepath.Join(dir, file)
// as the path and ioutil.ReadFile to read the data.
- ReadFile func(dir, file string) (path string, content []byte, err os.Error)
+ ReadFile func(dir, file string) (path string, content []byte, err error)
}
-func (ctxt *Context) readDir(dir string) ([]*os.FileInfo, os.Error) {
+func (ctxt *Context) readDir(dir string) ([]*os.FileInfo, error) {
if f := ctxt.ReadDir; f != nil {
return f(dir)
}
return ioutil.ReadDir(dir)
}
-func (ctxt *Context) readFile(dir, file string) (string, []byte, os.Error) {
+func (ctxt *Context) readFile(dir, file string) (string, []byte, error) {
if f := ctxt.ReadFile; f != nil {
return f(dir, file)
}
}
// ScanDir calls DefaultContext.ScanDir.
-func ScanDir(dir string) (info *DirInfo, err os.Error) {
+func ScanDir(dir string) (info *DirInfo, err error) {
return DefaultContext.ScanDir(dir)
}
// - files ending in _test.go
// - files starting with _ or .
//
-func (ctxt *Context) ScanDir(dir string) (info *DirInfo, err os.Error) {
+func (ctxt *Context) ScanDir(dir string) (info *DirInfo, err error) {
dirs, err := ctxt.readDir(dir)
if err != nil {
return nil, err
//
// TODO(rsc): This duplicates code in cgo.
// Once the dust settles, remove this code from cgo.
-func (ctxt *Context) saveCgo(filename string, di *DirInfo, cg *ast.CommentGroup) os.Error {
+func (ctxt *Context) saveCgo(filename string, di *DirInfo, cg *ast.CommentGroup) error {
text := doc.CommentText(cg)
for _, line := range strings.Split(text, "\n") {
orig := line
//
// []string{"a", "b:c d", "ef", `g"`}
//
-func splitQuoted(s string) (r []string, err os.Error) {
+func splitQuoted(s string) (r []string, err error) {
var args []string
arg := make([]rune, len(s))
escaped := false
args = append(args, string(arg[:i]))
}
if quote != 0 {
- err = os.NewError("unclosed quote")
+ err = errors.New("unclosed quote")
} else if escaped {
- err = os.NewError("unfinished escaping")
+ err = errors.New("unfinished escaping")
}
return args, err
}
package build
import (
+ "errors"
"fmt"
"log"
"os"
Goroot bool
}
-func newTree(p string) (*Tree, os.Error) {
+func newTree(p string) (*Tree, error) {
if !filepath.IsAbs(p) {
- return nil, os.NewError("must be absolute")
+ return nil, errors.New("must be absolute")
}
ep, err := filepath.EvalSymlinks(p)
if err != nil {
}
var (
- ErrNotFound = os.NewError("go/build: package could not be found locally")
- ErrTreeNotFound = os.NewError("go/build: no valid GOROOT or GOPATH could be found")
+ ErrNotFound = errors.New("go/build: package could not be found locally")
+ ErrTreeNotFound = errors.New("go/build: no valid GOROOT or GOPATH could be found")
)
// FindTree takes an import or filesystem path and returns the
// tree where the package source should be and the package import path.
-func FindTree(path string) (tree *Tree, pkg string, err os.Error) {
+func FindTree(path string) (tree *Tree, pkg string, err error) {
if isLocalPath(path) {
if path, err = filepath.Abs(path); err != nil {
return
import (
"bytes"
+ "errors"
"go/ast"
"go/scanner"
"go/token"
// otherwise it returns an error. If src == nil, readSource returns
// the result of reading the file specified by filename.
//
-func readSource(filename string, src interface{}) ([]byte, os.Error) {
+func readSource(filename string, src interface{}) ([]byte, error) {
if src != nil {
switch s := src.(type) {
case string:
}
return buf.Bytes(), nil
default:
- return nil, os.NewError("invalid source")
+ return nil, errors.New("invalid source")
}
}
return ioutil.ReadFile(filename)
}
-func (p *parser) errors() os.Error {
+func (p *parser) errors() error {
mode := scanner.Sorted
if p.mode&SpuriousErrors == 0 {
mode = scanner.NoMultiples
// as for ParseFile. If there is an error, the result expression
// may be nil or contain a partial AST.
//
-func ParseExpr(fset *token.FileSet, filename string, src interface{}) (ast.Expr, os.Error) {
+func ParseExpr(fset *token.FileSet, filename string, src interface{}) (ast.Expr, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
// interpretation as for ParseFile. If there is an error, the node
// list may be nil or contain partial ASTs.
//
-func ParseStmtList(fset *token.FileSet, filename string, src interface{}) ([]ast.Stmt, os.Error) {
+func ParseStmtList(fset *token.FileSet, filename string, src interface{}) ([]ast.Stmt, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
// interpretation as for ParseFile. If there is an error, the node
// list may be nil or contain partial ASTs.
//
-func ParseDeclList(fset *token.FileSet, filename string, src interface{}) ([]ast.Decl, os.Error) {
+func ParseDeclList(fset *token.FileSet, filename string, src interface{}) ([]ast.Decl, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
// representing the fragments of erroneous source code). Multiple errors
// are returned via a scanner.ErrorList which is sorted by file position.
//
-func ParseFile(fset *token.FileSet, filename string, src interface{}, mode uint) (*ast.File, os.Error) {
+func ParseFile(fset *token.FileSet, filename string, src interface{}, mode uint) (*ast.File, error) {
data, err := readSource(filename, src)
if err != nil {
return nil, err
// be incomplete (missing packages and/or incomplete packages) and the first
// error encountered is returned.
//
-func ParseFiles(fset *token.FileSet, filenames []string, mode uint) (pkgs map[string]*ast.Package, first os.Error) {
+func ParseFiles(fset *token.FileSet, filenames []string, mode uint) (pkgs map[string]*ast.Package, first error) {
pkgs = make(map[string]*ast.Package)
for _, filename := range filenames {
if src, err := ParseFile(fset, filename, nil, mode); err == nil {
// returned. If a parse error occurred, a non-nil but incomplete map and the
// error are returned.
//
-func ParseDir(fset *token.FileSet, path string, filter func(*os.FileInfo) bool, mode uint) (map[string]*ast.Package, os.Error) {
+func ParseDir(fset *token.FileSet, path string, filter func(*os.FileInfo) bool, mode uint) (map[string]*ast.Package, error) {
fd, err := os.Open(path)
if err != nil {
return nil, err
noExtraLinebreak
)
-// local error wrapper so we can distinguish os.Errors we want to return
+// local error wrapper so we can distinguish errors we want to return
// as errors from genuine panics (which we don't want to return as errors)
type osError struct {
- err os.Error
+ err error
}
type printer struct {
// However, this would mess up any formatting done by
// the tabwriter.
-func (p *trimmer) Write(data []byte) (n int, err os.Error) {
+func (p *trimmer) Write(data []byte) (n int, err error) {
// invariants:
// p.state == inSpace:
// p.space is unwritten
}
// fprint implements Fprint and takes a nodesSizes map for setting up the printer state.
-func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (written int, err os.Error) {
+func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (written int, err error) {
// redirect output through a trimmer to eliminate trailing whitespace
// (Input to a tabwriter must be untrimmed since trailing tabs provide
// formatting information. The tabwriter could provide trimming
// The node type must be *ast.File, or assignment-compatible to ast.Expr,
// ast.Decl, ast.Spec, or ast.Stmt.
//
-func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) (int, os.Error) {
+func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) (int, error) {
return cfg.fprint(output, fset, node, make(map[ast.Node]int))
}
// Fprint "pretty-prints" an AST node to output.
// It calls Config.Fprint with default settings.
//
-func Fprint(output io.Writer, fset *token.FileSet, node interface{}) os.Error {
+func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error {
_, err := (&Config{Tabwidth: 8}).Fprint(output, fset, node) // don't care about number of bytes written
return err
}
"fmt"
"go/token"
"io"
- "os"
"sort"
)
Msg string
}
-func (e *Error) String() string {
+func (e *Error) Error() string {
if e.Pos.Filename != "" || e.Pos.IsValid() {
// don't print "<unknown position>"
// TODO(gri) reconsider the semantics of Position.IsValid
return false
}
-func (p ErrorList) String() string {
+func (p ErrorList) Error() string {
switch len(p) {
case 0:
return "unspecified error"
case 1:
- return p[0].String()
+ return p[0].Error()
}
return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1)
}
return list
}
-// GetError is like GetErrorList, but it returns an os.Error instead
-// so that a nil result can be assigned to an os.Error variable and
+// GetError is like GetErrorList, but it returns an error instead
+// so that a nil result can be assigned to an error variable and
// remains nil.
//
-func (h *ErrorVector) GetError(mode int) os.Error {
+func (h *ErrorVector) GetError(mode int) error {
if len(h.errors) == 0 {
return nil
}
// one error per line, if the err parameter is an ErrorList. Otherwise
// it prints the err string.
//
-func PrintError(w io.Writer, err os.Error) {
+func PrintError(w io.Writer, err error) {
if list, ok := err.(ErrorList); ok {
for _, e := range list {
fmt.Fprintf(w, "%s\n", e)
import (
"gob"
"io"
- "os"
)
type serializedFile struct {
Files []serializedFile
}
-func (s *serializedFileSet) Read(r io.Reader) os.Error {
+func (s *serializedFileSet) Read(r io.Reader) error {
return gob.NewDecoder(r).Decode(s)
}
-func (s *serializedFileSet) Write(w io.Writer) os.Error {
+func (s *serializedFileSet) Write(w io.Writer) error {
return gob.NewEncoder(w).Encode(s)
}
// Read reads the fileset from r into s; s must not be nil.
// If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.
-func (s *FileSet) Read(r io.Reader) os.Error {
+func (s *FileSet) Read(r io.Reader) error {
var ss serializedFileSet
if err := ss.Read(r); err != nil {
return err
}
// Write writes the fileset s to w.
-func (s *FileSet) Write(w io.Writer) os.Error {
+func (s *FileSet) Write(w io.Writer) error {
var ss serializedFileSet
s.mutex.Lock()
import (
"bytes"
"fmt"
- "os"
"testing"
)
// equal returns nil if p and q describe the same file set;
// otherwise it returns an error describing the discrepancy.
-func equal(p, q *FileSet) os.Error {
+func equal(p, q *FileSet) error {
if p == q {
// avoid deadlock if p == q
return nil
import (
"bytes"
+ "errors"
"math"
- "os"
"reflect"
"strings"
"testing"
// Test instruction execution for decoding.
// Do not run the machine yet; instead do individual instructions crafted by hand.
func TestScalarDecInstructions(t *testing.T) {
- ovfl := os.NewError("overflow")
+ ovfl := errors.New("overflow")
// bool
{
Minc complex128
}
var it inputT
- var err os.Error
+ var err error
b := new(bytes.Buffer)
enc := NewEncoder(b)
dec := NewDecoder(b)
var o1 outi8
enc.Encode(it)
err = dec.Decode(&o1)
- if err == nil || err.String() != `value for "Maxi" out of range` {
+ if err == nil || err.Error() != `value for "Maxi" out of range` {
t.Error("wrong overflow error for int8:", err)
}
it = inputT{
b.Reset()
enc.Encode(it)
err = dec.Decode(&o1)
- if err == nil || err.String() != `value for "Mini" out of range` {
+ if err == nil || err.Error() != `value for "Mini" out of range` {
t.Error("wrong underflow error for int8:", err)
}
var o2 outi16
enc.Encode(it)
err = dec.Decode(&o2)
- if err == nil || err.String() != `value for "Maxi" out of range` {
+ if err == nil || err.Error() != `value for "Maxi" out of range` {
t.Error("wrong overflow error for int16:", err)
}
it = inputT{
b.Reset()
enc.Encode(it)
err = dec.Decode(&o2)
- if err == nil || err.String() != `value for "Mini" out of range` {
+ if err == nil || err.Error() != `value for "Mini" out of range` {
t.Error("wrong underflow error for int16:", err)
}
var o3 outi32
enc.Encode(it)
err = dec.Decode(&o3)
- if err == nil || err.String() != `value for "Maxi" out of range` {
+ if err == nil || err.Error() != `value for "Maxi" out of range` {
t.Error("wrong overflow error for int32:", err)
}
it = inputT{
b.Reset()
enc.Encode(it)
err = dec.Decode(&o3)
- if err == nil || err.String() != `value for "Mini" out of range` {
+ if err == nil || err.Error() != `value for "Mini" out of range` {
t.Error("wrong underflow error for int32:", err)
}
var o4 outu8
enc.Encode(it)
err = dec.Decode(&o4)
- if err == nil || err.String() != `value for "Maxu" out of range` {
+ if err == nil || err.Error() != `value for "Maxu" out of range` {
t.Error("wrong overflow error for uint8:", err)
}
var o5 outu16
enc.Encode(it)
err = dec.Decode(&o5)
- if err == nil || err.String() != `value for "Maxu" out of range` {
+ if err == nil || err.Error() != `value for "Maxu" out of range` {
t.Error("wrong overflow error for uint16:", err)
}
var o6 outu32
enc.Encode(it)
err = dec.Decode(&o6)
- if err == nil || err.String() != `value for "Maxu" out of range` {
+ if err == nil || err.Error() != `value for "Maxu" out of range` {
t.Error("wrong overflow error for uint32:", err)
}
var o7 outf32
enc.Encode(it)
err = dec.Decode(&o7)
- if err == nil || err.String() != `value for "Maxf" out of range` {
+ if err == nil || err.Error() != `value for "Maxf" out of range` {
t.Error("wrong overflow error for float32:", err)
}
var o8 outc64
enc.Encode(it)
err = dec.Decode(&o8)
- if err == nil || err.String() != `value for "Maxc" out of range` {
+ if err == nil || err.Error() != `value for "Maxc" out of range` {
t.Error("wrong overflow error for complex64:", err)
}
}
err := NewEncoder(b).Encode(&rec)
if err == nil {
t.Error("expected error; got none")
- } else if strings.Index(err.String(), "recursive") < 0 {
+ } else if strings.Index(err.Error(), "recursive") < 0 {
t.Error("expected recursive type error; got", err)
}
// Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
dummyEncoder.encode(b, reflect.ValueOf(&bad0), userType(reflect.TypeOf(&bad0)))
if err := dummyEncoder.err; err == nil {
t.Error("expected error; got none")
- } else if strings.Index(err.String(), "type") < 0 {
+ } else if strings.Index(err.Error(), "type") < 0 {
t.Error("expected type error; got", err)
}
}
import (
"bytes"
+ "errors"
"io"
"math"
- "os"
"reflect"
"unsafe"
)
var (
- errBadUint = os.NewError("gob: encoded unsigned integer out of range")
- errBadType = os.NewError("gob: unknown type id or corrupted data")
- errRange = os.NewError("gob: bad data: field numbers out of bounds")
+ errBadUint = errors.New("gob: encoded unsigned integer out of range")
+ errBadType = errors.New("gob: unknown type id or corrupted data")
+ errRange = errors.New("gob: bad data: field numbers out of bounds")
)
// decoderState is the execution state of an instance of the decoder. A new state
dec.freeList = d
}
-func overflow(name string) os.Error {
- return os.NewError(`value for "` + name + `" out of range`)
+func overflow(name string) error {
+ return errors.New(`value for "` + name + `" out of range`)
}
// decodeUintReader reads an encoded unsigned integer from an io.Reader.
// Used only by the Decoder to read the message length.
-func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err os.Error) {
+func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error) {
width = 1
_, err = r.Read(buf[0:width])
if err != nil {
}
width, err = io.ReadFull(r, buf[0:n])
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return
func (state *decoderState) decodeUint() (x uint64) {
b, err := state.b.ReadByte()
if err != nil {
- error(err)
+ error_(err)
}
if b <= 0x7f {
return uint64(b)
}
n := -int(int8(b))
if n > uint64Size {
- error(errBadUint)
+ error_(errBadUint)
}
width, err := state.b.Read(state.buf[0:n])
if err != nil {
- error(err)
+ error_(err)
}
// Don't need to check error; it's safe to loop regardless.
// Could check that the high byte is zero but it's not worth it.
// The 'instructions' of the decoding machine
type decInstr struct {
op decOp
- field int // field number of the wire type
- indir int // how many pointer indirections to reach the value in the struct
- offset uintptr // offset in the structure of the field to encode
- ovfl os.Error // error message for overflow/underflow (for arrays, of the elements)
+ field int // field number of the wire type
+ indir int // how many pointer indirections to reach the value in the struct
+ offset uintptr // offset in the structure of the field to encode
+ ovfl error // error message for overflow/underflow (for arrays, of the elements)
}
// Since the encoder writes no zeros, if we arrive at a decoder we have
}
v := state.decodeInt()
if v < math.MinInt8 || math.MaxInt8 < v {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*int8)(p) = int8(v)
}
}
v := state.decodeUint()
if math.MaxUint8 < v {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*uint8)(p) = uint8(v)
}
}
v := state.decodeInt()
if v < math.MinInt16 || math.MaxInt16 < v {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*int16)(p) = int16(v)
}
}
v := state.decodeUint()
if math.MaxUint16 < v {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*uint16)(p) = uint16(v)
}
}
v := state.decodeInt()
if v < math.MinInt32 || math.MaxInt32 < v {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*int32)(p) = int32(v)
}
}
v := state.decodeUint()
if math.MaxUint32 < v {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*uint32)(p) = uint32(v)
}
}
// +Inf is OK in both 32- and 64-bit floats. Underflow is always OK.
if math.MaxFloat32 < av && av <= math.MaxFloat64 {
- error(i.ovfl)
+ error_(i.ovfl)
} else {
*(*float32)(p) = float32(v)
}
// decodeSingle decodes a top-level value that is not a struct and stores it through p.
// Such values are preceded by a zero, making them have the memory layout of a
// struct field (although with an illegal field number).
-func (dec *Decoder) decodeSingle(engine *decEngine, ut *userTypeInfo, basep uintptr) (err os.Error) {
+func (dec *Decoder) decodeSingle(engine *decEngine, ut *userTypeInfo, basep uintptr) (err error) {
state := dec.newDecoderState(&dec.buf)
state.fieldnum = singletonField
delta := int(state.decodeUint())
}
instr := &engine.instr[singletonField]
if instr.indir != ut.indir {
- return os.NewError("gob: internal error: inconsistent indirection")
+ return errors.New("gob: internal error: inconsistent indirection")
}
ptr := unsafe.Pointer(basep) // offset will be zero
if instr.indir > 1 {
}
fieldnum := state.fieldnum + delta
if fieldnum >= len(engine.instr) {
- error(errRange)
+ error_(errRange)
break
}
instr := &engine.instr[fieldnum]
}
fieldnum := state.fieldnum + delta
if fieldnum >= len(engine.instr) {
- error(errRange)
+ error_(errRange)
}
instr := &engine.instr[fieldnum]
instr.op(instr, state, unsafe.Pointer(nil))
}
// decodeArrayHelper does the work for decoding arrays and slices.
-func (dec *Decoder) decodeArrayHelper(state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, elemIndir int, ovfl os.Error) {
+func (dec *Decoder) decodeArrayHelper(state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, elemIndir int, ovfl error) {
instr := &decInstr{elemOp, 0, elemIndir, 0, ovfl}
for i := 0; i < length; i++ {
up := unsafe.Pointer(p)
// decodeArray decodes an array and stores it through p, that is, p points to the zeroth element.
// The length is an unsigned integer preceding the elements. Even though the length is redundant
// (it's part of the type), it's a useful check and is included in the encoding.
-func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, indir, elemIndir int, ovfl os.Error) {
+func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, indir, elemIndir int, ovfl error) {
if indir > 0 {
p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect
}
// decodeIntoValue is a helper for map decoding. Since maps are decoded using reflection,
// unlike the other items we can't use a pointer directly.
-func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value, ovfl os.Error) reflect.Value {
+func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value, ovfl error) reflect.Value {
instr := &decInstr{op, 0, indir, 0, ovfl}
up := unsafe.Pointer(unsafeAddr(v))
if indir > 1 {
// Maps are encoded as a length followed by key:value pairs.
// Because the internals of maps are not visible to us, we must
// use reflection rather than pointer magic.
-func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, p uintptr, keyOp, elemOp decOp, indir, keyIndir, elemIndir int, ovfl os.Error) {
+func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, p uintptr, keyOp, elemOp decOp, indir, keyIndir, elemIndir int, ovfl error) {
if indir > 0 {
p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect
}
// ignoreArrayHelper does the work for discarding arrays and slices.
func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) {
- instr := &decInstr{elemOp, 0, 0, 0, os.NewError("no error")}
+ instr := &decInstr{elemOp, 0, 0, 0, errors.New("no error")}
for i := 0; i < length; i++ {
elemOp(instr, state, nil)
}
// ignoreMap discards the data for a map value with no destination.
func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
n := int(state.decodeUint())
- keyInstr := &decInstr{keyOp, 0, 0, 0, os.NewError("no error")}
- elemInstr := &decInstr{elemOp, 0, 0, 0, os.NewError("no error")}
+ keyInstr := &decInstr{keyOp, 0, 0, 0, errors.New("no error")}
+ elemInstr := &decInstr{elemOp, 0, 0, 0, errors.New("no error")}
for i := 0; i < n; i++ {
keyOp(keyInstr, state, nil)
elemOp(elemInstr, state, nil)
// decodeSlice decodes a slice and stores the slice header through p.
// Slices are encoded as an unsigned length followed by the elements.
-func (dec *Decoder) decodeSlice(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl os.Error) {
+func (dec *Decoder) decodeSlice(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl error) {
n := int(uintptr(state.decodeUint()))
if indir > 0 {
up := unsafe.Pointer(p)
// Read the type id of the concrete value.
concreteId := dec.decodeTypeSequence(true)
if concreteId < 0 {
- error(dec.err)
+ error_(dec.err)
}
// Byte count of value is next; we don't care what it is (it's there
// in case we want to ignore the value by skipping it completely).
value := allocValue(typ)
dec.decodeValue(concreteId, value)
if dec.err != nil {
- error(dec.err)
+ error_(dec.err)
}
// Allocate the destination interface value.
if indir > 0 {
b := make([]byte, state.decodeUint())
_, err := state.b.Read(b)
if err != nil {
- error(err)
+ error_(err)
}
id := dec.decodeTypeSequence(true)
if id < 0 {
- error(dec.err)
+ error_(dec.err)
}
// At this point, the decoder buffer contains a delimited value. Just toss it.
state.b.Next(int(state.decodeUint()))
b := make([]byte, state.decodeUint())
_, err := state.b.Read(b)
if err != nil {
- error(err)
+ error_(err)
}
// We know it's a GobDecoder, so just call the method directly.
err = v.Interface().(GobDecoder).GobDecode(b)
if err != nil {
- error(err)
+ error_(err)
}
}
b := make([]byte, state.decodeUint())
_, err := state.b.Read(b)
if err != nil {
- error(err)
+ error_(err)
}
}
// Generate a closure that calls out to the engine for the nested type.
enginePtr, err := dec.getDecEnginePtr(wireId, userType(typ))
if err != nil {
- error(err)
+ error_(err)
}
op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
// indirect through enginePtr to delay evaluation for recursive structs.
// Generate a closure that calls out to the engine for the nested type.
enginePtr, err := dec.getIgnoreEnginePtr(wireId)
if err != nil {
- error(err)
+ error_(err)
}
op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
// indirect through enginePtr to delay evaluation for recursive structs
// compileSingle compiles the decoder engine for a non-struct top-level value, including
// GobDecoders.
-func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err os.Error) {
+func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
rt := ut.user
engine = new(decEngine)
engine.instr = make([]decInstr, 1) // one item
name := rt.String() // best we can do
if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
- return nil, os.NewError("gob: wrong type received for local value " + name + ": " + dec.typeString(remoteId))
+ return nil, errors.New("gob: wrong type received for local value " + name + ": " + dec.typeString(remoteId))
}
op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
- ovfl := os.NewError(`value for "` + name + `" out of range`)
+ ovfl := errors.New(`value for "` + name + `" out of range`)
engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl}
engine.numInstr = 1
return
}
// compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded.
-func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err os.Error) {
+func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) {
engine = new(decEngine)
engine.instr = make([]decInstr, 1) // one item
op := dec.decIgnoreOpFor(remoteId)
// compileDec compiles the decoder engine for a value. If the value is not a struct,
// it calls out to compileSingle.
-func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err os.Error) {
+func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
rt := ut.base
srt := rt
if srt.Kind() != reflect.Struct ||
} else {
wire := dec.wireType[remoteId]
if wire == nil {
- error(errBadType)
+ error_(errBadType)
}
wireStruct = wire.StructT
}
}
// getDecEnginePtr returns the engine for the specified type.
-func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err os.Error) {
+func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) {
rt := ut.base
decoderMap, ok := dec.decoderCache[rt]
if !ok {
var emptyStructType = reflect.TypeOf(emptyStruct{})
// getDecEnginePtr returns the engine for the specified type when the value is to be discarded.
-func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err os.Error) {
+func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) {
var ok bool
if enginePtr, ok = dec.ignorerCache[wireId]; !ok {
// To handle recursive types, mark this engine as underway before compiling.
import (
"bufio"
"bytes"
+ "errors"
"io"
- "os"
"reflect"
"sync"
)
freeList *decoderState // list of free decoderStates; avoids reallocation
countBuf []byte // used for decoding integers while parsing messages
tmp []byte // temporary storage for i/o; saves reallocating
- err os.Error
+ err error
}
// NewDecoder returns a new decoder that reads from the io.Reader.
func (dec *Decoder) recvType(id typeId) {
// Have we already seen this type? That's an error
if id < firstUserId || dec.wireType[id] != nil {
- dec.err = os.NewError("gob: duplicate type received")
+ dec.err = errors.New("gob: duplicate type received")
return
}
dec.wireType[id] = wire
}
-var errBadCount = os.NewError("invalid message length")
+var errBadCount = errors.New("invalid message length")
// recvMessage reads the next count-delimited item from the input. It is the converse
// of Encoder.writeMessage. It returns false on EOF or other error reading the message.
// Read the data
_, dec.err = io.ReadFull(dec.r, dec.tmp)
if dec.err != nil {
- if dec.err == os.EOF {
+ if dec.err == io.EOF {
dec.err = io.ErrUnexpectedEOF
}
return
// will be absorbed by recvMessage.)
if dec.buf.Len() > 0 {
if !isInterface {
- dec.err = os.NewError("extra data in buffer")
+ dec.err = errors.New("extra data in buffer")
break
}
dec.nextUint()
// If e is nil, the value will be discarded. Otherwise,
// the value underlying e must be a pointer to the
// correct type for the next data item received.
-func (dec *Decoder) Decode(e interface{}) os.Error {
+func (dec *Decoder) Decode(e interface{}) error {
if e == nil {
return dec.DecodeValue(reflect.Value{})
}
// If e represents a value as opposed to a pointer, the answer won't
// get back to the caller. Make sure it's a pointer.
if value.Type().Kind() != reflect.Ptr {
- dec.err = os.NewError("gob: attempt to decode into a non-pointer")
+ dec.err = errors.New("gob: attempt to decode into a non-pointer")
return dec.err
}
return dec.DecodeValue(value)
// If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value.
// Otherwise, it stores the value into v. In that case, v must represent
// a non-nil pointer to data or be an assignable reflect.Value (v.CanSet())
-func (dec *Decoder) DecodeValue(v reflect.Value) os.Error {
+func (dec *Decoder) DecodeValue(v reflect.Value) error {
if v.IsValid() {
if v.Kind() == reflect.Ptr && !v.IsNil() {
// That's okay, we'll store through the pointer.
} else if !v.CanSet() {
- return os.NewError("gob: DecodeValue of unassignable value")
+ return errors.New("gob: DecodeValue of unassignable value")
}
}
// Make sure we're single-threaded through here.
if x <= 0x7F {
err := state.b.WriteByte(uint8(x))
if err != nil {
- error(err)
+ error_(err)
}
return
}
state.buf[i] = uint8(i - uint64Size) // = loop count, negated
_, err := state.b.Write(state.buf[i : uint64Size+1])
if err != nil {
- error(err)
+ error_(err)
}
}
state.encodeUint(uint64(len(name)))
_, err := state.b.WriteString(name)
if err != nil {
- error(err)
+ error_(err)
}
// Define the type id if necessary.
enc.sendTypeDescriptor(enc.writer(), state, ut)
data.Write(spaceForLength)
enc.encode(data, iv.Elem(), ut)
if enc.err != nil {
- error(enc.err)
+ error_(enc.err)
}
enc.popWriter()
enc.writeMessage(b, data)
if enc.err != nil {
- error(err)
+ error_(err)
}
enc.freeEncoderState(state)
}
// We know it's a GobEncoder, so just call the method directly.
data, err := v.Interface().(GobEncoder).GobEncode()
if err != nil {
- error(err)
+ error_(err)
}
state := enc.newEncoderState(b)
state.fieldnum = -1
func (enc *Encoder) getEncEngine(ut *userTypeInfo) *encEngine {
info, err1 := getTypeInfo(ut)
if err1 != nil {
- error(err1)
+ error_(err1)
}
if info.encoder == nil {
// mark this engine as underway before compiling to handle recursive types.
import (
"bytes"
+ "errors"
"io"
- "os"
"reflect"
"sync"
)
countState *encoderState // stage for writing counts
freeList *encoderState // list of free encoderStates; avoids reallocation
byteBuf bytes.Buffer // buffer for top-level encoderState
- err os.Error
+ err error
}
// Before we encode a message, we reserve space at the head of the
}
func (enc *Encoder) badType(rt reflect.Type) {
- enc.setError(os.NewError("gob: can't encode type " + rt.String()))
+ enc.setError(errors.New("gob: can't encode type " + rt.String()))
}
-func (enc *Encoder) setError(err os.Error) {
+func (enc *Encoder) setError(err error) {
if enc.err == nil { // remember the first.
enc.err = err
}
// Encode transmits the data item represented by the empty interface value,
// guaranteeing that all necessary type information has been transmitted first.
-func (enc *Encoder) Encode(e interface{}) os.Error {
+func (enc *Encoder) Encode(e interface{}) error {
return enc.EncodeValue(reflect.ValueOf(e))
}
// EncodeValue transmits the data item represented by the reflection value,
// guaranteeing that all necessary type information has been transmitted first.
-func (enc *Encoder) EncodeValue(value reflect.Value) os.Error {
+func (enc *Encoder) EncodeValue(value reflect.Value) error {
// Make sure we're single-threaded through here, so multiple
// goroutines can share an encoder.
enc.mutex.Lock()
"bytes"
"fmt"
"io"
- "os"
"reflect"
"strings"
"testing"
badTypeCheck(new(ET4), true, "different type of field", t)
}
-func corruptDataCheck(s string, err os.Error, t *testing.T) {
+func corruptDataCheck(s string, err error, t *testing.T) {
b := bytes.NewBufferString(s)
dec := NewDecoder(b)
err1 := dec.Decode(new(ET2))
// Check that we survive bad data.
func TestBadData(t *testing.T) {
- corruptDataCheck("", os.EOF, t)
+ corruptDataCheck("", io.EOF, t)
corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t)
corruptDataCheck("\x03now is the time for all good men", errBadType, t)
}
}
}
-func encAndDec(in, out interface{}) os.Error {
+func encAndDec(in, out interface{}) error {
b := new(bytes.Buffer)
enc := NewEncoder(b)
err := enc.Encode(in)
}
t4p := &Type4{3}
var t4 Type4 // note: not a pointer.
- if err := encAndDec(t4p, t4); err == nil || strings.Index(err.String(), "pointer") < 0 {
+ if err := encAndDec(t4p, t4); err == nil || strings.Index(err.Error(), "pointer") < 0 {
t.Error("expected error about pointer; got", err)
}
}
t.Errorf("expected error decoding %v: %s", test.in, test.err)
continue
case err != nil && test.err != "":
- if strings.Index(err.String(), test.err) < 0 {
+ if strings.Index(err.Error(), test.err) < 0 {
t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err)
}
continue
var ns NonStruct
if err := encAndDec(s, &ns); err == nil {
t.Error("should get error for struct/non-struct")
- } else if strings.Index(err.String(), "type") < 0 {
+ } else if strings.Index(err.Error(), "type") < 0 {
t.Error("for struct/non-struct expected type error; got", err)
}
// Now try the other way
}
if err := encAndDec(ns, &s); err == nil {
t.Error("should get error for non-struct/struct")
- } else if strings.Index(err.String(), "type") < 0 {
+ } else if strings.Index(err.Error(), "type") < 0 {
t.Error("for non-struct/struct expected type error; got", err)
}
}
type Bug1StructMap map[string]Bug1Elem
-func bug1EncDec(in Bug1StructMap, out *Bug1StructMap) os.Error {
+func bug1EncDec(in Bug1StructMap, out *Bug1StructMap) error {
return nil
}
b := []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1}
if err := NewDecoder(bytes.NewBuffer(b)).Decode(nil); err == nil {
t.Error("expected error from bad count")
- } else if err.String() != errBadCount.String() {
+ } else if err.Error() != errBadCount.Error() {
t.Error("expected bad count error; got", err)
}
}
package gob
-import (
- "fmt"
- "os"
-)
+import "fmt"
// Errors in decoding and encoding are handled using panic and recover.
// Panics caused by user error (that is, everything except run-time panics
// such as "index out of bounds" errors) do not leave the file that caused
-// them, but are instead turned into plain os.Error returns. Encoding and
-// decoding functions and methods that do not return an os.Error either use
+// them, but are instead turned into plain error returns. Encoding and
+// decoding functions and methods that do not return an error either use
// panic to report an error or are guaranteed error-free.
-// A gobError wraps an os.Error and is used to distinguish errors (panics) generated in this package.
+// A gobError is used to distinguish errors (panics) generated in this package.
type gobError struct {
- err os.Error
+ err error
}
-// errorf is like error but takes Printf-style arguments to construct an os.Error.
+// errorf is like error_ but takes Printf-style arguments to construct an error.
// It always prefixes the message with "gob: ".
func errorf(format string, args ...interface{}) {
- error(fmt.Errorf("gob: "+format, args...))
+ error_(fmt.Errorf("gob: "+format, args...))
}
// error wraps the argument error and uses it as the argument to panic.
-func error(err os.Error) {
+func error_(err error) {
panic(gobError{err})
}
// catchError is meant to be used as a deferred function to turn a panic(gobError) into a
-// plain os.Error. It overwrites the error return of the function that deferred its call.
-func catchError(err *os.Error) {
+// plain error. It overwrites the error return of the function that deferred its call.
+func catchError(err *error) {
if e := recover(); e != nil {
*err = e.(gobError).err // Will re-panic if not one of our errors, such as a runtime error.
}
import (
"bytes"
+ "errors"
"fmt"
- "os"
+ "io"
"strings"
"testing"
)
// The relevant methods
-func (g *ByteStruct) GobEncode() ([]byte, os.Error) {
+func (g *ByteStruct) GobEncode() ([]byte, error) {
b := make([]byte, 3)
b[0] = g.a
b[1] = g.a + 1
return b, nil
}
-func (g *ByteStruct) GobDecode(data []byte) os.Error {
+func (g *ByteStruct) GobDecode(data []byte) error {
if g == nil {
- return os.NewError("NIL RECEIVER")
+ return errors.New("NIL RECEIVER")
}
// Expect N sequential-valued bytes.
if len(data) == 0 {
- return os.EOF
+ return io.EOF
}
g.a = data[0]
for i, c := range data {
if c != g.a+byte(i) {
- return os.NewError("invalid data sequence")
+ return errors.New("invalid data sequence")
}
}
return nil
}
-func (g *StringStruct) GobEncode() ([]byte, os.Error) {
+func (g *StringStruct) GobEncode() ([]byte, error) {
return []byte(g.s), nil
}
-func (g *StringStruct) GobDecode(data []byte) os.Error {
+func (g *StringStruct) GobDecode(data []byte) error {
// Expect N sequential-valued bytes.
if len(data) == 0 {
- return os.EOF
+ return io.EOF
}
a := data[0]
for i, c := range data {
if c != a+byte(i) {
- return os.NewError("invalid data sequence")
+ return errors.New("invalid data sequence")
}
}
g.s = string(data)
return nil
}
-func (a *ArrayStruct) GobEncode() ([]byte, os.Error) {
+func (a *ArrayStruct) GobEncode() ([]byte, error) {
return a.a[:], nil
}
-func (a *ArrayStruct) GobDecode(data []byte) os.Error {
+func (a *ArrayStruct) GobDecode(data []byte) error {
if len(data) != len(a.a) {
- return os.NewError("wrong length in array decode")
+ return errors.New("wrong length in array decode")
}
copy(a.a[:], data)
return nil
}
-func (g *Gobber) GobEncode() ([]byte, os.Error) {
+func (g *Gobber) GobEncode() ([]byte, error) {
return []byte(fmt.Sprintf("VALUE=%d", *g)), nil
}
-func (g *Gobber) GobDecode(data []byte) os.Error {
+func (g *Gobber) GobDecode(data []byte) error {
_, err := fmt.Sscanf(string(data), "VALUE=%d", (*int)(g))
return err
}
-func (v ValueGobber) GobEncode() ([]byte, os.Error) {
+func (v ValueGobber) GobEncode() ([]byte, error) {
return []byte(fmt.Sprintf("VALUE=%s", v)), nil
}
-func (v *ValueGobber) GobDecode(data []byte) os.Error {
+func (v *ValueGobber) GobDecode(data []byte) error {
_, err := fmt.Sscanf(string(data), "VALUE=%s", (*string)(v))
return err
}
if err == nil {
t.Fatal("expected decode error for mismatched fields (encoder to non-decoder)")
}
- if strings.Index(err.String(), "type") < 0 {
+ if strings.Index(err.Error(), "type") < 0 {
t.Fatal("expected type error; got", err)
}
// Non-encoder to GobDecoder: error
if err == nil {
t.Fatal("expected decode error for mismatched fields (non-encoder to decoder)")
}
- if strings.Index(err.String(), "type") < 0 {
+ if strings.Index(err.Error(), "type") < 0 {
t.Fatal("expected type error; got", err)
}
}
return br.foo + "-" + br.bar
}
-func (br *gobDecoderBug0) GobEncode() ([]byte, os.Error) {
+func (br *gobDecoderBug0) GobEncode() ([]byte, error) {
return []byte(br.String()), nil
}
-func (br *gobDecoderBug0) GobDecode(b []byte) os.Error {
+func (br *gobDecoderBug0) GobDecode(b []byte) error {
br.foo = "foo"
br.bar = "bar"
return nil
func BenchmarkEndToEndPipe(b *testing.B) {
r, w, err := os.Pipe()
if err != nil {
- panic("can't get pipe:" + err.String())
+ panic("can't get pipe:" + err.Error())
}
benchmarkEndToEnd(r, w, b)
}
package gob
import (
+ "errors"
"fmt"
"os"
"reflect"
// validType returns, and saves, the information associated with user-provided type rt.
// If the user type is not valid, err will be non-nil. To be used when the error handler
// is not set up.
-func validUserType(rt reflect.Type) (ut *userTypeInfo, err os.Error) {
+func validUserType(rt reflect.Type) (ut *userTypeInfo, err error) {
userTypeLock.RLock()
ut = userTypeCache[rt]
userTypeLock.RUnlock()
ut.base = pt.Elem()
if ut.base == slowpoke { // ut.base lapped slowpoke
// recursive pointer type.
- return nil, os.NewError("can't represent recursive pointer type " + ut.base.String())
+ return nil, errors.New("can't represent recursive pointer type " + ut.base.String())
}
if ut.indir%2 == 0 {
slowpoke = slowpoke.Elem()
func userType(rt reflect.Type) *userTypeInfo {
ut, err := validUserType(rt)
if err != nil {
- error(err)
+ error_(err)
}
return ut
}
// of ut.
// This is only called from the encoding side. The decoding side
// works through typeIds and userTypeInfos alone.
-func newTypeObject(name string, ut *userTypeInfo, rt reflect.Type) (gobType, os.Error) {
+func newTypeObject(name string, ut *userTypeInfo, rt reflect.Type) (gobType, error) {
// Does this type implement GobEncoder?
if ut.isGobEncoder {
return newGobEncoderType(name), nil
}
- var err os.Error
+ var err error
var type0, type1 gobType
defer func() {
if err != nil {
return st, nil
default:
- return nil, os.NewError("gob NewTypeObject can't handle type: " + rt.String())
+ return nil, errors.New("gob NewTypeObject can't handle type: " + rt.String())
}
return nil, nil
}
// getBaseType returns the Gob type describing the given reflect.Type's base type.
// typeLock must be held.
-func getBaseType(name string, rt reflect.Type) (gobType, os.Error) {
+func getBaseType(name string, rt reflect.Type) (gobType, error) {
ut := userType(rt)
return getType(name, ut, ut.base)
}
// which may be pointers. All other types are handled through the
// base type, never a pointer.
// typeLock must be held.
-func getType(name string, ut *userTypeInfo, rt reflect.Type) (gobType, os.Error) {
+func getType(name string, ut *userTypeInfo, rt reflect.Type) (gobType, error) {
typ, present := types[rt]
if present {
return typ, nil
var typeInfoMap = make(map[reflect.Type]*typeInfo) // protected by typeLock
// typeLock must be held.
-func getTypeInfo(ut *userTypeInfo) (*typeInfo, os.Error) {
+func getTypeInfo(ut *userTypeInfo) (*typeInfo, error) {
rt := ut.base
if ut.isGobEncoder {
// We want the user type, not the base type.
func mustGetTypeInfo(rt reflect.Type) *typeInfo {
t, err := getTypeInfo(userType(rt))
if err != nil {
- panic("getTypeInfo: " + err.String())
+ panic("getTypeInfo: " + err.Error())
}
return t
}
// GobEncode returns a byte slice representing the encoding of the
// receiver for transmission to a GobDecoder, usually of the same
// concrete type.
- GobEncode() ([]byte, os.Error)
+ GobEncode() ([]byte, error)
}
// GobDecoder is the interface describing data that provides its own
// GobDecode overwrites the receiver, which must be a pointer,
// with the value represented by the byte slice, which was written
// by GobEncode, usually for the same concrete type.
- GobDecode([]byte) os.Error
+ GobDecode([]byte) error
}
var (
defer typeLock.Unlock()
t, err := getBaseType(name, rt)
if err != nil {
- panic("getTypeUnlocked: " + err.String())
+ panic("getTypeUnlocked: " + err.Error())
}
return t
}
// significant-byte first (network) order.
package adler32
-import (
- "hash"
- "os"
-)
+import "hash"
const (
mod = 65521
return b<<16 | a
}
-func (d *digest) Write(p []byte) (nn int, err os.Error) {
+func (d *digest) Write(p []byte) (nn int, err error) {
d.a, d.b = update(d.a, d.b, p)
return len(p), nil
}
import (
"hash"
- "os"
"sync"
)
return update(crc, tab, p)
}
-func (d *digest) Write(p []byte) (n int, err os.Error) {
+func (d *digest) Write(p []byte) (n int, err error) {
d.crc = Update(d.crc, d.tab, p)
return len(p), nil
}
// information.
package crc64
-import (
- "hash"
- "os"
-)
+import "hash"
// The size of a CRC-64 checksum in bytes.
const Size = 8
return update(crc, tab, p)
}
-func (d *digest) Write(p []byte) (n int, err os.Error) {
+func (d *digest) Write(p []byte) (n int, err error) {
d.crc = update(d.crc, d.tab, p)
return len(p), nil
}
import (
"encoding/binary"
"hash"
- "os"
)
type (
func (s *sum64) Sum64() uint64 { return uint64(*s) }
func (s *sum64a) Sum64() uint64 { return uint64(*s) }
-func (s *sum32) Write(data []byte) (int, os.Error) {
+func (s *sum32) Write(data []byte) (int, error) {
hash := *s
for _, c := range data {
hash *= prime32
return len(data), nil
}
-func (s *sum32a) Write(data []byte) (int, os.Error) {
+func (s *sum32a) Write(data []byte) (int, error) {
hash := *s
for _, c := range data {
hash ^= sum32a(c)
return len(data), nil
}
-func (s *sum64) Write(data []byte) (int, os.Error) {
+func (s *sum64) Write(data []byte) (int, error) {
hash := *s
for _, c := range data {
hash *= prime64
return len(data), nil
}
-func (s *sum64a) Write(data []byte) (int, os.Error) {
+func (s *sum64a) Write(data []byte) (int, error) {
hash := *s
for _, c := range data {
hash ^= sum64a(c)
import (
"bytes"
- "os"
"strings"
"utf8"
)
const escapedChars = `&'<>"`
-func escape(w writer, s string) os.Error {
+func escape(w writer, s string) error {
i := strings.IndexAny(s, escapedChars)
for i != -1 {
if _, err := w.WriteString(s[:i]); err != nil {
import (
"io"
- "os"
"strings"
)
// read reads the next token. This is usually from the tokenizer, but it may
// be the synthesized end tag implied by a self-closing tag.
-func (p *parser) read() os.Error {
+func (p *parser) read() error {
if p.hasSelfClosingToken {
p.hasSelfClosingToken = false
p.tok.Type = EndTagToken
// Parse returns the parse tree for the HTML from the given Reader.
// The input is assumed to be UTF-8 encoded.
-func Parse(r io.Reader) (*Node, os.Error) {
+func Parse(r io.Reader) (*Node, error) {
p := &parser{
tokenizer: NewTokenizer(r),
doc: &Node{
for {
if consumed {
if err := p.read(); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
break
}
return nil, err
import (
"bufio"
"bytes"
+ "errors"
"fmt"
"io"
"io/ioutil"
"testing"
)
-func pipeErr(err os.Error) io.Reader {
+func pipeErr(err error) io.Reader {
pr, pw := io.Pipe()
pw.CloseWithError(err)
return pr
}
}
-func dumpLevel(w io.Writer, n *Node, level int) os.Error {
+func dumpLevel(w io.Writer, n *Node, level int) error {
dumpIndent(w, level)
switch n.Type {
case ErrorNode:
- return os.NewError("unexpected ErrorNode")
+ return errors.New("unexpected ErrorNode")
case DocumentNode:
- return os.NewError("unexpected DocumentNode")
+ return errors.New("unexpected DocumentNode")
case ElementNode:
fmt.Fprintf(w, "<%s>", n.Data)
for _, a := range n.Attr {
case DoctypeNode:
fmt.Fprintf(w, "<!DOCTYPE %s>", n.Data)
case scopeMarkerNode:
- return os.NewError("unexpected scopeMarkerNode")
+ return errors.New("unexpected scopeMarkerNode")
default:
- return os.NewError("unknown node type")
+ return errors.New("unknown node type")
}
io.WriteString(w, "\n")
for _, c := range n.Child {
return nil
}
-func dump(n *Node) (string, os.Error) {
+func dump(n *Node) (string, error) {
if n == nil || len(n.Child) == 0 {
return "", nil
}
import (
"bufio"
+ "errors"
"fmt"
"io"
- "os"
)
type writer interface {
io.Writer
- WriteByte(byte) os.Error
- WriteString(string) (int, os.Error)
+ WriteByte(byte) error
+ WriteString(string) (int, error)
}
// Render renders the parse tree n to the given writer.
// text node would become a tree containing <html>, <head> and <body> elements.
// Another example is that the programmatic equivalent of "a<head>b</head>c"
// becomes "<html><head><head/><body>abc</body></html>".
-func Render(w io.Writer, n *Node) os.Error {
+func Render(w io.Writer, n *Node) error {
if x, ok := w.(writer); ok {
return render(x, n)
}
return buf.Flush()
}
-func render(w writer, n *Node) os.Error {
+func render(w writer, n *Node) error {
// Render non-element nodes; these are the easy cases.
switch n.Type {
case ErrorNode:
- return os.NewError("html: cannot render an ErrorNode node")
+ return errors.New("html: cannot render an ErrorNode node")
case TextNode:
return escape(w, n.Data)
case DocumentNode:
}
return w.WriteByte('>')
default:
- return os.NewError("html: unknown node type")
+ return errors.New("html: unknown node type")
}
// Render the <xxx> opening tag.
import (
"bytes"
"io"
- "os"
"strconv"
"strings"
)
// Next call would set z.err to os.EOF but return a TextToken, and all
// subsequent Next calls would return an ErrorToken.
// err is never reset. Once it becomes non-nil, it stays non-nil.
- err os.Error
+ err error
// buf[raw.start:raw.end] holds the raw bytes of the current token.
// buf[raw.end:] is buffered input that will yield future tokens.
raw span
// Error returns the error associated with the most recent ErrorToken token.
// This is typically os.EOF, meaning the end of tokenization.
-func (z *Tokenizer) Error() os.Error {
+func (z *Tokenizer) Error() error {
if z.tt != ErrorToken {
return nil
}
import (
"bytes"
- "os"
+ "io"
"strings"
"testing"
)
}
}
z.Next()
- if z.Error() != os.EOF {
+ if z.Error() != io.EOF {
t.Errorf("%s: want EOF got %q", tt.desc, z.Error())
}
}
tt := z.Next()
switch tt {
case ErrorToken:
- if z.Error() != os.EOF {
+ if z.Error() != io.EOF {
t.Error(z.Error())
}
break loop
import (
"bufio"
"crypto/tls"
+ "errors"
"fmt"
"http"
"io"
// environment. This assumes the current program is being run
// by a web server in a CGI environment.
// The returned Request's Body is populated, if applicable.
-func Request() (*http.Request, os.Error) {
+func Request() (*http.Request, error) {
r, err := RequestFromMap(envMap(os.Environ()))
if err != nil {
return nil, err
// RequestFromMap creates an http.Request from CGI variables.
// The returned Request's Body field is not populated.
-func RequestFromMap(params map[string]string) (*http.Request, os.Error) {
+func RequestFromMap(params map[string]string) (*http.Request, error) {
r := new(http.Request)
r.Method = params["REQUEST_METHOD"]
if r.Method == "" {
- return nil, os.NewError("cgi: no REQUEST_METHOD in environment")
+ return nil, errors.New("cgi: no REQUEST_METHOD in environment")
}
r.Proto = params["SERVER_PROTOCOL"]
var ok bool
r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
if !ok {
- return nil, os.NewError("cgi: invalid SERVER_PROTOCOL version")
+ return nil, errors.New("cgi: invalid SERVER_PROTOCOL version")
}
r.Close = true
if lenstr := params["CONTENT_LENGTH"]; lenstr != "" {
clen, err := strconv.Atoi64(lenstr)
if err != nil {
- return nil, os.NewError("cgi: bad CONTENT_LENGTH in environment: " + lenstr)
+ return nil, errors.New("cgi: bad CONTENT_LENGTH in environment: " + lenstr)
}
r.ContentLength = clen
}
rawurl := "http://" + r.Host + params["REQUEST_URI"]
url, err := url.Parse(rawurl)
if err != nil {
- return nil, os.NewError("cgi: failed to parse host and REQUEST_URI into a URL: " + rawurl)
+ return nil, errors.New("cgi: failed to parse host and REQUEST_URI into a URL: " + rawurl)
}
r.URL = url
}
uriStr := params["REQUEST_URI"]
url, err := url.Parse(uriStr)
if err != nil {
- return nil, os.NewError("cgi: failed to parse REQUEST_URI into a URL: " + uriStr)
+ return nil, errors.New("cgi: failed to parse REQUEST_URI into a URL: " + uriStr)
}
r.URL = url
}
// request, if any. If there's no current CGI environment
// an error is returned. The provided handler may be nil to use
// http.DefaultServeMux.
-func Serve(handler http.Handler) os.Error {
+func Serve(handler http.Handler) error {
req, err := Request()
if err != nil {
return err
return r.header
}
-func (r *response) Write(p []byte) (n int, err os.Error) {
+func (r *response) Write(p []byte) (n int, err error) {
if !r.headerSent {
r.WriteHeader(http.StatusOK)
}
cwd = "."
}
- internalError := func(err os.Error) {
+ internalError := func(err error) {
rw.WriteHeader(http.StatusInternalServerError)
h.printf("CGI error: %v", err)
}
h.printf("cgi: long header line from subprocess.")
return
}
- if err == os.EOF {
+ if err == io.EOF {
break
}
if err != nil {
for {
line, err := rw.Body.ReadString('\n')
switch {
- case err == os.EOF:
+ case err == io.EOF:
break readlines
case err != nil:
t.Fatalf("unexpected error reading from CGI: %v", err)
cgifile, _ := filepath.Abs("testdata/test.cgi")
var perl string
- var err os.Error
+ var err error
perl, err = exec.LookPath("perl")
if err != nil {
return
cgifile, _ := filepath.Abs("testdata/test.cgi")
var perl string
- var err os.Error
+ var err error
perl, err = exec.LookPath("perl")
if err != nil {
return
"bufio"
"io"
"log"
- "os"
"strconv"
)
// Write the contents of data as one chunk to Wire.
// NOTE: Note that the corresponding chunk-writing procedure in Conn.Write has
// a bug since it does not check for success of io.WriteString
-func (cw *chunkedWriter) Write(data []byte) (n int, err os.Error) {
+func (cw *chunkedWriter) Write(data []byte) (n int, err error) {
// Don't send 0-length data. It looks like EOF for chunked encoding.
if len(data) == 0 {
return
}
-func (cw *chunkedWriter) Close() os.Error {
+func (cw *chunkedWriter) Close() error {
_, err := io.WriteString(cw.Wire, "0\r\n")
return err
}
import (
"encoding/base64"
+ "errors"
"fmt"
"io"
- "os"
"strings"
"url"
)
//
// If CheckRedirect is nil, the Client uses its default policy,
// which is to stop after 10 consecutive requests.
- CheckRedirect func(req *Request, via []*Request) os.Error
+ CheckRedirect func(req *Request, via []*Request) error
}
// DefaultClient is the default Client and is used by Get, Head, and Post.
// RoundTrip should not modify the request, except for
// consuming the Body. The request's URL and Header fields
// are guaranteed to be initialized.
- RoundTrip(*Request) (*Response, os.Error)
+ RoundTrip(*Request) (*Response, error)
}
// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
// connection to the server for a subsequent "keep-alive" request.
//
// Generally Get, Post, or PostForm will be used instead of Do.
-func (c *Client) Do(req *Request) (resp *Response, err os.Error) {
+func (c *Client) Do(req *Request) (resp *Response, err error) {
if req.Method == "GET" || req.Method == "HEAD" {
return c.doFollowingRedirects(req)
}
}
// send issues an HTTP request. Caller should close resp.Body when done reading from it.
-func send(req *Request, t RoundTripper) (resp *Response, err os.Error) {
+func send(req *Request, t RoundTripper) (resp *Response, err error) {
if t == nil {
t = DefaultTransport
if t == nil {
- err = os.NewError("http: no Client.Transport or DefaultTransport")
+ err = errors.New("http: no Client.Transport or DefaultTransport")
return
}
}
if req.URL == nil {
- return nil, os.NewError("http: nil Request.URL")
+ return nil, errors.New("http: nil Request.URL")
}
// Most the callers of send (Get, Post, et al) don't need
// Caller should close r.Body when done reading from it.
//
// Get is a convenience wrapper around DefaultClient.Get.
-func Get(url string) (r *Response, err os.Error) {
+func Get(url string) (r *Response, err error) {
return DefaultClient.Get(url)
}
// 307 (Temporary Redirect)
//
// Caller should close r.Body when done reading from it.
-func (c *Client) Get(url string) (r *Response, err os.Error) {
+func (c *Client) Get(url string) (r *Response, err error) {
req, err := NewRequest("GET", url, nil)
if err != nil {
return nil, err
return c.doFollowingRedirects(req)
}
-func (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err os.Error) {
+func (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err error) {
// TODO: if/when we add cookie support, the redirected request shouldn't
// necessarily supply the same cookies as the original.
var base *url.URL
var via []*Request
if ireq.URL == nil {
- return nil, os.NewError("http: nil Request.URL")
+ return nil, errors.New("http: nil Request.URL")
}
req := ireq
if shouldRedirect(r.StatusCode) {
r.Body.Close()
if urlStr = r.Header.Get("Location"); urlStr == "" {
- err = os.NewError(fmt.Sprintf("%d response missing Location header", r.StatusCode))
+ err = errors.New(fmt.Sprintf("%d response missing Location header", r.StatusCode))
break
}
base = req.URL
return
}
-func defaultCheckRedirect(req *Request, via []*Request) os.Error {
+func defaultCheckRedirect(req *Request, via []*Request) error {
if len(via) >= 10 {
- return os.NewError("stopped after 10 redirects")
+ return errors.New("stopped after 10 redirects")
}
return nil
}
// Caller should close r.Body when done reading from it.
//
// Post is a wrapper around DefaultClient.Post
-func Post(url string, bodyType string, body io.Reader) (r *Response, err os.Error) {
+func Post(url string, bodyType string, body io.Reader) (r *Response, err error) {
return DefaultClient.Post(url, bodyType, body)
}
// Post issues a POST to the specified URL.
//
// Caller should close r.Body when done reading from it.
-func (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response, err os.Error) {
+func (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response, err error) {
req, err := NewRequest("POST", url, body)
if err != nil {
return nil, err
// Caller should close r.Body when done reading from it.
//
// PostForm is a wrapper around DefaultClient.PostForm
-func PostForm(url string, data url.Values) (r *Response, err os.Error) {
+func PostForm(url string, data url.Values) (r *Response, err error) {
return DefaultClient.PostForm(url, data)
}
// with data's keys and values urlencoded as the request body.
//
// Caller should close r.Body when done reading from it.
-func (c *Client) PostForm(url string, data url.Values) (r *Response, err os.Error) {
+func (c *Client) PostForm(url string, data url.Values) (r *Response, err error) {
return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
// 307 (Temporary Redirect)
//
// Head is a wrapper around DefaultClient.Head
-func Head(url string) (r *Response, err os.Error) {
+func Head(url string) (r *Response, err error) {
return DefaultClient.Head(url)
}
// 302 (Found)
// 303 (See Other)
// 307 (Temporary Redirect)
-func (c *Client) Head(url string) (r *Response, err os.Error) {
+func (c *Client) Head(url string) (r *Response, err error) {
req, err := NewRequest("HEAD", url, nil)
if err != nil {
return nil, err
import (
"crypto/tls"
+ "errors"
"fmt"
. "http"
"http/httptest"
"io"
"io/ioutil"
"net"
- "os"
"strconv"
"strings"
"testing"
req *Request
}
-func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err os.Error) {
+func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
t.req = req
- return nil, os.NewError("dummy impl")
+ return nil, errors.New("dummy impl")
}
func TestGetRequestFormat(t *testing.T) {
t.Errorf("with default client Do, expected error %q, got %q", e, g)
}
- var checkErr os.Error
+ var checkErr error
var lastVia []*Request
- c = &Client{CheckRedirect: func(_ *Request, via []*Request) os.Error {
+ c = &Client{CheckRedirect: func(_ *Request, via []*Request) error {
lastVia = via
return checkErr
}}
t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
}
- checkErr = os.NewError("no redirects allowed")
+ checkErr = errors.New("no redirects allowed")
res, err = c.Get(ts.URL)
finalUrl = res.Request.URL.String()
if e, g := "Get /?n=1: no redirects allowed", fmt.Sprintf("%v", err); e != g {
}
close(say)
_, err = io.ReadFull(res.Body, buf[0:1])
- if err != os.EOF {
+ if err != io.EOF {
t.Fatalf("at end expected EOF, got %v", err)
}
}
count *int
}
-func (c *writeCountingConn) Write(p []byte) (int, os.Error) {
+func (c *writeCountingConn) Write(p []byte) (int, error) {
*c.count++
return c.Conn.Write(p)
}
defer ts.Close()
writes := 0
- dialer := func(netz string, addr string) (net.Conn, os.Error) {
+ dialer := func(netz string, addr string) (net.Conn, error) {
c, err := net.Dial(netz, addr)
if err == nil {
c = &writeCountingConn{c, &writes}
import (
"fmt"
"json"
- "os"
"reflect"
"testing"
"time"
return Header(ho)
}
-func (ho headerOnlyResponseWriter) Write([]byte) (int, os.Error) {
+func (ho headerOnlyResponseWriter) Write([]byte) (int, error) {
panic("NOIMPL")
}
"bytes"
"io"
"io/ioutil"
- "os"
)
// One of the copies, say from b to r2, could be avoided by using a more
// elaborate trick where the other copy is made during Request/Response.Write.
// This would complicate things too much, given that these functions are for
// debugging only.
-func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err os.Error) {
+func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, nil, err
// changes req.Body to refer to the in-memory copy.
// The documentation for Request.Write details which fields
// of req are used.
-func DumpRequest(req *Request, body bool) (dump []byte, err os.Error) {
+func DumpRequest(req *Request, body bool) (dump []byte, err error) {
var b bytes.Buffer
save := req.Body
if !body || req.Body == nil {
}
// DumpResponse is like DumpRequest but dumps a response.
-func DumpResponse(resp *Response, body bool) (dump []byte, err os.Error) {
+func DumpResponse(resp *Response, body bool) (dump []byte, err error) {
var b bytes.Buffer
save := resp.Body
savecl := resp.ContentLength
return r.header
}
-func (r *response) Write(data []byte) (int, os.Error) {
+func (r *response) Write(data []byte) (int, error) {
if !r.wroteHeader {
r.WriteHeader(http.StatusOK)
}
r.w.Flush()
}
-func (r *response) Close() os.Error {
+func (r *response) Close() error {
r.Flush()
return r.w.Close()
}
if err != nil {
// there was an error reading the request
r.WriteHeader(http.StatusInternalServerError)
- c.conn.writeRecord(typeStderr, req.reqId, []byte(err.String()))
+ c.conn.writeRecord(typeStderr, req.reqId, []byte(err.Error()))
} else {
httpReq.Body = body
c.handler.ServeHTTP(r, httpReq)
// to reply to them.
// If l is nil, Serve accepts connections on stdin.
// If handler is nil, http.DefaultServeMux is used.
-func Serve(l net.Listener, handler http.Handler) os.Error {
+func Serve(l net.Listener, handler http.Handler) error {
if l == nil {
- var err os.Error
+ var err error
l, err = net.FileListener(os.Stdin)
if err != nil {
return err
"bufio"
"bytes"
"encoding/binary"
+ "errors"
"io"
- "os"
"sync"
)
reserved [5]uint8
}
-func (br *beginRequest) read(content []byte) os.Error {
+func (br *beginRequest) read(content []byte) error {
if len(content) != 8 {
- return os.NewError("fcgi: invalid begin request record")
+ return errors.New("fcgi: invalid begin request record")
}
br.role = binary.BigEndian.Uint16(content)
br.flags = content[2]
return &conn{rwc: rwc}
}
-func (c *conn) Close() os.Error {
+func (c *conn) Close() error {
c.mutex.Lock()
defer c.mutex.Unlock()
return c.rwc.Close()
buf [maxWrite + maxPad]byte
}
-func (rec *record) read(r io.Reader) (err os.Error) {
+func (rec *record) read(r io.Reader) (err error) {
if err = binary.Read(r, binary.BigEndian, &rec.h); err != nil {
return err
}
if rec.h.Version != 1 {
- return os.NewError("fcgi: invalid header version")
+ return errors.New("fcgi: invalid header version")
}
n := int(rec.h.ContentLength) + int(rec.h.PaddingLength)
if _, err = io.ReadFull(r, rec.buf[:n]); err != nil {
}
// writeRecord writes and sends a single record.
-func (c *conn) writeRecord(recType uint8, reqId uint16, b []byte) os.Error {
+func (c *conn) writeRecord(recType uint8, reqId uint16, b []byte) error {
c.mutex.Lock()
defer c.mutex.Unlock()
c.buf.Reset()
return err
}
-func (c *conn) writeBeginRequest(reqId uint16, role uint16, flags uint8) os.Error {
+func (c *conn) writeBeginRequest(reqId uint16, role uint16, flags uint8) error {
b := [8]byte{byte(role >> 8), byte(role), flags}
return c.writeRecord(typeBeginRequest, reqId, b[:])
}
-func (c *conn) writeEndRequest(reqId uint16, appStatus int, protocolStatus uint8) os.Error {
+func (c *conn) writeEndRequest(reqId uint16, appStatus int, protocolStatus uint8) error {
b := make([]byte, 8)
binary.BigEndian.PutUint32(b, uint32(appStatus))
b[4] = protocolStatus
return c.writeRecord(typeEndRequest, reqId, b)
}
-func (c *conn) writePairs(recType uint8, reqId uint16, pairs map[string]string) os.Error {
+func (c *conn) writePairs(recType uint8, reqId uint16, pairs map[string]string) error {
w := newWriter(c, recType, reqId)
b := make([]byte, 8)
for k, v := range pairs {
*bufio.Writer
}
-func (w *bufWriter) Close() os.Error {
+func (w *bufWriter) Close() error {
if err := w.Writer.Flush(); err != nil {
w.closer.Close()
return err
reqId uint16
}
-func (w *streamWriter) Write(p []byte) (int, os.Error) {
+func (w *streamWriter) Write(p []byte) (int, error) {
nn := 0
for len(p) > 0 {
n := len(p)
return nn, nil
}
-func (w *streamWriter) Close() os.Error {
+func (w *streamWriter) Close() error {
// send empty record to close the stream
return w.c.writeRecord(w.recType, w.reqId, nil)
}
import (
"bytes"
"io"
- "os"
"testing"
)
io.ReadWriter
}
-func (c *nilCloser) Close() os.Error { return nil }
+func (c *nilCloser) Close() error { return nil }
func TestStreams(t *testing.T) {
var rec record
import (
"fmt"
"io"
- "os"
)
// fileTransport implements RoundTripper for the 'file' protocol.
return fileTransport{fileHandler{fs}}
}
-func (t fileTransport) RoundTrip(req *Request) (resp *Response, err os.Error) {
+func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error) {
// We start ServeHTTP in a goroutine, which may take a long
// time if the file is large. The newPopulateResponseWriter
// call returns a channel which either ServeHTTP or finish()
pr.res.Status = fmt.Sprintf("%d %s", code, StatusText(code))
}
-func (pr *populateResponse) Write(p []byte) (n int, err os.Error) {
+func (pr *populateResponse) Write(p []byte) (n int, err error) {
if !pr.wroteHeader {
pr.WriteHeader(StatusOK)
}
"http"
"io/ioutil"
"path/filepath"
- "os"
"testing"
)
-func checker(t *testing.T) func(string, os.Error) {
- return func(call string, err os.Error) {
+func checker(t *testing.T) func(string, error) {
+ return func(call string, err error) {
if err == nil {
return
}
package http
import (
+ "errors"
"fmt"
"io"
"mime"
// system restricted to a specific directory tree.
type Dir string
-func (d Dir) Open(name string) (File, os.Error) {
+func (d Dir) Open(name string) (File, error) {
if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 {
- return nil, os.NewError("http: invalid character in file path")
+ return nil, errors.New("http: invalid character in file path")
}
f, err := os.Open(filepath.Join(string(d), filepath.FromSlash(path.Clean("/"+name))))
if err != nil {
// The elements in a file path are separated by slash ('/', U+002F)
// characters, regardless of host operating system convention.
type FileSystem interface {
- Open(name string) (File, os.Error)
+ Open(name string) (File, error)
}
// A File is returned by a FileSystem's Open method and can be
// served by the FileServer implementation.
type File interface {
- Close() os.Error
- Stat() (*os.FileInfo, os.Error)
- Readdir(count int) ([]os.FileInfo, os.Error)
- Read([]byte) (int, os.Error)
- Seek(offset int64, whence int) (int64, os.Error)
+ Close() error
+ Stat() (*os.FileInfo, error)
+ Readdir(count int) ([]os.FileInfo, error)
+ Read([]byte) (int, error)
+ Seek(offset int64, whence int) (int64, error)
}
// Heuristic: b is text if it is valid UTF-8 and doesn't
// TODO(adg): handle multiple ranges
ranges, err := parseRange(r.Header.Get("Range"), size)
if err == nil && len(ranges) > 1 {
- err = os.NewError("multiple ranges not supported")
+ err = errors.New("multiple ranges not supported")
}
if err != nil {
- Error(w, err.String(), StatusRequestedRangeNotSatisfiable)
+ Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
return
}
if len(ranges) == 1 {
ra := ranges[0]
if _, err := f.Seek(ra.start, os.SEEK_SET); err != nil {
- Error(w, err.String(), StatusRequestedRangeNotSatisfiable)
+ Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
return
}
size = ra.length
}
// parseRange parses a Range header string as per RFC 2616.
-func parseRange(s string, size int64) ([]httpRange, os.Error) {
+func parseRange(s string, size int64) ([]httpRange, error) {
if s == "" {
return nil, nil // header not present
}
const b = "bytes="
if !strings.HasPrefix(s, b) {
- return nil, os.NewError("invalid range")
+ return nil, errors.New("invalid range")
}
var ranges []httpRange
for _, ra := range strings.Split(s[len(b):], ",") {
i := strings.Index(ra, "-")
if i < 0 {
- return nil, os.NewError("invalid range")
+ return nil, errors.New("invalid range")
}
start, end := ra[:i], ra[i+1:]
var r httpRange
// range start relative to the end of the file.
i, err := strconv.Atoi64(end)
if err != nil {
- return nil, os.NewError("invalid range")
+ return nil, errors.New("invalid range")
}
if i > size {
i = size
} else {
i, err := strconv.Atoi64(start)
if err != nil || i > size || i < 0 {
- return nil, os.NewError("invalid range")
+ return nil, errors.New("invalid range")
}
r.start = i
if end == "" {
} else {
i, err := strconv.Atoi64(end)
if err != nil || r.start > i {
- return nil, os.NewError("invalid range")
+ return nil, errors.New("invalid range")
}
if i >= size {
i = size - 1
}))
defer ts.Close()
- var err os.Error
+ var err error
file, err := ioutil.ReadFile(testFile)
if err != nil {
}
type testFileSystem struct {
- open func(name string) (File, os.Error)
+ open func(name string) (File, error)
}
-func (fs *testFileSystem) Open(name string) (File, os.Error) {
+func (fs *testFileSystem) Open(name string) (File, error) {
return fs.open(name)
}
func TestFileServerCleans(t *testing.T) {
ch := make(chan string, 1)
- fs := FileServer(&testFileSystem{func(name string) (File, os.Error) {
+ fs := FileServer(&testFileSystem{func(name string) (File, error) {
ch <- name
return nil, os.ENOENT
}})
"fmt"
"io"
"net/textproto"
- "os"
"sort"
"strings"
)
}
// Write writes a header in wire format.
-func (h Header) Write(w io.Writer) os.Error {
+func (h Header) Write(w io.Writer) error {
return h.WriteSubset(w, nil)
}
// WriteSubset writes a header in wire format.
// If exclude is not nil, keys where exclude[key] == true are not written.
-func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) os.Error {
+func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error {
keys := make([]string, 0, len(h))
for k := range h {
if exclude == nil || !exclude[k] {
import (
"bytes"
"http"
- "os"
)
// ResponseRecorder is an implementation of http.ResponseWriter that
}
// Write always succeeds and writes to rw.Body, if not nil.
-func (rw *ResponseRecorder) Write(buf []byte) (int, os.Error) {
+func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
if rw.Body != nil {
rw.Body.Write(buf)
}
history []net.Conn
}
-func (hs *historyListener) Accept() (c net.Conn, err os.Error) {
+func (hs *historyListener) Accept() (c net.Conn, err error) {
c, err = hs.Listener.Accept()
if err == nil {
hs.history = append(hs.history, c)
import (
"bufio"
+ "errors"
"io"
"net"
"net/textproto"
lk sync.Mutex // read-write protects the following fields
c net.Conn
r *bufio.Reader
- re, we os.Error // read/write errors
+ re, we error // read/write errors
lastbody io.ReadCloser
nread, nwritten int
pipereq map[*Request]uint
}
// Close calls Hijack and then also closes the underlying connection
-func (sc *ServerConn) Close() os.Error {
+func (sc *ServerConn) Close() error {
c, _ := sc.Hijack()
if c != nil {
return c.Close()
// it is gracefully determined that there are no more requests (e.g. after the
// first request on an HTTP/1.0 connection, or after a Connection:close on a
// HTTP/1.1 connection).
-func (sc *ServerConn) Read() (req *Request, err os.Error) {
+func (sc *ServerConn) Read() (req *Request, err error) {
// Ensure ordered execution of Reads and Writes
id := sc.pipe.Next()
// Write writes resp in response to req. To close the connection gracefully, set the
// Response.Close field to true. Write should be considered operational until
// it returns an error, regardless of any errors returned on the Read side.
-func (sc *ServerConn) Write(req *Request, resp *Response) os.Error {
+func (sc *ServerConn) Write(req *Request, resp *Response) error {
// Retrieve the pipeline ID of this request/response pair
sc.lk.Lock()
c := sc.c
if sc.nread <= sc.nwritten {
defer sc.lk.Unlock()
- return os.NewError("persist server pipe count")
+ return errors.New("persist server pipe count")
}
if resp.Close {
// After signaling a keep-alive close, any pipelined unread
lk sync.Mutex // read-write protects the following fields
c net.Conn
r *bufio.Reader
- re, we os.Error // read/write errors
+ re, we error // read/write errors
lastbody io.ReadCloser
nread, nwritten int
pipereq map[*Request]uint
pipe textproto.Pipeline
- writeReq func(*Request, io.Writer) os.Error
+ writeReq func(*Request, io.Writer) error
}
// NewClientConn returns a new ClientConn reading and writing c. If r is not
}
// Close calls Hijack and then also closes the underlying connection
-func (cc *ClientConn) Close() os.Error {
+func (cc *ClientConn) Close() error {
c, _ := cc.Hijack()
if c != nil {
return c.Close()
// keepalive connection is logically closed after this request and the opposing
// server is informed. An ErrUnexpectedEOF indicates the remote closed the
// underlying TCP connection, which is usually considered as graceful close.
-func (cc *ClientConn) Write(req *Request) (err os.Error) {
+func (cc *ClientConn) Write(req *Request) (err error) {
// Ensure ordered execution of Writes
id := cc.pipe.Next()
// returned together with an ErrPersistEOF, which means that the remote
// requested that this be the last request serviced. Read can be called
// concurrently with Write, but not with another Read.
-func (cc *ClientConn) Read(req *Request) (*Response, os.Error) {
+func (cc *ClientConn) Read(req *Request) (*Response, error) {
return cc.readUsing(req, ReadResponse)
}
// readUsing is the implementation of Read with a replaceable
// ReadResponse-like function, used by the Transport.
-func (cc *ClientConn) readUsing(req *Request, readRes func(*bufio.Reader, *Request) (*Response, os.Error)) (resp *Response, err os.Error) {
+func (cc *ClientConn) readUsing(req *Request, readRes func(*bufio.Reader, *Request) (*Response, error)) (resp *Response, err error) {
// Retrieve the pipeline ID of this request/response pair
cc.lk.Lock()
id, ok := cc.pipereq[req]
}
// Do is convenience method that writes a request and reads a response.
-func (cc *ClientConn) Do(req *Request) (resp *Response, err os.Error) {
+func (cc *ClientConn) Do(req *Request) (resp *Response, err error) {
err = cc.Write(req)
if err != nil {
return
"bytes"
"fmt"
"http"
+ "io"
"os"
"runtime"
"runtime/pprof"
// Wait until here to check for err; the last
// symbol will have an err because it doesn't end in +.
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
fmt.Fprintf(&buf, "reading request: %v\n", err)
}
break
braw.WriteString(tt.Raw)
req, err := ReadRequest(bufio.NewReader(&braw))
if err != nil {
- if err.String() != tt.Error {
- t.Errorf("#%d: error %q, want error %q", i, err.String(), tt.Error)
+ if err.Error() != tt.Error {
+ t.Errorf("#%d: error %q, want error %q", i, err.Error(), tt.Error)
}
continue
}
"bytes"
"crypto/tls"
"encoding/base64"
+ "errors"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/textproto"
- "os"
"strconv"
"strings"
"url"
// ErrMissingFile is returned by FormFile when the provided file field name
// is either not present in the request or not a file field.
-var ErrMissingFile = os.NewError("http: no such file")
+var ErrMissingFile = errors.New("http: no such file")
// HTTP request parsing errors.
type ProtocolError struct {
ErrorString string
}
-func (err *ProtocolError) String() string { return err.ErrorString }
+func (err *ProtocolError) Error() string { return err.ErrorString }
var (
ErrLineTooLong = &ProtocolError{"header line too long"}
str string
}
-func (e *badStringError) String() string { return fmt.Sprintf("%s %q", e.what, e.str) }
+func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
// Headers that Request.Write handles itself and should be skipped.
var reqWriteExcludeHeader = map[string]bool{
return readCookies(r.Header, "")
}
-var ErrNoCookie = os.NewError("http: named cookied not present")
+var ErrNoCookie = errors.New("http: named cookied not present")
// Cookie returns the named cookie provided in the request or
// ErrNoCookie if not found.
-func (r *Request) Cookie(name string) (*Cookie, os.Error) {
+func (r *Request) Cookie(name string) (*Cookie, error) {
for _, c := range readCookies(r.Header, name) {
return c, nil
}
// multipart/form-data POST request, else returns nil and an error.
// Use this function instead of ParseMultipartForm to
// process the request body as a stream.
-func (r *Request) MultipartReader() (*multipart.Reader, os.Error) {
+func (r *Request) MultipartReader() (*multipart.Reader, error) {
if r.MultipartForm == multipartByReader {
- return nil, os.NewError("http: MultipartReader called twice")
+ return nil, errors.New("http: MultipartReader called twice")
}
if r.MultipartForm != nil {
- return nil, os.NewError("http: multipart handled by ParseMultipartForm")
+ return nil, errors.New("http: multipart handled by ParseMultipartForm")
}
r.MultipartForm = multipartByReader
return r.multipartReader()
}
-func (r *Request) multipartReader() (*multipart.Reader, os.Error) {
+func (r *Request) multipartReader() (*multipart.Reader, error) {
v := r.Header.Get("Content-Type")
if v == "" {
return nil, ErrNotMultipart
// If Body is present, Content-Length is <= 0 and TransferEncoding
// hasn't been set to "identity", Write adds "Transfer-Encoding:
// chunked" to the header. Body is closed after it is sent.
-func (req *Request) Write(w io.Writer) os.Error {
+func (req *Request) Write(w io.Writer) error {
return req.write(w, false, nil)
}
// section 5.1.2 of RFC 2616, including the scheme and host. In
// either case, WriteProxy also writes a Host header, using either
// req.Host or req.URL.Host.
-func (req *Request) WriteProxy(w io.Writer) os.Error {
+func (req *Request) WriteProxy(w io.Writer) error {
return req.write(w, true, nil)
}
-func (req *Request) dumpWrite(w io.Writer) os.Error {
+func (req *Request) dumpWrite(w io.Writer) error {
// TODO(bradfitz): RawPath here?
urlStr := valueOrDefault(req.URL.EncodedPath(), "/")
if req.URL.RawQuery != "" {
}
// extraHeaders may be nil
-func (req *Request) write(w io.Writer, usingProxy bool, extraHeaders Header) os.Error {
+func (req *Request) write(w io.Writer, usingProxy bool, extraHeaders Header) error {
host := req.Host
if host == "" {
if req.URL == nil {
- return os.NewError("http: Request.Write on Request with no Host or URL set")
+ return errors.New("http: Request.Write on Request with no Host or URL set")
}
host = req.URL.Host
}
// Give up if the line exceeds maxLineLength.
// The returned bytes are a pointer into storage in
// the bufio, so they are only valid until the next bufio read.
-func readLineBytes(b *bufio.Reader) (p []byte, err os.Error) {
+func readLineBytes(b *bufio.Reader) (p []byte, err error) {
if p, err = b.ReadSlice('\n'); err != nil {
// We always know when EOF is coming.
// If the caller asked for a line, there should be a line.
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
} else if err == bufio.ErrBufferFull {
err = ErrLineTooLong
}
// readLineBytes, but convert the bytes into a string.
-func readLine(b *bufio.Reader) (s string, err os.Error) {
+func readLine(b *bufio.Reader) (s string, err error) {
p, e := readLineBytes(b)
if e != nil {
return "", e
type chunkedReader struct {
r *bufio.Reader
n uint64 // unread bytes in chunk
- err os.Error
+ err error
}
func (cr *chunkedReader) beginChunk() {
break
}
}
- cr.err = os.EOF
+ cr.err = io.EOF
}
}
-func (cr *chunkedReader) Read(b []uint8) (n int, err os.Error) {
+func (cr *chunkedReader) Read(b []uint8) (n int, err error) {
if cr.err != nil {
return 0, cr.err
}
b := make([]byte, 2)
if _, cr.err = io.ReadFull(cr.r, b); cr.err == nil {
if b[0] != '\r' || b[1] != '\n' {
- cr.err = os.NewError("malformed chunked encoding")
+ cr.err = errors.New("malformed chunked encoding")
}
}
}
}
// NewRequest returns a new Request given a method, URL, and optional body.
-func NewRequest(method, urlStr string, body io.Reader) (*Request, os.Error) {
+func NewRequest(method, urlStr string, body io.Reader) (*Request, error) {
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
// ReadRequest reads and parses a request from b.
-func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) {
+func ReadRequest(b *bufio.Reader) (req *Request, err error) {
tp := textproto.NewReader(b)
req = new(Request)
// First line: GET /index.html HTTP/1.0
var s string
if s, err = tp.ReadLine(); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
stopped bool
}
-func (l *maxBytesReader) Read(p []byte) (n int, err os.Error) {
+func (l *maxBytesReader) Read(p []byte) (n int, err error) {
if l.n <= 0 {
if !l.stopped {
l.stopped = true
res.requestTooLarge()
}
}
- return 0, os.NewError("http: request body too large")
+ return 0, errors.New("http: request body too large")
}
if int64(len(p)) > l.n {
p = p[:l.n]
return
}
-func (l *maxBytesReader) Close() os.Error {
+func (l *maxBytesReader) Close() error {
return l.r.Close()
}
//
// ParseMultipartForm calls ParseForm automatically.
// It is idempotent.
-func (r *Request) ParseForm() (err os.Error) {
+func (r *Request) ParseForm() (err error) {
if r.Form != nil {
return
}
}
if r.Method == "POST" || r.Method == "PUT" {
if r.Body == nil {
- return os.NewError("missing form body")
+ return errors.New("missing form body")
}
ct := r.Header.Get("Content-Type")
ct, _, err := mime.ParseMediaType(ct)
break
}
if int64(len(b)) > maxFormSize {
- return os.NewError("http: POST too large")
+ return errors.New("http: POST too large")
}
var newValues url.Values
newValues, e = url.ParseQuery(string(b))
// disk in temporary files.
// ParseMultipartForm calls ParseForm if necessary.
// After one call to ParseMultipartForm, subsequent calls have no effect.
-func (r *Request) ParseMultipartForm(maxMemory int64) os.Error {
+func (r *Request) ParseMultipartForm(maxMemory int64) error {
if r.MultipartForm == multipartByReader {
- return os.NewError("http: multipart handled by MultipartReader")
+ return errors.New("http: multipart handled by MultipartReader")
}
if r.Form == nil {
err := r.ParseForm()
// FormFile returns the first file for the provided form key.
// FormFile calls ParseMultipartForm and ParseForm if necessary.
-func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, os.Error) {
+func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
if r.MultipartForm == multipartByReader {
- return nil, nil, os.NewError("http: multipart handled by MultipartReader")
+ return nil, nil, errors.New("http: multipart handled by MultipartReader")
}
if r.MultipartForm == nil {
err := r.ParseMultipartForm(defaultMaxMemory)
type stringMap map[string][]string
type parseContentTypeTest struct {
contentType stringMap
- error bool
+ err bool
}
var parseContentTypeTests = []parseContentTypeTest{
{contentType: stringMap{"Content-Type": {"text/plain; boundary="}}},
{
contentType: stringMap{"Content-Type": {"application/unknown"}},
- error: true,
+ err: true,
},
}
Body: ioutil.NopCloser(bytes.NewBufferString("body")),
}
err := req.ParseForm()
- if !test.error && err != nil {
+ if !test.err && err != nil {
t.Errorf("test %d: Unexpected error: %v", i, err)
}
- if test.error && err == nil {
+ if test.err && err == nil {
t.Errorf("test %d should have returned error", i)
}
}
import (
"bytes"
+ "errors"
"fmt"
"io"
"io/ioutil"
- "os"
"strings"
"testing"
"url"
WantProxy string // Request.WriteProxy
WantDump string // DumpRequest
- WantError os.Error // wanted error from Request.Write
+ WantError error // wanted error from Request.Write
}
var reqWriteTests = []reqWriteTest{
ContentLength: 10, // but we're going to send only 5 bytes
},
Body: []byte("12345"),
- WantError: os.NewError("http: Request.ContentLength=10 with Body length 5"),
+ WantError: errors.New("http: Request.ContentLength=10 with Body length 5"),
},
// Request with a ContentLength of 4 but an 8 byte body.
ContentLength: 4, // but we're going to try to send 8 bytes
},
Body: []byte("12345678"),
- WantError: os.NewError("http: Request.ContentLength=4 with Body length 8"),
+ WantError: errors.New("http: Request.ContentLength=4 with Body length 8"),
},
// Request with a 5 ContentLength and nil body.
ProtoMinor: 1,
ContentLength: 5, // but we'll omit the body
},
- WantError: os.NewError("http: Request.ContentLength=5 with nil Body"),
+ WantError: errors.New("http: Request.ContentLength=5 with nil Body"),
},
// Verify that DumpRequest preserves the HTTP version number, doesn't add a Host,
closed bool
}
-func (rc *closeChecker) Close() os.Error {
+func (rc *closeChecker) Close() error {
rc.closed = true
return nil
}
import (
"bufio"
+ "errors"
"io"
"net/textproto"
- "os"
"strconv"
"strings"
"url"
return readSetCookies(r.Header)
}
-var ErrNoLocation = os.NewError("http: no Location header in response")
+var ErrNoLocation = errors.New("http: no Location header in response")
// Location returns the URL of the response's "Location" header,
// if present. Relative redirects are resolved relative to
// the Response's Request. ErrNoLocation is returned if no
// Location header is present.
-func (r *Response) Location() (*url.URL, os.Error) {
+func (r *Response) Location() (*url.URL, error) {
lv := r.Header.Get("Location")
if lv == "" {
return nil, ErrNoLocation
// reading resp.Body. After that call, clients can inspect
// resp.Trailer to find key/value pairs included in the response
// trailer.
-func ReadResponse(r *bufio.Reader, req *Request) (resp *Response, err os.Error) {
+func ReadResponse(r *bufio.Reader, req *Request) (resp *Response, err error) {
tp := textproto.NewReader(r)
resp = new(Response)
// Parse the first line of the response.
line, err := tp.ReadLine()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
// ContentLength
// Header, values for non-canonical keys will have unpredictable behavior
//
-func (resp *Response) Write(w io.Writer) os.Error {
+func (resp *Response) Write(w io.Writer) error {
// RequestMethod should be upper-case
if resp.Request != nil {
"compress/gzip"
"crypto/rand"
"fmt"
- "os"
"io"
"io/ioutil"
"reflect"
args = append([]interface{}{test.chunked, test.compressed}, args...)
t.Fatalf("on test chunked=%v, compressed=%v: "+format, args...)
}
- checkErr := func(err os.Error, msg string) {
+ checkErr := func(err error, msg string) {
if err == nil {
return
}
}
if test.compressed {
buf.WriteString("Content-Encoding: gzip\r\n")
- var err os.Error
+ var err error
wr, err = gzip.NewWriter(wr)
checkErr(err, "gzip.NewWriter")
}
location string // Response's Location header or ""
requrl string // Response.Request.URL or ""
want string
- wantErr os.Error
+ wantErr error
}
var responseLocationTests = []responseLocationTest{
res.Header.Set("Location", tt.location)
if tt.requrl != "" {
res.Request = &Request{}
- var err os.Error
+ var err error
res.Request.URL, err = url.Parse(tt.requrl)
if err != nil {
t.Fatalf("bad test URL %q: %v", tt.requrl, err)
t.Errorf("%d. err=nil; want %q", i, tt.wantErr)
continue
}
- if g, e := err.String(), tt.wantErr.String(); g != e {
+ if g, e := err.Error(), tt.wantErr.Error(); g != e {
t.Errorf("%d. err=%q; want %q", i, g, e)
continue
}
"io"
"log"
"net"
- "os"
"strings"
"sync"
"time"
done chan bool
}
-func (m *maxLatencyWriter) Write(p []byte) (n int, err os.Error) {
+func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
m.lk.Lock()
defer m.lk.Unlock()
if m.done == nil {
conn net.Conn
}
-func (l *oneConnListener) Accept() (c net.Conn, err os.Error) {
+func (l *oneConnListener) Accept() (c net.Conn, err error) {
c = l.conn
if c == nil {
- err = os.EOF
+ err = io.EOF
return
}
err = nil
return
}
-func (l *oneConnListener) Close() os.Error {
+func (l *oneConnListener) Close() error {
return nil
}
writeBuf bytes.Buffer
}
-func (c *testConn) Read(b []byte) (int, os.Error) {
+func (c *testConn) Read(b []byte) (int, error) {
return c.readBuf.Read(b)
}
-func (c *testConn) Write(b []byte) (int, os.Error) {
+func (c *testConn) Write(b []byte) (int, error) {
return c.writeBuf.Write(b)
}
-func (c *testConn) Close() os.Error {
+func (c *testConn) Close() error {
return nil
}
return dummyAddr("remote-addr")
}
-func (c *testConn) SetTimeout(nsec int64) os.Error {
+func (c *testConn) SetTimeout(nsec int64) error {
return nil
}
-func (c *testConn) SetReadTimeout(nsec int64) os.Error {
+func (c *testConn) SetReadTimeout(nsec int64) error {
return nil
}
-func (c *testConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *testConn) SetWriteTimeout(nsec int64) error {
return nil
}
reqNum := 0
ch := make(chan *Request)
- servech := make(chan os.Error)
+ servech := make(chan error)
listener := &oneConnListener{conn}
handler := func(res ResponseWriter, req *Request) {
reqNum++
req.Method, "POST")
}
- if serveerr := <-servech; serveerr != os.EOF {
+ if serveerr := <-servech; serveerr != io.EOF {
t.Errorf("Serve returned %q; expected EOF", serveerr)
}
}
buf := make([]byte, 1)
n, err := conn.Read(buf)
latency := time.Nanoseconds() - t1
- if n != 0 || err != os.EOF {
- t.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, os.EOF)
+ if n != 0 || err != io.EOF {
+ t.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF)
}
if latency < second*0.20 /* fudge from 0.25 above */ {
t.Errorf("got EOF after %d ns, want >= %d", latency, second*0.20)
func TestTimeoutHandler(t *testing.T) {
sendHi := make(chan bool, 1)
- writeErrors := make(chan os.Error, 1)
+ writeErrors := make(chan error, 1)
sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
<-sendHi
_, werr := w.Write([]byte("hi"))
type neverEnding byte
-func (b neverEnding) Read(p []byte) (n int, err os.Error) {
+func (b neverEnding) Read(p []byte) (n int, err error) {
for i := range p {
p[i] = byte(b)
}
n *int64
}
-func (cr countReader) Read(p []byte) (n int, err os.Error) {
+func (cr countReader) Read(p []byte) (n int, err error) {
n, err = cr.r.Read(p)
*cr.n += int64(n)
return
}
type errorListener struct {
- errs []os.Error
+ errs []error
}
-func (l *errorListener) Accept() (c net.Conn, err os.Error) {
+func (l *errorListener) Accept() (c net.Conn, err error) {
if len(l.errs) == 0 {
- return nil, os.EOF
+ return nil, io.EOF
}
err = l.errs[0]
l.errs = l.errs[1:]
return
}
-func (l *errorListener) Close() os.Error {
+func (l *errorListener) Close() error {
return nil
}
log.SetOutput(ioutil.Discard) // is noisy otherwise
defer log.SetOutput(os.Stderr)
- ln := &errorListener{[]os.Error{
+ ln := &errorListener{[]error{
&net.OpError{
- Op: "accept",
- Error: os.Errno(syscall.EMFILE),
+ Op: "accept",
+ Err: os.Errno(syscall.EMFILE),
}}}
err := Serve(ln, HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})))
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("got error %v, want EOF", err)
}
}
for i := 0; i < b.N; i++ {
res, err := Get(ts.URL)
if err != nil {
- panic("Get: " + err.String())
+ panic("Get: " + err.Error())
}
all, err := ioutil.ReadAll(res.Body)
if err != nil {
- panic("ReadAll: " + err.String())
+ panic("ReadAll: " + err.Error())
}
body := string(all)
if body != "Hello world.\n" {
"bytes"
"crypto/rand"
"crypto/tls"
+ "errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
- "os"
"path"
"runtime/debug"
"strconv"
// Errors introduced by the HTTP server.
var (
- ErrWriteAfterFlush = os.NewError("Conn.Write called after Flush")
- ErrBodyNotAllowed = os.NewError("http: response status code does not allow body")
- ErrHijacked = os.NewError("Conn has been hijacked")
- ErrContentLength = os.NewError("Conn.Write wrote more than the declared Content-Length")
+ ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
+ ErrBodyNotAllowed = errors.New("http: response status code does not allow body")
+ ErrHijacked = errors.New("Conn has been hijacked")
+ ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length")
)
// Objects implementing the Handler interface can be
// Write writes the data to the connection as part of an HTTP reply.
// If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
// before writing the data.
- Write([]byte) (int, os.Error)
+ Write([]byte) (int, error)
// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will not do anything else with the connection.
// It becomes the caller's responsibility to manage
// and close the connection.
- Hijack() (net.Conn, *bufio.ReadWriter, os.Error)
+ Hijack() (net.Conn, *bufio.ReadWriter, error)
}
// A conn represents the server side of an HTTP connection.
io.Writer
}
-func (w *response) ReadFrom(src io.Reader) (n int64, err os.Error) {
+func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
// Flush before checking w.chunking, as Flush will call
// WriteHeader if it hasn't been called yet, and WriteHeader
// is what sets w.chunking.
const noLimit int64 = (1 << 63) - 1
// Create new connection from rwc.
-func (srv *Server) newConn(rwc net.Conn) (c *conn, err os.Error) {
+func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
c = new(conn)
c.remoteAddr = rwc.RemoteAddr().String()
c.server = srv
closed bool
}
-func (ecr *expectContinueReader) Read(p []byte) (n int, err os.Error) {
+func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
if ecr.closed {
- return 0, os.NewError("http: Read after Close on request Body")
+ return 0, errors.New("http: Read after Close on request Body")
}
if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked {
ecr.resp.wroteContinue = true
return ecr.readCloser.Read(p)
}
-func (ecr *expectContinueReader) Close() os.Error {
+func (ecr *expectContinueReader) Close() error {
ecr.closed = true
return ecr.readCloser.Close()
}
// It is like time.RFC1123 but hard codes GMT as the time zone.
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
-var errTooLarge = os.NewError("http: request too large")
+var errTooLarge = errors.New("http: request too large")
// Read next request from connection.
-func (c *conn) readRequest() (w *response, err os.Error) {
+func (c *conn) readRequest() (w *response, err error) {
if c.hijacked {
return nil, ErrHijacked
}
var hasCL bool
var contentLength int64
if clenStr := w.header.Get("Content-Length"); clenStr != "" {
- var err os.Error
+ var err error
contentLength, err = strconv.Atoi64(clenStr)
if err == nil {
hasCL = true
return w.status != StatusNotModified && w.req.Method != "HEAD"
}
-func (w *response) Write(data []byte) (n int, err os.Error) {
+func (w *response) Write(data []byte) (n int, err error) {
if w.conn.hijacked {
log.Print("http: response.Write on hijacked connection")
return 0, ErrHijacked
// Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
// and a Hijacker.
-func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err os.Error) {
+func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
if w.conn.hijacked {
return nil, nil, ErrHijacked
}
// creating a new service thread for each. The service threads
// read requests and then call handler to reply to them.
// Handler is typically nil, in which case the DefaultServeMux is used.
-func Serve(l net.Listener, handler Handler) os.Error {
+func Serve(l net.Listener, handler Handler) error {
srv := &Server{Handler: handler}
return srv.Serve(l)
}
// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections. If
// srv.Addr is blank, ":http" is used.
-func (srv *Server) ListenAndServe() os.Error {
+func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
// Serve accepts incoming connections on the Listener l, creating a
// new service thread for each. The service threads read requests and
// then call srv.Handler to reply to them.
-func (srv *Server) Serve(l net.Listener) os.Error {
+func (srv *Server) Serve(l net.Listener) error {
defer l.Close()
for {
rw, e := l.Accept()
// log.Fatal("ListenAndServe: ", err.String())
// }
// }
-func ListenAndServe(addr string, handler Handler) os.Error {
+func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
// }
//
// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
-func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) os.Error {
+func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServeTLS(certFile, keyFile)
}
// of the server's certificate followed by the CA's certificate.
//
// If srv.Addr is blank, ":https" is used.
-func (s *Server) ListenAndServeTLS(certFile, keyFile string) os.Error {
+func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := s.Addr
if addr == "" {
addr = ":https"
NextProtos: []string{"http/1.1"},
}
- var err os.Error
+ var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
// ErrHandlerTimeout is returned on ResponseWriter Write calls
// in handlers which have timed out.
-var ErrHandlerTimeout = os.NewError("http: Handler timeout")
+var ErrHandlerTimeout = errors.New("http: Handler timeout")
type timeoutHandler struct {
handler Handler
return tw.w.Header()
}
-func (tw *timeoutWriter) Write(p []byte) (int, os.Error) {
+func (tw *timeoutWriter) Write(p []byte) (int, error) {
tw.mu.Lock()
timedOut := tw.timedOut
tw.mu.Unlock()
import (
"bytes"
"bufio"
+ "errors"
"fmt"
"io"
"io/ioutil"
- "os"
"strconv"
"strings"
)
Trailer Header
}
-func newTransferWriter(r interface{}) (t *transferWriter, err os.Error) {
+func newTransferWriter(r interface{}) (t *transferWriter, err error) {
t = &transferWriter{}
// Extract relevant fields
return false
}
-func (t *transferWriter) WriteHeader(w io.Writer) (err os.Error) {
+func (t *transferWriter) WriteHeader(w io.Writer) (err error) {
if t.Close {
_, err = io.WriteString(w, "Connection: close\r\n")
if err != nil {
return
}
-func (t *transferWriter) WriteBody(w io.Writer) (err os.Error) {
+func (t *transferWriter) WriteBody(w io.Writer) (err error) {
var ncopy int64
// Write body
}
// msg is *Request or *Response.
-func readTransfer(msg interface{}, r *bufio.Reader) (err os.Error) {
+func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
t := &transferReader{}
// Unify input
func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
// Sanitize transfer encoding
-func fixTransferEncoding(requestMethod string, header Header) ([]string, os.Error) {
+func fixTransferEncoding(requestMethod string, header Header) ([]string, error) {
raw, present := header["Transfer-Encoding"]
if !present {
return nil, nil
// Determine the expected body length, using RFC 2616 Section 4.4. This
// function is not a method, because ultimately it should be shared by
// ReadResponse and ReadRequest.
-func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, os.Error) {
+func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
// Logic based on response type or status
if noBodyExpected(requestMethod) {
}
// Parse the trailer header
-func fixTrailer(header Header, te []string) (Header, os.Error) {
+func fixTrailer(header Header, te []string) (Header, error) {
raw := header.Get("Trailer")
if raw == "" {
return nil, nil
// the body has been closed. This typically happens when the body is
// read after an HTTP Handler calls WriteHeader or Write on its
// ResponseWriter.
-var ErrBodyReadAfterClose = os.NewError("http: invalid Read on closed request Body")
+var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed request Body")
-func (b *body) Read(p []byte) (n int, err os.Error) {
+func (b *body) Read(p []byte) (n int, err error) {
if b.closed {
return 0, ErrBodyReadAfterClose
}
return b.Reader.Read(p)
}
-func (b *body) Close() os.Error {
+func (b *body) Close() error {
if b.closed {
return nil
}
"compress/gzip"
"crypto/tls"
"encoding/base64"
+ "errors"
"fmt"
"io"
"io/ioutil"
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
// If Proxy is nil or returns a nil *URL, no proxy is used.
- Proxy func(*Request) (*url.URL, os.Error)
+ Proxy func(*Request) (*url.URL, error)
// Dial specifies the dial function for creating TCP
// connections.
// If Dial is nil, net.Dial is used.
- Dial func(net, addr string) (c net.Conn, err os.Error)
+ Dial func(net, addr string) (c net.Conn, err error)
// TLSClientConfig specifies the TLS configuration to use with
// tls.Client. If nil, the default configuration is used.
// given request, as indicated by the environment variables
// $HTTP_PROXY and $NO_PROXY (or $http_proxy and $no_proxy).
// Either URL or an error is returned.
-func ProxyFromEnvironment(req *Request) (*url.URL, os.Error) {
+func ProxyFromEnvironment(req *Request) (*url.URL, error) {
proxy := getenvEitherCase("HTTP_PROXY")
if proxy == "" {
return nil, nil
}
proxyURL, err := url.ParseRequest(proxy)
if err != nil {
- return nil, os.NewError("invalid proxy address")
+ return nil, errors.New("invalid proxy address")
}
if proxyURL.Host == "" {
proxyURL, err = url.ParseRequest("http://" + proxy)
if err != nil {
- return nil, os.NewError("invalid proxy address")
+ return nil, errors.New("invalid proxy address")
}
}
return proxyURL, nil
// ProxyURL returns a proxy function (for use in a Transport)
// that always returns the same URL.
-func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, os.Error) {
- return func(*Request) (*url.URL, os.Error) {
+func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
+ return func(*Request) (*url.URL, error) {
return fixedURL, nil
}
}
}
// RoundTrip implements the RoundTripper interface.
-func (t *Transport) RoundTrip(req *Request) (resp *Response, err os.Error) {
+func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) {
if req.URL == nil {
- return nil, os.NewError("http: nil Request.URL")
+ return nil, errors.New("http: nil Request.URL")
}
if req.Header == nil {
- return nil, os.NewError("http: nil Request.Header")
+ return nil, errors.New("http: nil Request.Header")
}
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
t.lk.Lock()
return os.Getenv(strings.ToLower(k))
}
-func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, os.Error) {
+func (t *Transport) connectMethodForRequest(treq *transportRequest) (*connectMethod, error) {
cm := &connectMethod{
targetScheme: treq.URL.Scheme,
targetAddr: canonicalAddr(treq.URL),
}
if t.Proxy != nil {
- var err os.Error
+ var err error
cm.proxyURL, err = t.Proxy(treq.Request)
if err != nil {
return nil, err
return
}
-func (t *Transport) dial(network, addr string) (c net.Conn, err os.Error) {
+func (t *Transport) dial(network, addr string) (c net.Conn, err error) {
if t.Dial != nil {
return t.Dial(network, addr)
}
// specified in the connectMethod. This includes doing a proxy CONNECT
// and/or setting up TLS. If this doesn't return an error, the persistConn
// is ready to write requests to.
-func (t *Transport) getConn(cm *connectMethod) (*persistConn, os.Error) {
+func (t *Transport) getConn(cm *connectMethod) (*persistConn, error) {
if pc := t.getIdleConn(cm); pc != nil {
return pc, nil
}
if resp.StatusCode != 200 {
f := strings.SplitN(resp.Status, " ", 2)
conn.Close()
- return nil, os.NewError(f[1])
+ return nil, errors.New(f[1])
}
}
return pc.numExpectedResponses > 0
}
-var remoteSideClosedFunc func(os.Error) bool // or nil to use default
+var remoteSideClosedFunc func(error) bool // or nil to use default
-func remoteSideClosed(err os.Error) bool {
- if err == os.EOF || err == os.EINVAL {
+func remoteSideClosed(err error) bool {
+ if err == io.EOF || err == os.EINVAL {
return true
}
if remoteSideClosedFunc != nil {
}
rc := <-pc.reqch
- resp, err := pc.cc.readUsing(rc.req, func(buf *bufio.Reader, forReq *Request) (*Response, os.Error) {
+ resp, err := pc.cc.readUsing(rc.req, func(buf *bufio.Reader, forReq *Request) (*Response, error) {
resp, err := ReadResponse(buf, forReq)
if err != nil || resp.ContentLength == 0 {
return resp, err
type responseAndError struct {
res *Response
- err os.Error
+ err error
}
type requestAndChan struct {
addedGzip bool
}
-func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err os.Error) {
+func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) {
if pc.mutateHeaderFunc != nil {
pc.mutateHeaderFunc(req.extraHeaders())
}
pc.numExpectedResponses++
pc.lk.Unlock()
- pc.cc.writeReq = func(r *Request, w io.Writer) os.Error {
+ pc.cc.writeReq = func(r *Request, w io.Writer) error {
return r.write(w, pc.isProxy, req.extra)
}
isClosed bool
}
-func (es *bodyEOFSignal) Read(p []byte) (n int, err os.Error) {
+func (es *bodyEOFSignal) Read(p []byte) (n int, err error) {
n, err = es.body.Read(p)
if es.isClosed && n > 0 {
panic("http: unexpected bodyEOFSignal Read after Close; see issue 1725")
}
- if err == os.EOF && es.fn != nil {
+ if err == io.EOF && es.fn != nil {
es.fn()
es.fn = nil
}
return
}
-func (es *bodyEOFSignal) Close() (err os.Error) {
+func (es *bodyEOFSignal) Close() (err error) {
if es.isClosed {
return nil
}
io.Closer
}
-func (r *readFirstCloseBoth) Close() os.Error {
+func (r *readFirstCloseBoth) Close() error {
if err := r.ReadCloser.Close(); err != nil {
r.Closer.Close()
return err
io.ReadCloser
}
-func (d *discardOnCloseReadCloser) Close() os.Error {
+func (d *discardOnCloseReadCloser) Close() error {
io.Copy(ioutil.Discard, d.ReadCloser) // ignore errors; likely invalid or already closed
return d.ReadCloser.Close()
}
"http/httptest"
"io"
"io/ioutil"
- "os"
"strconv"
"strings"
"testing"
fetch := func(n int) string {
req := new(Request)
- var err os.Error
+ var err error
req.URL, err = url.Parse(ts.URL + fmt.Sprintf("/?close=%v", connectionClose))
if err != nil {
t.Fatalf("URL parse error: %v", err)
fetch := func(n int) string {
req := new(Request)
- var err os.Error
+ var err error
req.URL, err = url.Parse(ts.URL)
if err != nil {
t.Fatalf("URL parse error: %v", err)
type fooProto struct{}
-func (fooProto) RoundTrip(req *Request) (*Response, os.Error) {
+func (fooProto) RoundTrip(req *Request) (*Response, error) {
res := &Response{
Status: "200 OK",
StatusCode: 200,
)
func init() {
- remoteSideClosedFunc = func(err os.Error) (out bool) {
+ remoteSideClosedFunc = func(err error) (out bool) {
op, ok := err.(*net.OpError)
- if ok && op.Op == "WSARecv" && op.Net == "tcp" && op.Error == os.Errno(10058) {
+ if ok && op.Op == "WSARecv" && op.Net == "tcp" && op.Err == os.Errno(10058) {
// TODO(bradfitz): find the symbol for 10058
return true
}
package bmp
import (
+ "errors"
"image/color"
"image"
"io"
- "os"
)
// ErrUnsupported means that the input BMP image uses a valid but unsupported
// feature.
-var ErrUnsupported = os.NewError("bmp: unsupported BMP image")
+var ErrUnsupported = errors.New("bmp: unsupported BMP image")
func readUint16(b []byte) uint16 {
return uint16(b[0]) | uint16(b[1])<<8
}
// decodePaletted reads an 8 bit-per-pixel BMP image from r.
-func decodePaletted(r io.Reader, c image.Config) (image.Image, os.Error) {
+func decodePaletted(r io.Reader, c image.Config) (image.Image, error) {
var tmp [4]byte
paletted := image.NewPaletted(image.Rect(0, 0, c.Width, c.Height), c.ColorModel.(color.Palette))
// BMP images are stored bottom-up rather than top-down.
}
// decodeRGBA reads a 24 bit-per-pixel BMP image from r.
-func decodeRGBA(r io.Reader, c image.Config) (image.Image, os.Error) {
+func decodeRGBA(r io.Reader, c image.Config) (image.Image, error) {
rgba := image.NewRGBA(image.Rect(0, 0, c.Width, c.Height))
// There are 3 bytes per pixel, and each row is 4-byte aligned.
b := make([]byte, (3*c.Width+3)&^3)
// Decode reads a BMP image from r and returns it as an image.Image.
// Limitation: The file must be 8 or 24 bits per pixel.
-func Decode(r io.Reader) (image.Image, os.Error) {
+func Decode(r io.Reader) (image.Image, error) {
c, err := DecodeConfig(r)
if err != nil {
return nil, err
// DecodeConfig returns the color model and dimensions of a BMP image without
// decoding the entire image.
// Limitation: The file must be 8 or 24 bits per pixel.
-func DecodeConfig(r io.Reader) (config image.Config, err os.Error) {
+func DecodeConfig(r io.Reader) (config image.Config, err error) {
// We only support those BMP images that are a BITMAPFILEHEADER
// immediately followed by a BITMAPINFOHEADER.
const (
return
}
if string(b[:2]) != "BM" {
- err = os.NewError("bmp: invalid format")
+ err = errors.New("bmp: invalid format")
return
}
offset := readUint32(b[10:14])
{"testdata/video-005.gray.png", "testdata/video-005.gray.png", 0},
}
-func decode(filename string) (image.Image, string, os.Error) {
+func decode(filename string) (image.Image, string, error) {
f, err := os.Open(filename)
if err != nil {
return nil, "", err
return image.Decode(bufio.NewReader(f))
}
-func decodeConfig(filename string) (image.Config, string, os.Error) {
+func decodeConfig(filename string) (image.Config, string, error) {
f, err := os.Open(filename)
if err != nil {
return image.Config{}, "", err
for _, it := range imageTests {
g := golden[it.goldenFilename]
if g == nil {
- var err os.Error
+ var err error
g, _, err = decode(it.goldenFilename)
if err != nil {
t.Errorf("%s: %v", it.goldenFilename, err)
import (
"bufio"
+ "errors"
"io"
- "os"
)
// An UnknownFormatErr indicates that decoding encountered an unknown format.
-var UnknownFormatErr = os.NewError("image: unknown format")
+var UnknownFormatErr = errors.New("image: unknown format")
// A format holds an image format's name, magic header and how to decode it.
type format struct {
name, magic string
- decode func(io.Reader) (Image, os.Error)
- decodeConfig func(io.Reader) (Config, os.Error)
+ decode func(io.Reader) (Image, error)
+ decodeConfig func(io.Reader) (Config, error)
}
// Formats is the list of registered formats.
// string can contain "?" wildcards that each match any one byte.
// Decode is the function that decodes the encoded image.
// DecodeConfig is the function that decodes just its configuration.
-func RegisterFormat(name, magic string, decode func(io.Reader) (Image, os.Error), decodeConfig func(io.Reader) (Config, os.Error)) {
+func RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error)) {
formats = append(formats, format{name, magic, decode, decodeConfig})
}
// A reader is an io.Reader that can also peek ahead.
type reader interface {
io.Reader
- Peek(int) ([]byte, os.Error)
+ Peek(int) ([]byte, error)
}
// AsReader converts an io.Reader to a reader.
// The string returned is the format name used during format registration.
// Format registration is typically done by the init method of the codec-
// specific package.
-func Decode(r io.Reader) (Image, string, os.Error) {
+func Decode(r io.Reader) (Image, string, error) {
rr := asReader(r)
f := sniff(rr)
if f.decode == nil {
// been encoded in a registered format. The string returned is the format name
// used during format registration. Format registration is typically done by
// the init method of the codec-specific package.
-func DecodeConfig(r io.Reader) (Config, string, os.Error) {
+func DecodeConfig(r io.Reader) (Config, string, error) {
rr := asReader(r)
f := sniff(rr)
if f.decodeConfig == nil {
import (
"bufio"
"compress/lzw"
+ "errors"
"fmt"
"image"
"image/color"
"io"
- "os"
)
// If the io.Reader does not also have ReadByte, then decode will introduce its own buffering.
tmp [256]byte
}
-func (b *blockReader) Read(p []byte) (int, os.Error) {
+func (b *blockReader) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
return 0, err
}
if blockLen == 0 {
- return 0, os.EOF
+ return 0, io.EOF
}
b.slice = b.tmp[0:blockLen]
if _, err = io.ReadFull(b.r, b.slice); err != nil {
}
// decode reads a GIF image from r and stores the result in d.
-func (d *decoder) decode(r io.Reader, configOnly bool) os.Error {
+func (d *decoder) decode(r io.Reader, configOnly bool) error {
// Add buffering if r does not provide ReadByte.
if rr, ok := r.(reader); ok {
d.r = rr
for err == nil {
var c byte
c, err = d.r.ReadByte()
- if err == os.EOF {
+ if err == io.EOF {
break
}
switch c {
return err
}
if c != 0 {
- return os.NewError("gif: extra data after image")
+ return errors.New("gif: extra data after image")
}
// Undo the interlacing if necessary.
return nil
}
-func (d *decoder) readHeaderAndScreenDescriptor() os.Error {
+func (d *decoder) readHeaderAndScreenDescriptor() error {
_, err := io.ReadFull(d.r, d.tmp[0:13])
if err != nil {
return err
return nil
}
-func (d *decoder) readColorMap() (color.Palette, os.Error) {
+func (d *decoder) readColorMap() (color.Palette, error) {
if d.pixelSize > 8 {
return nil, fmt.Errorf("gif: can't handle %d bits per pixel", d.pixelSize)
}
return colorMap, nil
}
-func (d *decoder) readExtension() os.Error {
+func (d *decoder) readExtension() error {
extension, err := d.r.ReadByte()
if err != nil {
return err
panic("unreachable")
}
-func (d *decoder) readGraphicControl() os.Error {
+func (d *decoder) readGraphicControl() error {
if _, err := io.ReadFull(d.r, d.tmp[0:6]); err != nil {
return fmt.Errorf("gif: can't read graphic control: %s", err)
}
}
}
-func (d *decoder) newImageFromDescriptor() (*image.Paletted, os.Error) {
+func (d *decoder) newImageFromDescriptor() (*image.Paletted, error) {
if _, err := io.ReadFull(d.r, d.tmp[0:9]); err != nil {
return nil, fmt.Errorf("gif: can't read image descriptor: %s", err)
}
return image.NewPaletted(image.Rect(left, top, left+width, top+height), nil), nil
}
-func (d *decoder) readBlock() (int, os.Error) {
+func (d *decoder) readBlock() (int, error) {
n, err := d.r.ReadByte()
if n == 0 || err != nil {
return 0, err
// Decode reads a GIF image from r and returns the first embedded
// image as an image.Image.
-func Decode(r io.Reader) (image.Image, os.Error) {
+func Decode(r io.Reader) (image.Image, error) {
var d decoder
if err := d.decode(r, false); err != nil {
return nil, err
// DecodeAll reads a GIF image from r and returns the sequential frames
// and timing information.
-func DecodeAll(r io.Reader) (*GIF, os.Error) {
+func DecodeAll(r io.Reader) (*GIF, error) {
var d decoder
if err := d.decode(r, false); err != nil {
return nil, err
// DecodeConfig returns the global color model and dimensions of a GIF image
// without decoding the entire image.
-func DecodeConfig(r io.Reader) (image.Config, os.Error) {
+func DecodeConfig(r io.Reader) (image.Config, error) {
var d decoder
if err := d.decode(r, true); err != nil {
return image.Config{}, err
package jpeg
-import (
- "io"
- "os"
-)
+import "io"
// Each code is at most 16 bits long.
const maxCodeLength = 16
}
// Reads bytes from the io.Reader to ensure that bits.n is at least n.
-func (d *decoder) ensureNBits(n int) os.Error {
+func (d *decoder) ensureNBits(n int) error {
for d.b.n < n {
c, err := d.r.ReadByte()
if err != nil {
}
// The composition of RECEIVE and EXTEND, specified in section F.2.2.1.
-func (d *decoder) receiveExtend(t uint8) (int, os.Error) {
+func (d *decoder) receiveExtend(t uint8) (int, error) {
err := d.ensureNBits(int(t))
if err != nil {
return 0, err
// Processes a Define Huffman Table marker, and initializes a huffman struct from its contents.
// Specified in section B.2.4.2.
-func (d *decoder) processDHT(n int) os.Error {
+func (d *decoder) processDHT(n int) error {
for n > 0 {
if n < 17 {
return FormatError("DHT has wrong length")
// Returns the next Huffman-coded value from the bit stream, decoded according to h.
// TODO(nigeltao): This decoding algorithm is simple, but slow. A lookahead table, instead of always
// peeling off only 1 bit at at time, ought to be faster.
-func (d *decoder) decodeHuffman(h *huffman) (uint8, os.Error) {
+func (d *decoder) decodeHuffman(h *huffman) (uint8, error) {
if h.length == 0 {
return 0, FormatError("uninitialized Huffman table")
}
"image/color"
"image/ycbcr"
"io"
- "os"
)
// TODO(nigeltao): fix up the doc comment style so that sentences start with
// A FormatError reports that the input is not a valid JPEG.
type FormatError string
-func (e FormatError) String() string { return "invalid JPEG format: " + string(e) }
+func (e FormatError) Error() string { return "invalid JPEG format: " + string(e) }
// An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.
type UnsupportedError string
-func (e UnsupportedError) String() string { return "unsupported JPEG feature: " + string(e) }
+func (e UnsupportedError) Error() string { return "unsupported JPEG feature: " + string(e) }
// Component specification, specified in section B.2.2.
type component struct {
// If the passed in io.Reader does not also have ReadByte, then Decode will introduce its own buffering.
type Reader interface {
io.Reader
- ReadByte() (c byte, err os.Error)
+ ReadByte() (c byte, err error)
}
type decoder struct {
}
// Reads and ignores the next n bytes.
-func (d *decoder) ignore(n int) os.Error {
+func (d *decoder) ignore(n int) error {
for n > 0 {
m := len(d.tmp)
if m > n {
}
// Specified in section B.2.2.
-func (d *decoder) processSOF(n int) os.Error {
+func (d *decoder) processSOF(n int) error {
switch n {
case 6 + 3*nGrayComponent:
d.nComp = nGrayComponent
}
// Specified in section B.2.4.1.
-func (d *decoder) processDQT(n int) os.Error {
+func (d *decoder) processDQT(n int) error {
const qtLength = 1 + blockSize
for ; n >= qtLength; n -= qtLength {
_, err := io.ReadFull(d.r, d.tmp[0:qtLength])
}
// Specified in section B.2.3.
-func (d *decoder) processSOS(n int) os.Error {
+func (d *decoder) processSOS(n int) error {
if d.nComp == 0 {
return FormatError("missing SOF marker")
}
}
// Specified in section B.2.4.4.
-func (d *decoder) processDRI(n int) os.Error {
+func (d *decoder) processDRI(n int) error {
if n != 2 {
return FormatError("DRI has wrong length")
}
}
// decode reads a JPEG image from r and returns it as an image.Image.
-func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, os.Error) {
+func (d *decoder) decode(r io.Reader, configOnly bool) (image.Image, error) {
if rr, ok := r.(Reader); ok {
d.r = rr
} else {
}
// Decode reads a JPEG image from r and returns it as an image.Image.
-func Decode(r io.Reader) (image.Image, os.Error) {
+func Decode(r io.Reader) (image.Image, error) {
var d decoder
return d.decode(r, false)
}
// DecodeConfig returns the color model and dimensions of a JPEG image without
// decoding the entire image.
-func DecodeConfig(r io.Reader) (image.Config, os.Error) {
+func DecodeConfig(r io.Reader) (image.Config, error) {
var d decoder
if _, err := d.decode(r, true); err != nil {
return image.Config{}, err
import (
"bufio"
+ "errors"
"image"
"image/ycbcr"
"io"
- "os"
)
// min returns the minimum of two integers.
// writer is a buffered writer.
type writer interface {
- Flush() os.Error
- Write([]byte) (int, os.Error)
- WriteByte(byte) os.Error
+ Flush() error
+ Write([]byte) (int, error)
+ WriteByte(byte) error
}
// encoder encodes an image to the JPEG format.
// w is the writer to write to. err is the first error encountered during
// writing. All attempted writes after the first error become no-ops.
w writer
- err os.Error
+ err error
// buf is a scratch buffer.
buf [16]byte
// bits and nBits are accumulated bits to write to w.
// Encode writes the Image m to w in JPEG 4:2:0 baseline format with the given
// options. Default parameters are used if a nil *Options is passed.
-func Encode(w io.Writer, m image.Image, o *Options) os.Error {
+func Encode(w io.Writer, m image.Image, o *Options) error {
b := m.Bounds()
if b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {
- return os.NewError("jpeg: image is too large to encode")
+ return errors.New("jpeg: image is too large to encode")
}
var e encoder
if ww, ok := w.(writer); ok {
return d
}
-func readPng(filename string) (image.Image, os.Error) {
+func readPng(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
"image"
"image/color"
"io"
- "os"
)
// Color type, as per the PNG spec.
// A FormatError reports that the input is not a valid PNG.
type FormatError string
-func (e FormatError) String() string { return "png: invalid format: " + string(e) }
+func (e FormatError) Error() string { return "png: invalid format: " + string(e) }
var chunkOrderError = FormatError("chunk out of order")
// An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.
type UnsupportedError string
-func (e UnsupportedError) String() string { return "png: unsupported feature: " + string(e) }
+func (e UnsupportedError) Error() string { return "png: unsupported feature: " + string(e) }
func abs(x int) int {
if x < 0 {
return b
}
-func (d *decoder) parseIHDR(length uint32) os.Error {
+func (d *decoder) parseIHDR(length uint32) error {
if length != 13 {
return FormatError("bad IHDR length")
}
return d.verifyChecksum()
}
-func (d *decoder) parsePLTE(length uint32) os.Error {
+func (d *decoder) parsePLTE(length uint32) error {
np := int(length / 3) // The number of palette entries.
if length%3 != 0 || np <= 0 || np > 256 || np > 1<<uint(d.depth) {
return FormatError("bad PLTE length")
return d.verifyChecksum()
}
-func (d *decoder) parsetRNS(length uint32) os.Error {
+func (d *decoder) parsetRNS(length uint32) error {
if length > 256 {
return FormatError("bad tRNS length")
}
// immediately before the first Read call is that d.r is positioned between the
// first IDAT and xxx, and the decoder state immediately after the last Read
// call is that d.r is positioned between yy and crc1.
-func (d *decoder) Read(p []byte) (int, os.Error) {
+func (d *decoder) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
}
// decode decodes the IDAT data into an image.
-func (d *decoder) decode() (image.Image, os.Error) {
+func (d *decoder) decode() (image.Image, error) {
r, err := zlib.NewReader(d)
if err != nil {
return nil, err
// Check for EOF, to verify the zlib checksum.
n, err := r.Read(pr[:1])
- if err != os.EOF {
- return nil, FormatError(err.String())
+ if err != io.EOF {
+ return nil, FormatError(err.Error())
}
if n != 0 || d.idatLength != 0 {
return nil, FormatError("too much pixel data")
return img, nil
}
-func (d *decoder) parseIDAT(length uint32) (err os.Error) {
+func (d *decoder) parseIDAT(length uint32) (err error) {
d.idatLength = length
d.img, err = d.decode()
if err != nil {
return d.verifyChecksum()
}
-func (d *decoder) parseIEND(length uint32) os.Error {
+func (d *decoder) parseIEND(length uint32) error {
if length != 0 {
return FormatError("bad IEND length")
}
return d.verifyChecksum()
}
-func (d *decoder) parseChunk() os.Error {
+func (d *decoder) parseChunk() error {
// Read the length and chunk type.
n, err := io.ReadFull(d.r, d.tmp[:8])
if err != nil {
return d.verifyChecksum()
}
-func (d *decoder) verifyChecksum() os.Error {
+func (d *decoder) verifyChecksum() error {
if _, err := io.ReadFull(d.r, d.tmp[:4]); err != nil {
return err
}
return nil
}
-func (d *decoder) checkHeader() os.Error {
+func (d *decoder) checkHeader() error {
_, err := io.ReadFull(d.r, d.tmp[:len(pngHeader)])
if err != nil {
return err
// Decode reads a PNG image from r and returns it as an image.Image.
// The type of Image returned depends on the PNG contents.
-func Decode(r io.Reader) (image.Image, os.Error) {
+func Decode(r io.Reader) (image.Image, error) {
d := &decoder{
r: r,
crc: crc32.NewIEEE(),
}
if err := d.checkHeader(); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
for d.stage != dsSeenIEND {
if err := d.parseChunk(); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
// DecodeConfig returns the color model and dimensions of a PNG image without
// decoding the entire image.
-func DecodeConfig(r io.Reader) (image.Config, os.Error) {
+func DecodeConfig(r io.Reader) (image.Config, error) {
d := &decoder{
r: r,
crc: crc32.NewIEEE(),
}
if err := d.checkHeader(); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return image.Config{}, err
}
for {
if err := d.parseChunk(); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return image.Config{}, err
"basn6a16",
}
-func readPNG(filename string) (image.Image, os.Error) {
+func readPNG(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
for {
ps, perr := pb.ReadString('\n')
ss, serr := sb.ReadString('\n')
- if perr == os.EOF && serr == os.EOF {
+ if perr == io.EOF && serr == io.EOF {
break
}
if perr != nil {
t.Errorf("decoding %s: missing error", tt.file)
continue
}
- if !strings.Contains(err.String(), tt.err) {
+ if !strings.Contains(err.Error(), tt.err) {
t.Errorf("decoding %s: %s, want %s", tt.file, err, tt.err)
}
if img != nil {
"image"
"image/color"
"io"
- "os"
"strconv"
)
w io.Writer
m image.Image
cb int
- err os.Error
+ err error
header [8]byte
footer [4]byte
tmp [3 * 256]byte
//
// This method should only be called from writeIDATs (via writeImage).
// No other code should treat an encoder as an io.Writer.
-func (e *encoder) Write(b []byte) (int, os.Error) {
+func (e *encoder) Write(b []byte) (int, error) {
e.writeChunk(b, "IDAT")
if e.err != nil {
return 0, e.err
return filter
}
-func writeImage(w io.Writer, m image.Image, cb int) os.Error {
+func writeImage(w io.Writer, m image.Image, cb int) error {
zw, err := zlib.NewWriter(w)
if err != nil {
return err
// Encode writes the Image m to w in PNG format. Any Image may be encoded, but
// images that are not image.NRGBA might be encoded lossily.
-func Encode(w io.Writer, m image.Image) os.Error {
+func Encode(w io.Writer, m image.Image) error {
// Obviously, negative widths and heights are invalid. Furthermore, the PNG
// spec section 11.2.2 says that zero is invalid. Excessively large images are
// also rejected.
"image"
"image/color"
"io/ioutil"
- "os"
"testing"
)
-func diff(m0, m1 image.Image) os.Error {
+func diff(m0, m1 image.Image) error {
b0, b1 := m0.Bounds(), m1.Bounds()
if !b0.Size().Eq(b1.Size()) {
return fmt.Errorf("dimensions differ: %v vs %v", b0, b1)
return nil
}
-func encodeDecode(m image.Image) (image.Image, os.Error) {
+func encodeDecode(m image.Image) (image.Image, error) {
b := bytes.NewBuffer(nil)
err := Encode(b, m)
if err != nil {
buf []byte
}
-func (b *buffer) ReadAt(p []byte, off int64) (int, os.Error) {
+func (b *buffer) ReadAt(p []byte, off int64) (int, error) {
o := int(off)
end := o + len(p)
if int64(end) != off+int64(len(p)) {
package tiff
import (
- "os"
+ "io"
"strings"
"testing"
)
n int
off int64
s string
- err os.Error
+ err error
}{
{2, 0, "ab", nil},
{6, 0, "abcdef", nil},
{3, 3, "def", nil},
- {3, 5, "f", os.EOF},
- {3, 6, "", os.EOF},
+ {3, 5, "f", io.EOF},
+ {3, 6, "", io.EOF},
}
func TestReadAt(t *testing.T) {
import (
"bufio"
"io"
- "os"
)
type byteReader interface {
//
// The PackBits compression format is described in section 9 (p. 42)
// of the TIFF spec.
-func unpackBits(r io.Reader) ([]byte, os.Error) {
+func unpackBits(r io.Reader) ([]byte, error) {
buf := make([]byte, 128)
dst := make([]byte, 0, 1024)
br, ok := r.(byteReader)
for {
b, err := br.ReadByte()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
return dst, nil
}
return nil, err
"image/color"
"io"
"io/ioutil"
- "os"
)
// A FormatError reports that the input is not a valid TIFF image.
type FormatError string
-func (e FormatError) String() string {
+func (e FormatError) Error() string {
return "tiff: invalid format: " + string(e)
}
// unimplemented feature.
type UnsupportedError string
-func (e UnsupportedError) String() string {
+func (e UnsupportedError) Error() string {
return "tiff: unsupported feature: " + string(e)
}
// An InternalError reports that an internal error was encountered.
type InternalError string
-func (e InternalError) String() string {
+func (e InternalError) Error() string {
return "tiff: internal error: " + string(e)
}
// ifdUint decodes the IFD entry in p, which must be of the Byte, Short
// or Long type, and returns the decoded uint values.
-func (d *decoder) ifdUint(p []byte) (u []uint, err os.Error) {
+func (d *decoder) ifdUint(p []byte) (u []uint, err error) {
var raw []byte
datatype := d.byteOrder.Uint16(p[2:4])
count := d.byteOrder.Uint32(p[4:8])
// parseIFD decides whether the the IFD entry in p is "interesting" and
// stows away the data in the decoder.
-func (d *decoder) parseIFD(p []byte) os.Error {
+func (d *decoder) parseIFD(p []byte) error {
tag := d.byteOrder.Uint16(p[0:2])
switch tag {
case tBitsPerSample,
// decode decodes the raw data of an image.
// It reads from d.buf and writes the strip with ymin <= y < ymax into dst.
-func (d *decoder) decode(dst image.Image, ymin, ymax int) os.Error {
+func (d *decoder) decode(dst image.Image, ymin, ymax int) error {
d.off = 0
// Apply horizontal predictor if necessary.
return nil
}
-func newDecoder(r io.Reader) (*decoder, os.Error) {
+func newDecoder(r io.Reader) (*decoder, error) {
d := &decoder{
r: newReaderAt(r),
features: make(map[int][]uint),
// DecodeConfig returns the color model and dimensions of a TIFF image without
// decoding the entire image.
-func DecodeConfig(r io.Reader) (image.Config, os.Error) {
+func DecodeConfig(r io.Reader) (image.Config, error) {
d, err := newDecoder(r)
if err != nil {
return image.Config{}, err
// Decode reads a TIFF image from r and returns it as an image.Image.
// The type of Image returned depends on the contents of the TIFF.
-func Decode(r io.Reader) (img image.Image, err os.Error) {
+func Decode(r io.Reader) (img image.Image, err error) {
d, err := newDecoder(r)
if err != nil {
return
)
// Read makes *buffer implements io.Reader, so that we can pass one to Decode.
-func (*buffer) Read([]byte) (int, os.Error) {
+func (*buffer) Read([]byte) (int, error) {
panic("unimplemented")
}
"bytes"
"encoding/binary"
"io"
- "os"
"regexp"
"sort"
)
}
// writeInt writes an int x to w using buf to buffer the write.
-func writeInt(w io.Writer, buf []byte, x int) os.Error {
+func writeInt(w io.Writer, buf []byte, x int) error {
binary.PutVarint(buf, int64(x))
_, err := w.Write(buf[0:binary.MaxVarintLen64])
return err
}
// readInt reads an int x from r using buf to buffer the read and returns x.
-func readInt(r io.Reader, buf []byte) (int, os.Error) {
+func readInt(r io.Reader, buf []byte) (int, error) {
_, err := io.ReadFull(r, buf[0:binary.MaxVarintLen64]) // ok to continue with error
x, _ := binary.Varint(buf)
return int(x), err
// writeSlice writes data[:n] to w and returns n.
// It uses buf to buffer the write.
-func writeSlice(w io.Writer, buf []byte, data []int) (n int, err os.Error) {
+func writeSlice(w io.Writer, buf []byte, data []int) (n int, err error) {
// encode as many elements as fit into buf
p := binary.MaxVarintLen64
for ; n < len(data) && p+binary.MaxVarintLen64 <= len(buf); n++ {
// readSlice reads data[:n] from r and returns n.
// It uses buf to buffer the read.
-func readSlice(r io.Reader, buf []byte, data []int) (n int, err os.Error) {
+func readSlice(r io.Reader, buf []byte, data []int) (n int, err error) {
// read buffer size
var size int
size, err = readInt(r, buf)
const bufSize = 16 << 10 // reasonable for BenchmarkSaveRestore
// Read reads the index from r into x; x must not be nil.
-func (x *Index) Read(r io.Reader) os.Error {
+func (x *Index) Read(r io.Reader) error {
// buffer for all reads
buf := make([]byte, bufSize)
}
// Write writes the index x to w.
-func (x *Index) Write(w io.Writer) os.Error {
+func (x *Index) Write(w io.Writer) error {
// buffer for all writes
buf := make([]byte, bufSize)
// abstract the functionality, plus some other related primitives.
package io
-import "os"
-
// Error represents an unexpected I/O behavior.
type Error struct {
ErrorString string
}
-func (err *Error) String() string { return err.ErrorString }
+func (err *Error) Error() string { return err.ErrorString }
// ErrShortWrite means that a write accepted fewer bytes than requested
// but failed to return an explicit error.
-var ErrShortWrite os.Error = &Error{"short write"}
+var ErrShortWrite error = &Error{"short write"}
// ErrShortBuffer means that a read required a longer buffer than was provided.
-var ErrShortBuffer os.Error = &Error{"short buffer"}
+var ErrShortBuffer error = &Error{"short buffer"}
+
+// EOF is the error returned by Read when no more input is available.
+// Functions should return EOF only to signal a graceful end of input.
+// If the EOF occurs unexpectedly in a structured data stream,
+// the appropriate error is either ErrUnexpectedEOF or some other error
+// giving more detail.
+var EOF error = &Error{"EOF"}
-// ErrUnexpectedEOF means that os.EOF was encountered in the
+// ErrUnexpectedEOF means that EOF was encountered in the
// middle of reading a fixed-size block or data structure.
-var ErrUnexpectedEOF os.Error = &Error{"unexpected EOF"}
+var ErrUnexpectedEOF error = &Error{"unexpected EOF"}
// Reader is the interface that wraps the basic Read method.
//
// or return the error (and n == 0) from a subsequent call.
// An instance of this general case is that a Reader returning
// a non-zero number of bytes at the end of the input stream may
-// return either err == os.EOF or err == nil. The next Read should
-// return 0, os.EOF regardless.
+// return either err == EOF or err == nil. The next Read should
+// return 0, EOF regardless.
//
// Callers should always process the n > 0 bytes returned before
// considering the error err. Doing so correctly handles I/O errors
// that happen after reading some bytes and also both of the
// allowed EOF behaviors.
type Reader interface {
- Read(p []byte) (n int, err os.Error)
+ Read(p []byte) (n int, err error)
}
// Writer is the interface that wraps the basic Write method.
// and any error encountered that caused the write to stop early.
// Write must return a non-nil error if it returns n < len(p).
type Writer interface {
- Write(p []byte) (n int, err os.Error)
+ Write(p []byte) (n int, err error)
}
// Closer is the interface that wraps the basic Close method.
type Closer interface {
- Close() os.Error
+ Close() error
}
// Seeker is the interface that wraps the basic Seek method.
// relative to the end. Seek returns the new offset and an Error, if
// any.
type Seeker interface {
- Seek(offset int64, whence int) (ret int64, err os.Error)
+ Seek(offset int64, whence int) (ret int64, err error)
}
// ReadWriter is the interface that groups the basic Read and Write methods.
// ReaderFrom is the interface that wraps the ReadFrom method.
type ReaderFrom interface {
- ReadFrom(r Reader) (n int64, err os.Error)
+ ReadFrom(r Reader) (n int64, err error)
}
// WriterTo is the interface that wraps the WriteTo method.
type WriterTo interface {
- WriteTo(w Writer) (n int64, err os.Error)
+ WriteTo(w Writer) (n int64, err error)
}
// ReaderAt is the interface that wraps the basic ReadAt method.
// In this respect ReadAt is different from Read.
//
// If the n = len(p) bytes returned by ReadAt are at the end of the
-// input source, ReadAt may return either err == os.EOF or err == nil.
+// input source, ReadAt may return either err == EOF or err == nil.
//
// If ReadAt is reading from an input source with a seek offset,
// ReadAt should not affect nor be affected by the underlying
// seek offset.
type ReaderAt interface {
- ReadAt(p []byte, off int64) (n int, err os.Error)
+ ReadAt(p []byte, off int64) (n int, err error)
}
// WriterAt is the interface that wraps the basic WriteAt method.
// and any error encountered that caused the write to stop early.
// WriteAt must return a non-nil error if it returns n < len(p).
type WriterAt interface {
- WriteAt(p []byte, off int64) (n int, err os.Error)
+ WriteAt(p []byte, off int64) (n int, err error)
}
// ByteReader is the interface that wraps the ReadByte method.
// ReadByte reads and returns the next byte from the input.
// If no byte is available, err will be set.
type ByteReader interface {
- ReadByte() (c byte, err os.Error)
+ ReadByte() (c byte, err error)
}
// ByteScanner is the interface that adds the UnreadByte method to the
// call to ReadByte.
type ByteScanner interface {
ByteReader
- UnreadByte() os.Error
+ UnreadByte() error
}
// RuneReader is the interface that wraps the ReadRune method.
// and returns the rune and its size in bytes. If no character is
// available, err will be set.
type RuneReader interface {
- ReadRune() (r rune, size int, err os.Error)
+ ReadRune() (r rune, size int, err error)
}
// RuneScanner is the interface that adds the UnreadRune method to the
// call to ReadRune.
type RuneScanner interface {
RuneReader
- UnreadRune() os.Error
+ UnreadRune() error
}
// stringWriter is the interface that wraps the WriteString method.
type stringWriter interface {
- WriteString(s string) (n int, err os.Error)
+ WriteString(s string) (n int, err error)
}
// WriteString writes the contents of the string s to w, which accepts an array of bytes.
-func WriteString(w Writer, s string) (n int, err os.Error) {
+func WriteString(w Writer, s string) (n int, err error) {
if sw, ok := w.(stringWriter); ok {
return sw.WriteString(s)
}
// ReadAtLeast reads from r into buf until it has read at least min bytes.
// It returns the number of bytes copied and an error if fewer bytes were read.
-// The error is os.EOF only if no bytes were read.
+// The error is EOF only if no bytes were read.
// If an EOF happens after reading fewer than min bytes,
// ReadAtLeast returns ErrUnexpectedEOF.
// If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer.
-func ReadAtLeast(r Reader, buf []byte, min int) (n int, err os.Error) {
+func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error) {
if len(buf) < min {
return 0, ErrShortBuffer
}
nn, err = r.Read(buf[n:])
n += nn
}
- if err == os.EOF {
+ if err == EOF {
if n >= min {
err = nil
} else if n > 0 {
// ReadFull reads exactly len(buf) bytes from r into buf.
// It returns the number of bytes copied and an error if fewer bytes were read.
-// The error is os.EOF only if no bytes were read.
+// The error is EOF only if no bytes were read.
// If an EOF happens after reading some but not all the bytes,
// ReadFull returns ErrUnexpectedEOF.
-func ReadFull(r Reader, buf []byte) (n int, err os.Error) {
+func ReadFull(r Reader, buf []byte) (n int, err error) {
return ReadAtLeast(r, buf, len(buf))
}
// It returns the number of bytes copied and the earliest
// error encountered while copying. Because Read can
// return the full amount requested as well as an error
-// (including os.EOF), so can CopyN.
+// (including EOF), so can CopyN.
//
// If dst implements the ReaderFrom interface,
// the copy is implemented by calling dst.ReadFrom(src).
-func CopyN(dst Writer, src Reader, n int64) (written int64, err os.Error) {
+func CopyN(dst Writer, src Reader, n int64) (written int64, err error) {
// If the writer has a ReadFrom method, use it to do the copy.
// Avoids a buffer allocation and a copy.
if rt, ok := dst.(ReaderFrom); ok {
written, err = rt.ReadFrom(LimitReader(src, n))
if written < n && err == nil {
// rt stopped early; must have been EOF.
- err = os.EOF
+ err = EOF
}
return
}
// on src or an error occurs. It returns the number of bytes
// copied and the first error encountered while copying, if any.
//
-// A successful Copy returns err == nil, not err == os.EOF.
+// A successful Copy returns err == nil, not err == EOF.
// Because Copy is defined to read from src until EOF, it does
// not treat an EOF from Read as an error to be reported.
//
// the copy is implemented by calling dst.ReadFrom(src).
// Otherwise, if src implements the WriterTo interface,
// the copy is implemented by calling src.WriteTo(dst).
-func Copy(dst Writer, src Reader) (written int64, err os.Error) {
+func Copy(dst Writer, src Reader) (written int64, err error) {
// If the writer has a ReadFrom method, use it to do the copy.
// Avoids an allocation and a copy.
if rt, ok := dst.(ReaderFrom); ok {
break
}
}
- if er == os.EOF {
+ if er == EOF {
break
}
if er != nil {
}
// LimitReader returns a Reader that reads from r
-// but stops with os.EOF after n bytes.
+// but stops with EOF after n bytes.
// The underlying implementation is a *LimitedReader.
func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }
N int64 // max bytes remaining
}
-func (l *LimitedReader) Read(p []byte) (n int, err os.Error) {
+func (l *LimitedReader) Read(p []byte) (n int, err error) {
if l.N <= 0 {
- return 0, os.EOF
+ return 0, EOF
}
if int64(len(p)) > l.N {
p = p[0:l.N]
}
// NewSectionReader returns a SectionReader that reads from r
-// starting at offset off and stops with os.EOF after n bytes.
+// starting at offset off and stops with EOF after n bytes.
func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader {
return &SectionReader{r, off, off, off + n}
}
limit int64
}
-func (s *SectionReader) Read(p []byte) (n int, err os.Error) {
+func (s *SectionReader) Read(p []byte) (n int, err error) {
if s.off >= s.limit {
- return 0, os.EOF
+ return 0, EOF
}
if max := s.limit - s.off; int64(len(p)) > max {
p = p[0:max]
return
}
-func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err os.Error) {
+var errWhence = &Error{"Seek: invalid whence"}
+var errOffset = &Error{"Seek: invalid offset"}
+
+func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err error) {
switch whence {
default:
- return 0, os.EINVAL
+ return 0, errWhence
case 0:
offset += s.base
case 1:
offset += s.limit
}
if offset < s.base || offset > s.limit {
- return 0, os.EINVAL
+ return 0, errOffset
}
s.off = offset
return offset - s.base, nil
}
-func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err os.Error) {
+func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error) {
if off < 0 || off >= s.limit-s.base {
- return 0, os.EOF
+ return 0, EOF
}
off += s.base
if max := s.limit - off; int64(len(p)) > max {
w Writer
}
-func (t *teeReader) Read(p []byte) (n int, err os.Error) {
+func (t *teeReader) Read(p []byte) (n int, err error) {
n, err = t.r.Read(p)
if n > 0 {
if n, err := t.w.Write(p[:n]); err != nil {
import (
"bytes"
. "io"
- "os"
"strings"
"testing"
)
w Writer
}
-func (w *noReadFrom) Write(p []byte) (n int, err os.Error) {
+func (w *noReadFrom) Write(p []byte) (n int, err error) {
return w.w.Write(p)
}
}
n, err = CopyN(&noReadFrom{b}, strings.NewReader("foo"), 4)
- if n != 3 || err != os.EOF {
+ if n != 3 || err != EOF {
t.Errorf("CopyN(noReadFrom, foo, 4) = %d, %v; want 3, EOF", n, err)
}
}
n, err = CopyN(b, strings.NewReader("foo"), 4) // b has read from
- if n != 3 || err != os.EOF {
+ if n != 3 || err != EOF {
t.Errorf("CopyN(bytes.Buffer, foo, 4) = %d, %v; want 3, EOF", n, err)
}
}
testReadAtLeast(t, &rb)
}
-// A version of bytes.Buffer that returns n > 0, os.EOF on Read
+// A version of bytes.Buffer that returns n > 0, EOF on Read
// when the input is exhausted.
type dataAndEOFBuffer struct {
bytes.Buffer
}
-func (r *dataAndEOFBuffer) Read(p []byte) (n int, err os.Error) {
+func (r *dataAndEOFBuffer) Read(p []byte) (n int, err error) {
n, err = r.Buffer.Read(p)
if n > 0 && r.Buffer.Len() == 0 && err == nil {
- err = os.EOF
+ err = EOF
}
return
}
t.Errorf("expected to have read 2 bytes, got %v", n)
}
n, err = ReadAtLeast(rb, buf, 2)
- if err != os.EOF {
+ if err != EOF {
t.Errorf("expected EOF, got %v", err)
}
if n != 0 {
if !bytes.Equal(wb.Bytes(), src) {
t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
}
- if n, err := r.Read(dst); n != 0 || err != os.EOF {
+ if n, err := r.Read(dst); n != 0 || err != EOF {
t.Errorf("r.Read at EOF = %d, %v want 0, EOF", n, err)
}
rb = bytes.NewBuffer(src)
pr, pw := Pipe()
pr.Close()
r = TeeReader(rb, pw)
- if n, err := ReadFull(r, dst); n != 0 || err != os.EPIPE {
+ if n, err := ReadFull(r, dst); n != 0 || err != ErrClosedPipe {
t.Errorf("closed tee: ReadFull(r, dst) = %d, %v; want 0, EPIPE", n, err)
}
}
// readAll reads from r until an error or EOF and returns the data it read
// from the internal buffer allocated with a specified capacity.
-func readAll(r io.Reader, capacity int64) ([]byte, os.Error) {
+func readAll(r io.Reader, capacity int64) ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
_, err := buf.ReadFrom(r)
return buf.Bytes(), err
}
// ReadAll reads from r until an error or EOF and returns the data it read.
-func ReadAll(r io.Reader) ([]byte, os.Error) {
+func ReadAll(r io.Reader) ([]byte, error) {
return readAll(r, bytes.MinRead)
}
// ReadFile reads the file named by filename and returns the contents.
-func ReadFile(filename string) ([]byte, os.Error) {
+func ReadFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
// WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it with permissions perm;
// otherwise WriteFile truncates it before writing.
-func WriteFile(filename string, data []byte, perm uint32) os.Error {
+func WriteFile(filename string, data []byte, perm uint32) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
// ReadDir reads the directory named by dirname and returns
// a list of sorted directory entries.
-func ReadDir(dirname string) ([]*os.FileInfo, os.Error) {
+func ReadDir(dirname string) ([]*os.FileInfo, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
io.Reader
}
-func (nopCloser) Close() os.Error { return nil }
+func (nopCloser) Close() error { return nil }
// NopCloser returns a ReadCloser with a no-op Close method wrapping
// the provided Reader r.
// ioutil.Discard can avoid doing unnecessary work.
var _ io.ReaderFrom = devNull(0)
-func (devNull) Write(p []byte) (int, os.Error) {
+func (devNull) Write(p []byte) (int, error) {
return len(p), nil
}
var blackHole = make([]byte, 8192)
-func (devNull) ReadFrom(r io.Reader) (n int64, err os.Error) {
+func (devNull) ReadFrom(r io.Reader) (n int64, err error) {
readSize := 0
for {
readSize, err = r.Read(blackHole)
n += int64(readSize)
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
return n, nil
}
return
// will not choose the same file. The caller can use f.Name()
// to find the name of the file. It is the caller's responsibility to
// remove the file when no longer needed.
-func TempFile(dir, prefix string) (f *os.File, err os.Error) {
+func TempFile(dir, prefix string) (f *os.File, err error) {
if dir == "" {
dir = os.TempDir()
}
for i := 0; i < 10000; i++ {
name := filepath.Join(dir, prefix+nextSuffix())
f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
- if pe, ok := err.(*os.PathError); ok && pe.Error == os.EEXIST {
+ if pe, ok := err.(*os.PathError); ok && pe.Err == os.EEXIST {
if nconflict++; nconflict > 10 {
rand = reseed()
}
// Multiple programs calling TempDir simultaneously
// will not choose the same directory. It is the caller's responsibility
// to remove the directory when no longer needed.
-func TempDir(dir, prefix string) (name string, err os.Error) {
+func TempDir(dir, prefix string) (name string, err error) {
if dir == "" {
dir = os.TempDir()
}
for i := 0; i < 10000; i++ {
try := filepath.Join(dir, prefix+nextSuffix())
err = os.Mkdir(try, 0700)
- if pe, ok := err.(*os.PathError); ok && pe.Error == os.EEXIST {
+ if pe, ok := err.(*os.PathError); ok && pe.Err == os.EEXIST {
if nconflict++; nconflict > 10 {
rand = reseed()
}
package io
-import "os"
-
type multiReader struct {
readers []Reader
}
-func (mr *multiReader) Read(p []byte) (n int, err os.Error) {
+func (mr *multiReader) Read(p []byte) (n int, err error) {
for len(mr.readers) > 0 {
n, err = mr.readers[0].Read(p)
- if n > 0 || err != os.EOF {
- if err == os.EOF {
+ if n > 0 || err != EOF {
+ if err == EOF {
// Don't return EOF yet. There may be more bytes
// in the remaining readers.
err = nil
}
mr.readers = mr.readers[1:]
}
- return 0, os.EOF
+ return 0, EOF
}
// MultiReader returns a Reader that's the logical concatenation of
// the provided input readers. They're read sequentially. Once all
-// inputs are drained, Read will return os.EOF.
+// inputs are drained, Read will return EOF.
func MultiReader(readers ...Reader) Reader {
return &multiReader{readers}
}
writers []Writer
}
-func (t *multiWriter) Write(p []byte) (n int, err os.Error) {
+func (t *multiWriter) Write(p []byte) (n int, err error) {
for _, w := range t.writers {
n, err = w.Write(p)
if err != nil {
"bytes"
"crypto/sha1"
"fmt"
- "os"
"strings"
"testing"
)
buf = make([]byte, 20)
tests()
}
- expectRead := func(size int, expected string, eerr os.Error) {
+ expectRead := func(size int, expected string, eerr error) {
nread++
n, gerr := mr.Read(buf[0:size])
if n != len(expected) {
expectRead(2, "fo", nil)
expectRead(5, "o ", nil)
expectRead(5, "bar", nil)
- expectRead(5, "", os.EOF)
+ expectRead(5, "", EOF)
})
withFooBar(func() {
expectRead(4, "foo ", nil)
expectRead(1, "b", nil)
expectRead(3, "ar", nil)
- expectRead(1, "", os.EOF)
+ expectRead(1, "", EOF)
})
withFooBar(func() {
expectRead(5, "foo ", nil)
package io
-import (
- "os"
- "sync"
-)
+import "sync"
+
+// ErrClosedPipe is the error used for read or write operations on a closed pipe.
+var ErrClosedPipe = &Error{"io: read/write on closed pipe"}
type pipeResult struct {
n int
- err os.Error
+ err error
}
// A pipe is the shared pipe structure underlying PipeReader and PipeWriter.
data []byte // data remaining in pending write
rwait sync.Cond // waiting reader
wwait sync.Cond // waiting writer
- rerr os.Error // if reader closed, error to give writes
- werr os.Error // if writer closed, error to give reads
+ rerr error // if reader closed, error to give writes
+ werr error // if writer closed, error to give reads
}
-func (p *pipe) read(b []byte) (n int, err os.Error) {
+func (p *pipe) read(b []byte) (n int, err error) {
// One reader at a time.
p.rl.Lock()
defer p.rl.Unlock()
defer p.l.Unlock()
for {
if p.rerr != nil {
- return 0, os.EINVAL
+ return 0, ErrClosedPipe
}
if p.data != nil {
break
var zero [0]byte
-func (p *pipe) write(b []byte) (n int, err os.Error) {
+func (p *pipe) write(b []byte) (n int, err error) {
// pipe uses nil to mean not available
if b == nil {
b = zero[:]
break
}
if p.werr != nil {
- err = os.EINVAL
+ err = ErrClosedPipe
}
p.wwait.Wait()
}
return
}
-func (p *pipe) rclose(err os.Error) {
+func (p *pipe) rclose(err error) {
if err == nil {
- err = os.EPIPE
+ err = ErrClosedPipe
}
p.l.Lock()
defer p.l.Unlock()
p.wwait.Signal()
}
-func (p *pipe) wclose(err os.Error) {
+func (p *pipe) wclose(err error) {
if err == nil {
- err = os.EOF
+ err = EOF
}
p.l.Lock()
defer p.l.Unlock()
// it reads data from the pipe, blocking until a writer
// arrives or the write end is closed.
// If the write end is closed with an error, that error is
-// returned as err; otherwise err is os.EOF.
-func (r *PipeReader) Read(data []byte) (n int, err os.Error) {
+// returned as err; otherwise err is EOF.
+func (r *PipeReader) Read(data []byte) (n int, err error) {
return r.p.read(data)
}
// Close closes the reader; subsequent writes to the
-// write half of the pipe will return the error os.EPIPE.
-func (r *PipeReader) Close() os.Error {
+// write half of the pipe will return the error ErrClosedPipe.
+func (r *PipeReader) Close() error {
return r.CloseWithError(nil)
}
// CloseWithError closes the reader; subsequent writes
// to the write half of the pipe will return the error err.
-func (r *PipeReader) CloseWithError(err os.Error) os.Error {
+func (r *PipeReader) CloseWithError(err error) error {
r.p.rclose(err)
return nil
}
// it writes data to the pipe, blocking until readers
// have consumed all the data or the read end is closed.
// If the read end is closed with an error, that err is
-// returned as err; otherwise err is os.EPIPE.
-func (w *PipeWriter) Write(data []byte) (n int, err os.Error) {
+// returned as err; otherwise err is ErrClosedPipe.
+func (w *PipeWriter) Write(data []byte) (n int, err error) {
return w.p.write(data)
}
// Close closes the writer; subsequent reads from the
-// read half of the pipe will return no bytes and os.EOF.
-func (w *PipeWriter) Close() os.Error {
+// read half of the pipe will return no bytes and EOF.
+func (w *PipeWriter) Close() error {
return w.CloseWithError(nil)
}
// CloseWithError closes the writer; subsequent reads from the
// read half of the pipe will return no bytes and the error err.
-func (w *PipeWriter) CloseWithError(err os.Error) os.Error {
+func (w *PipeWriter) CloseWithError(err error) error {
w.p.wclose(err)
return nil
}
import (
"fmt"
. "io"
- "os"
"testing"
"time"
)
var buf = make([]byte, 64)
for {
n, err := r.Read(buf)
- if err == os.EOF {
+ if err == EOF {
c <- 0
break
}
type pipeReturn struct {
n int
- err os.Error
+ err error
}
// Test a large write that requires multiple reads to satisfy.
tot := 0
for n := 1; n <= 256; n *= 2 {
nn, err := r.Read(rdat[tot : tot+n])
- if err != nil && err != os.EOF {
+ if err != nil && err != EOF {
t.Fatalf("read: %v", err)
}
expect = 1
} else if n == 256 {
expect = 0
- if err != os.EOF {
+ if err != EOF {
t.Fatalf("read at end: %v", err)
}
}
// Test read after/before writer close.
type closer interface {
- CloseWithError(os.Error) os.Error
- Close() os.Error
+ CloseWithError(error) error
+ Close() error
}
type pipeTest struct {
async bool
- err os.Error
+ err error
closeWithError bool
}
func delayClose(t *testing.T, cl closer, ch chan int, tt pipeTest) {
time.Sleep(1e6) // 1 ms
- var err os.Error
+ var err error
if tt.closeWithError {
err = cl.CloseWithError(tt.err)
} else {
<-c
want := tt.err
if want == nil {
- want = os.EOF
+ want = EOF
}
if err != want {
t.Errorf("read from closed pipe: %v want %v", err, want)
go delayClose(t, r, c, pipeTest{})
n, err := r.Read(make([]byte, 64))
<-c
- if n != 0 || err != os.EINVAL {
- t.Errorf("read from closed pipe: %v, %v want %v, %v", n, err, 0, os.EINVAL)
+ if n != 0 || err != ErrClosedPipe {
+ t.Errorf("read from closed pipe: %v, %v want %v, %v", n, err, 0, ErrClosedPipe)
}
}
<-c
expect := tt.err
if expect == nil {
- expect = os.EPIPE
+ expect = ErrClosedPipe
}
if err != expect {
t.Errorf("write on closed pipe: %v want %v", err, expect)
import (
"encoding/base64"
- "os"
+ "errors"
"reflect"
"runtime"
"strconv"
// If no more serious errors are encountered, Unmarshal returns
// an UnmarshalTypeError describing the earliest such error.
//
-func Unmarshal(data []byte, v interface{}) os.Error {
+func Unmarshal(data []byte, v interface{}) error {
d := new(decodeState).init(data)
// Quick check for well-formedness.
// encoding. UnmarshalJSON must copy the JSON data
// if it wishes to retain the data after returning.
type Unmarshaler interface {
- UnmarshalJSON([]byte) os.Error
+ UnmarshalJSON([]byte) error
}
// An UnmarshalTypeError describes a JSON value that was
Type reflect.Type // type of Go value it could not be assigned to
}
-func (e *UnmarshalTypeError) String() string {
+func (e *UnmarshalTypeError) Error() string {
return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
}
Field reflect.StructField
}
-func (e *UnmarshalFieldError) String() string {
+func (e *UnmarshalFieldError) Error() string {
return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
}
Type reflect.Type
}
-func (e *InvalidUnmarshalError) String() string {
+func (e *InvalidUnmarshalError) Error() string {
if e.Type == nil {
return "json: Unmarshal(nil)"
}
return "json: Unmarshal(nil " + e.Type.String() + ")"
}
-func (d *decodeState) unmarshal(v interface{}) (err os.Error) {
+func (d *decodeState) unmarshal(v interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
- err = r.(os.Error)
+ err = r.(error)
}
}()
off int // read offset in data
scan scanner
nextscan scanner // for calls to nextValue
- savedError os.Error
+ savedError error
tempstr string // scratch space to avoid some allocations
}
// errPhase is used for errors that should not happen unless
// there is a bug in the JSON decoder or something is editing
// the data slice while the decoder executes.
-var errPhase = os.NewError("JSON decoder out of sync - data changing underfoot?")
+var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?")
func (d *decodeState) init(data []byte) *decodeState {
d.data = data
}
// error aborts the decoding by panicking with err.
-func (d *decodeState) error(err os.Error) {
+func (d *decodeState) error(err error) {
panic(err)
}
// saveError saves the first err it is called with,
// for reporting at the end of the unmarshal.
-func (d *decodeState) saveError(err os.Error) {
+func (d *decodeState) saveError(err error) {
if d.savedError == nil {
d.savedError = err
}
import (
"bytes"
- "os"
"reflect"
"strings"
"testing"
T bool
}
-func (u *unmarshaler) UnmarshalJSON(b []byte) os.Error {
+func (u *unmarshaler) UnmarshalJSON(b []byte) error {
*u = unmarshaler{true} // All we need to see that UnmarshalJson is called.
return nil
}
in string
ptr interface{}
out interface{}
- err os.Error
+ err error
}
var unmarshalTests = []unmarshalTest{
import (
"bytes"
"encoding/base64"
- "os"
"reflect"
"runtime"
"sort"
// handle them. Passing cyclic structures to Marshal will result in
// an infinite recursion.
//
-func Marshal(v interface{}) ([]byte, os.Error) {
+func Marshal(v interface{}) ([]byte, error) {
e := &encodeState{}
err := e.marshal(v)
if err != nil {
}
// MarshalIndent is like Marshal but applies Indent to format the output.
-func MarshalIndent(v interface{}, prefix, indent string) ([]byte, os.Error) {
+func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
b, err := Marshal(v)
if err != nil {
return nil, err
}
// MarshalForHTML is like Marshal but applies HTMLEscape to the output.
-func MarshalForHTML(v interface{}) ([]byte, os.Error) {
+func MarshalForHTML(v interface{}) ([]byte, error) {
b, err := Marshal(v)
if err != nil {
return nil, err
// Marshaler is the interface implemented by objects that
// can marshal themselves into valid JSON.
type Marshaler interface {
- MarshalJSON() ([]byte, os.Error)
+ MarshalJSON() ([]byte, error)
}
type UnsupportedTypeError struct {
Type reflect.Type
}
-func (e *UnsupportedTypeError) String() string {
+func (e *UnsupportedTypeError) Error() string {
return "json: unsupported type: " + e.Type.String()
}
S string
}
-func (e *InvalidUTF8Error) String() string {
+func (e *InvalidUTF8Error) Error() string {
return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
}
type MarshalerError struct {
- Type reflect.Type
- Error os.Error
+ Type reflect.Type
+ Err error
}
-func (e *MarshalerError) String() string {
- return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Error.String()
+func (e *MarshalerError) Error() string {
+ return "json: error calling MarshalJSON for type " + e.Type.String() + ": " + e.Err.Error()
}
type interfaceOrPtrValue interface {
bytes.Buffer // accumulated output
}
-func (e *encodeState) marshal(v interface{}) (err os.Error) {
+func (e *encodeState) marshal(v interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
- err = r.(os.Error)
+ err = r.(error)
}
}()
e.reflectValue(reflect.ValueOf(v))
return nil
}
-func (e *encodeState) error(err os.Error) {
+func (e *encodeState) error(err error) {
panic(err)
}
func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) }
func (sv stringValues) get(i int) string { return sv[i].String() }
-func (e *encodeState) string(s string) (int, os.Error) {
+func (e *encodeState) string(s string) (int, error) {
len0 := e.Len()
e.WriteByte('"')
start := 0
package json
-import (
- "bytes"
- "os"
-)
+import "bytes"
// Compact appends to dst the JSON-encoded src with
// insignificant space characters elided.
-func Compact(dst *bytes.Buffer, src []byte) os.Error {
+func Compact(dst *bytes.Buffer, src []byte) error {
origLen := dst.Len()
var scan scanner
scan.reset()
// copies of indent according to the indentation nesting.
// The data appended to dst has no trailing newline, to make it easier
// to embed inside other formatted JSON data.
-func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) os.Error {
+func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
origLen := dst.Len()
var scan scanner
scan.reset()
// This file starts with two simple examples using the scanner
// before diving into the scanner itself.
-import (
- "os"
- "strconv"
-)
+import "strconv"
// checkValid verifies that data is valid JSON-encoded data.
// scan is passed in for use by checkValid to avoid an allocation.
-func checkValid(data []byte, scan *scanner) os.Error {
+func checkValid(data []byte, scan *scanner) error {
scan.reset()
for _, c := range data {
scan.bytes++
// nextValue splits data after the next whole JSON value,
// returning that value and the bytes that follow it as separate slices.
// scan is passed in for use by nextValue to avoid an allocation.
-func nextValue(data []byte, scan *scanner) (value, rest []byte, err os.Error) {
+func nextValue(data []byte, scan *scanner) (value, rest []byte, err error) {
scan.reset()
for i, c := range data {
v := scan.step(scan, int(c))
Offset int64 // error occurred after reading Offset bytes
}
-func (e *SyntaxError) String() string { return e.msg }
+func (e *SyntaxError) Error() string { return e.msg }
// A scanner is a JSON scanning state machine.
// Callers call scan.reset() and then pass bytes in one at a time
parseState []int
// Error that happened, if any.
- err os.Error
+ err error
// 1-byte redo (see undo method)
redoCode int
import (
"bytes"
"math"
- "os"
"rand"
"reflect"
"testing"
type indentErrorTest struct {
in string
- err os.Error
+ err error
}
var indentErrorTests = []indentErrorTest{
package json
import (
+ "errors"
"io"
- "os"
)
// A Decoder reads and decodes JSON objects from an input stream.
buf []byte
d decodeState
scan scanner
- err os.Error
+ err error
}
// NewDecoder returns a new decoder that reads from r.
//
// See the documentation for Unmarshal for details about
// the conversion of JSON into a Go value.
-func (dec *Decoder) Decode(v interface{}) os.Error {
+func (dec *Decoder) Decode(v interface{}) error {
if dec.err != nil {
return dec.err
}
// readValue reads a JSON value into dec.buf.
// It returns the length of the encoding.
-func (dec *Decoder) readValue() (int, os.Error) {
+func (dec *Decoder) readValue() (int, error) {
dec.scan.reset()
scanp := 0
- var err os.Error
+ var err error
Input:
for {
// Look in the buffer for a new value.
// Did the last read have an error?
// Delayed until now to allow buffer scan.
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
if dec.scan.step(&dec.scan, ' ') == scanEnd {
break Input
}
type Encoder struct {
w io.Writer
e encodeState
- err os.Error
+ err error
}
// NewEncoder returns a new encoder that writes to w.
//
// See the documentation for Marshal for details about the
// conversion of Go values to JSON.
-func (enc *Encoder) Encode(v interface{}) os.Error {
+func (enc *Encoder) Encode(v interface{}) error {
if enc.err != nil {
return enc.err
}
type RawMessage []byte
// MarshalJSON returns *m as the JSON encoding of m.
-func (m *RawMessage) MarshalJSON() ([]byte, os.Error) {
+func (m *RawMessage) MarshalJSON() ([]byte, error) {
return *m, nil
}
// UnmarshalJSON sets *m to a copy of data.
-func (m *RawMessage) UnmarshalJSON(data []byte) os.Error {
+func (m *RawMessage) UnmarshalJSON(data []byte) error {
if m == nil {
- return os.NewError("json.RawMessage: UnmarshalJSON on nil pointer")
+ return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[0:0], data...)
return nil
// already a newline. Calldepth is used to recover the PC and is
// provided for generality, although at the moment on all pre-defined
// paths it will be 2.
-func (l *Logger) Output(calldepth int, s string) os.Error {
+func (l *Logger) Output(calldepth int, s string) error {
now := time.Nanoseconds() // get this early.
var file string
var line int
"bufio"
"bytes"
"encoding/base64"
+ "errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/textproto"
- "os"
"strconv"
"strings"
"time"
// ReadMessage reads a message from r.
// The headers are parsed, and the body of the message will be reading from r.
-func ReadMessage(r io.Reader) (msg *Message, err os.Error) {
+func ReadMessage(r io.Reader) (msg *Message, err error) {
tp := textproto.NewReader(bufio.NewReader(r))
hdr, err := tp.ReadMIMEHeader()
}
}
-func parseDate(date string) (*time.Time, os.Error) {
+func parseDate(date string) (*time.Time, error) {
for _, layout := range dateLayouts {
t, err := time.Parse(layout, date)
if err == nil {
return t, nil
}
}
- return nil, os.NewError("mail: header could not be parsed")
+ return nil, errors.New("mail: header could not be parsed")
}
// A Header represents the key-value pairs in a mail message header.
return textproto.MIMEHeader(h).Get(key)
}
-var ErrHeaderNotPresent = os.NewError("mail: header not in message")
+var ErrHeaderNotPresent = errors.New("mail: header not in message")
// Date parses the Date header field.
-func (h Header) Date() (*time.Time, os.Error) {
+func (h Header) Date() (*time.Time, error) {
hdr := h.Get("Date")
if hdr == "" {
return nil, ErrHeaderNotPresent
}
// AddressList parses the named header field as a list of addresses.
-func (h Header) AddressList(key string) ([]*Address, os.Error) {
+func (h Header) AddressList(key string) ([]*Address, error) {
hdr := h.Get(key)
if hdr == "" {
return nil, ErrHeaderNotPresent
return &p
}
-func (p *addrParser) parseAddressList() ([]*Address, os.Error) {
+func (p *addrParser) parseAddressList() ([]*Address, error) {
var list []*Address
for {
p.skipSpace()
break
}
if !p.consume(',') {
- return nil, os.NewError("mail: expected comma")
+ return nil, errors.New("mail: expected comma")
}
}
return list, nil
}
// parseAddress parses a single RFC 5322 address at the start of p.
-func (p *addrParser) parseAddress() (addr *Address, err os.Error) {
+func (p *addrParser) parseAddress() (addr *Address, err error) {
debug.Printf("parseAddress: %q", *p)
p.skipSpace()
if p.empty() {
- return nil, os.NewError("mail: no address")
+ return nil, errors.New("mail: no address")
}
// address = name-addr / addr-spec
// angle-addr = "<" addr-spec ">"
p.skipSpace()
if !p.consume('<') {
- return nil, os.NewError("mail: no angle-addr")
+ return nil, errors.New("mail: no angle-addr")
}
spec, err = p.consumeAddrSpec()
if err != nil {
return nil, err
}
if !p.consume('>') {
- return nil, os.NewError("mail: unclosed angle-addr")
+ return nil, errors.New("mail: unclosed angle-addr")
}
debug.Printf("parseAddress: spec=%q", spec)
}
// consumeAddrSpec parses a single RFC 5322 addr-spec at the start of p.
-func (p *addrParser) consumeAddrSpec() (spec string, err os.Error) {
+func (p *addrParser) consumeAddrSpec() (spec string, err error) {
debug.Printf("consumeAddrSpec: %q", *p)
orig := *p
var localPart string
p.skipSpace()
if p.empty() {
- return "", os.NewError("mail: no addr-spec")
+ return "", errors.New("mail: no addr-spec")
}
if p.peek() == '"' {
// quoted-string
}
if !p.consume('@') {
- return "", os.NewError("mail: missing @ in addr-spec")
+ return "", errors.New("mail: missing @ in addr-spec")
}
// domain = dot-atom / domain-literal
var domain string
p.skipSpace()
if p.empty() {
- return "", os.NewError("mail: no domain in addr-spec")
+ return "", errors.New("mail: no domain in addr-spec")
}
// TODO(dsymonds): Handle domain-literal
domain, err = p.consumeAtom(true)
}
// consumePhrase parses the RFC 5322 phrase at the start of p.
-func (p *addrParser) consumePhrase() (phrase string, err os.Error) {
+func (p *addrParser) consumePhrase() (phrase string, err error) {
debug.Printf("consumePhrase: [%s]", *p)
// phrase = 1*word
var words []string
var word string
p.skipSpace()
if p.empty() {
- return "", os.NewError("mail: missing phrase")
+ return "", errors.New("mail: missing phrase")
}
if p.peek() == '"' {
// quoted-string
// Ignore any error if we got at least one word.
if err != nil && len(words) == 0 {
debug.Printf("consumePhrase: hit err: %v", err)
- return "", os.NewError("mail: missing word in phrase")
+ return "", errors.New("mail: missing word in phrase")
}
phrase = strings.Join(words, " ")
return phrase, nil
}
// consumeQuotedString parses the quoted string at the start of p.
-func (p *addrParser) consumeQuotedString() (qs string, err os.Error) {
+func (p *addrParser) consumeQuotedString() (qs string, err error) {
// Assume first byte is '"'.
i := 1
qsb := make([]byte, 0, 10)
Loop:
for {
if i >= p.len() {
- return "", os.NewError("mail: unclosed quoted-string")
+ return "", errors.New("mail: unclosed quoted-string")
}
switch c := (*p)[i]; {
case c == '"':
break Loop
case c == '\\':
if i+1 == p.len() {
- return "", os.NewError("mail: unclosed quoted-string")
+ return "", errors.New("mail: unclosed quoted-string")
}
qsb = append(qsb, (*p)[i+1])
i += 2
// consumeAtom parses an RFC 5322 atom at the start of p.
// If dot is true, consumeAtom parses an RFC 5322 dot-atom instead.
-func (p *addrParser) consumeAtom(dot bool) (atom string, err os.Error) {
+func (p *addrParser) consumeAtom(dot bool) (atom string, err error) {
if !isAtext(p.peek(), false) {
- return "", os.NewError("mail: invalid string")
+ return "", errors.New("mail: invalid string")
}
i := 1
for ; i < p.len() && isAtext((*p)[i], dot); i++ {
return len(*p)
}
-func decodeRFC2047Word(s string) (string, os.Error) {
+func decodeRFC2047Word(s string) (string, error) {
fields := strings.Split(s, "?")
if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" {
- return "", os.NewError("mail: address not RFC 2047 encoded")
+ return "", errors.New("mail: address not RFC 2047 encoded")
}
charset, enc := strings.ToLower(fields[1]), strings.ToLower(fields[2])
if charset != "iso-8859-1" && charset != "utf-8" {
scratch [2]byte
}
-func (qd qDecoder) Read(p []byte) (n int, err os.Error) {
+func (qd qDecoder) Read(p []byte) (n int, err error) {
// This method writes at most one byte into p.
if len(p) == 0 {
return 0, nil
import (
"bytes"
+ "errors"
"fmt"
- "os"
"strings"
"unicode"
)
return b.String()
}
-func checkMediaTypeDisposition(s string) os.Error {
+func checkMediaTypeDisposition(s string) error {
typ, rest := consumeToken(s)
if typ == "" {
- return os.NewError("mime: no media type")
+ return errors.New("mime: no media type")
}
if rest == "" {
return nil
}
if !strings.HasPrefix(rest, "/") {
- return os.NewError("mime: expected slash after first token")
+ return errors.New("mime: expected slash after first token")
}
subtype, rest := consumeToken(rest[1:])
if subtype == "" {
- return os.NewError("mime: expected token after slash")
+ return errors.New("mime: expected token after slash")
}
if rest != "" {
- return os.NewError("mime: unexpected content after media subtype")
+ return errors.New("mime: unexpected content after media subtype")
}
return nil
}
// to lowercase and trimmed of white space and a non-nil map.
// The returned map, params, maps from the lowercase
// attribute to the attribute value with its case preserved.
-func ParseMediaType(v string) (mediatype string, params map[string]string, err os.Error) {
+func ParseMediaType(v string) (mediatype string, params map[string]string, err error) {
i := strings.Index(v, ";")
if i == -1 {
i = len(v)
return
}
// Parse error.
- return "", nil, os.NewError("mime: invalid media parameter")
+ return "", nil, errors.New("mime: invalid media parameter")
}
pmap := params
}
if _, exists := pmap[key]; exists {
// Duplicate parameter name is bogus.
- return "", nil, os.NewError("mime: duplicate parameter name")
+ return "", nil, errors.New("mime: duplicate parameter name")
}
pmap[key] = value
v = rest
return param, value, rest
}
-func percentHexUnescape(s string) (string, os.Error) {
+func percentHexUnescape(s string) (string, error) {
// Count %, check that they're well-formed.
percents := 0
for i := 0; i < len(s); {
if err == nil {
t.Fatalf("expected an error parsing invalid media type; got type %q, params %#v", mt, params)
}
- if err.String() != "mime: invalid media parameter" {
+ if err.Error() != "mime: invalid media parameter" {
t.Errorf("expected invalid media parameter; got error %q", err)
}
}
import (
"bytes"
+ "errors"
"io"
"io/ioutil"
"net/textproto"
// a Content-Disposition of "form-data".
// It stores up to maxMemory bytes of the file parts in memory
// and the remainder on disk in temporary files.
-func (r *Reader) ReadForm(maxMemory int64) (f *Form, err os.Error) {
+func (r *Reader) ReadForm(maxMemory int64) (f *Form, err error) {
form := &Form{make(map[string][]string), make(map[string][]*FileHeader)}
defer func() {
if err != nil {
maxValueBytes := int64(10 << 20) // 10 MB is a lot of text.
for {
p, err := r.NextPart()
- if err == os.EOF {
+ if err == io.EOF {
break
}
if err != nil {
if filename == "" {
// value, store as string in memory
n, err := io.CopyN(&b, p, maxValueBytes)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
return nil, err
}
maxValueBytes -= n
if maxValueBytes == 0 {
- return nil, os.NewError("multipart: message too large")
+ return nil, errors.New("multipart: message too large")
}
form.Value[name] = append(form.Value[name], b.String())
continue
Header: p.Header,
}
n, err := io.CopyN(&b, p, maxMemory+1)
- if err != nil && err != os.EOF {
+ if err != nil && err != io.EOF {
return nil, err
}
if n > maxMemory {
}
// RemoveAll removes any temporary files associated with a Form.
-func (f *Form) RemoveAll() os.Error {
- var err os.Error
+func (f *Form) RemoveAll() error {
+ var err error
for _, fhs := range f.File {
for _, fh := range fhs {
if fh.tmpfile != "" {
}
// Open opens and returns the FileHeader's associated File.
-func (fh *FileHeader) Open() (File, os.Error) {
+func (fh *FileHeader) Open() (File, error) {
if b := fh.content; b != nil {
r := io.NewSectionReader(sliceReaderAt(b), 0, int64(len(b)))
return sectionReadCloser{r}, nil
*io.SectionReader
}
-func (rc sectionReadCloser) Close() os.Error {
+func (rc sectionReadCloser) Close() error {
return nil
}
type sliceReaderAt []byte
-func (r sliceReaderAt) ReadAt(b []byte, off int64) (int, os.Error) {
+func (r sliceReaderAt) ReadAt(b []byte, off int64) (int, error) {
if int(off) >= len(r) || off < 0 {
return 0, os.EINVAL
}
"io/ioutil"
"mime"
"net/textproto"
- "os"
)
// TODO(bradfitz): inline these once the compiler can inline them in
func (p *Part) parseContentDisposition() {
v := p.Header.Get("Content-Disposition")
- var err os.Error
+ var err error
p.disposition, p.dispositionParams, err = mime.ParseMediaType(v)
if err != nil {
p.dispositionParams = emptyParams
}
}
-func newPart(mr *Reader) (*Part, os.Error) {
+func newPart(mr *Reader) (*Part, error) {
bp := &Part{
Header: make(map[string][]string),
mr: mr,
return bp, nil
}
-func (bp *Part) populateHeaders() os.Error {
+func (bp *Part) populateHeaders() error {
r := textproto.NewReader(bp.mr.bufReader)
header, err := r.ReadMIMEHeader()
if err == nil {
// Read reads the body of a part, after its headers and before the
// next part (if any) begins.
-func (bp *Part) Read(p []byte) (n int, err os.Error) {
+func (bp *Part) Read(p []byte) (n int, err error) {
if bp.buffer.Len() >= len(p) {
// Internal buffer of unconsumed data is large enough for
// the read request. No need to parse more at the moment.
return bp.buffer.Read(p)
}
peek, err := bp.mr.bufReader.Peek(4096) // TODO(bradfitz): add buffer size accessor
- unexpectedEof := err == os.EOF
+ unexpectedEof := err == io.EOF
if err != nil && !unexpectedEof {
return 0, fmt.Errorf("multipart: Part Read: %v", err)
}
}
}
n, err = bp.buffer.Read(p)
- if err == os.EOF && !foundBoundary {
+ if err == io.EOF && !foundBoundary {
// If the boundary hasn't been reached there's more to
// read, so don't pass through an EOF from the buffer
err = nil
return
}
-func (bp *Part) Close() os.Error {
+func (bp *Part) Close() error {
io.Copy(ioutil.Discard, bp)
return nil
}
// NextPart returns the next part in the multipart or an error.
// When there are no more parts, the error os.EOF is returned.
-func (mr *Reader) NextPart() (*Part, os.Error) {
+func (mr *Reader) NextPart() (*Part, error) {
if mr.currentPart != nil {
mr.currentPart.Close()
}
if hasPrefixThenNewline(line, mr.dashBoundaryDash) {
// Expected EOF
- return nil, os.EOF
+ return nil, io.EOF
}
if expectNewPart {
"io"
"io/ioutil"
"json"
- "os"
"strings"
"testing"
)
if part != nil {
t.Error("Didn't expect a fifth part.")
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("On fifth part expected os.EOF; got %v", err)
}
}
if part != nil {
t.Errorf("Unexpected part in test %d", testNum)
}
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("On test %d expected os.EOF; got %v", testNum, err)
}
const maxReadThreshold = 1 << 20
-func (mr *maliciousReader) Read(b []byte) (n int, err os.Error) {
+func (mr *maliciousReader) Read(b []byte) (n int, err error) {
mr.n += len(b)
if mr.n >= maxReadThreshold {
mr.t.Fatal("too much was read")
- return 0, os.EOF
+ return 0, io.EOF
}
return len(b), nil
}
r io.Reader
}
-func (s *slowReader) Read(p []byte) (int, os.Error) {
+func (s *slowReader) Read(p []byte) (int, error) {
if len(p) == 0 {
return s.r.Read(p)
}
import (
"bytes"
"crypto/rand"
+ "errors"
"fmt"
"io"
"net/textproto"
- "os"
"strings"
)
// header. The body of the part should be written to the returned
// Writer. After calling CreatePart, any previous part may no longer
// be written to.
-func (w *Writer) CreatePart(header textproto.MIMEHeader) (io.Writer, os.Error) {
+func (w *Writer) CreatePart(header textproto.MIMEHeader) (io.Writer, error) {
if w.lastpart != nil {
if err := w.lastpart.close(); err != nil {
return nil, err
// CreateFormFile is a convenience wrapper around CreatePart. It creates
// a new form-data header with the provided field name and file name.
-func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, os.Error) {
+func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
// CreateFormField calls CreatePart with a header using the
// given field name.
-func (w *Writer) CreateFormField(fieldname string) (io.Writer, os.Error) {
+func (w *Writer) CreateFormField(fieldname string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"`, escapeQuotes(fieldname)))
}
// WriteField calls CreateFormField and then writes the given value.
-func (w *Writer) WriteField(fieldname, value string) os.Error {
+func (w *Writer) WriteField(fieldname, value string) error {
p, err := w.CreateFormField(fieldname)
if err != nil {
return err
// Close finishes the multipart message and writes the trailing
// boundary end line to the output.
-func (w *Writer) Close() os.Error {
+func (w *Writer) Close() error {
if w.lastpart != nil {
if err := w.lastpart.close(); err != nil {
return err
type part struct {
mw *Writer
closed bool
- we os.Error // last error that occurred writing
+ we error // last error that occurred writing
}
-func (p *part) close() os.Error {
+func (p *part) close() error {
p.closed = true
return p.we
}
-func (p *part) Write(d []byte) (n int, err os.Error) {
+func (p *part) Write(d []byte) (n int, err error) {
if p.closed {
- return 0, os.NewError("multipart: can't write to finished part")
+ return 0, errors.New("multipart: can't write to finished part")
}
n, err = p.mw.w.Write(d)
if err != nil {
// AddExtensionType sets the MIME type associated with
// the extension ext to typ. The extension should begin with
// a leading dot, as in ".html".
-func AddExtensionType(ext, typ string) os.Error {
+func AddExtensionType(ext, typ string) error {
if ext == "" || ext[0] != '.' {
return fmt.Errorf(`mime: extension "%s" misses dot`, ext)
}
return setExtensionType(ext, typ)
}
-func setExtensionType(extension, mimeType string) os.Error {
+func setExtensionType(extension, mimeType string) error {
full, param, err := ParseMediaType(mimeType)
if err != nil {
return err
package net
-import "os"
-
-func cgoLookupHost(name string) (addrs []string, err os.Error, completed bool) {
+func cgoLookupHost(name string) (addrs []string, err error, completed bool) {
return nil, nil, false
}
-func cgoLookupPort(network, service string) (port int, err os.Error, completed bool) {
+func cgoLookupPort(network, service string) (port int, err error, completed bool) {
return 0, nil, false
}
-func cgoLookupIP(name string) (addrs []IP, err os.Error, completed bool) {
+func cgoLookupIP(name string) (addrs []IP, err error, completed bool) {
return nil, nil, false
}
-func cgoLookupCNAME(name string) (cname string, err os.Error, completed bool) {
+func cgoLookupCNAME(name string) (cname string, err error, completed bool) {
return "", nil, false
}
*/
import (
- "os"
"syscall"
"unsafe"
)
return string(a[:i])
}
-func cgoLookupHost(name string) (addrs []string, err os.Error, completed bool) {
+func cgoLookupHost(name string) (addrs []string, err error, completed bool) {
ip, err, completed := cgoLookupIP(name)
for _, p := range ip {
addrs = append(addrs, p.String())
return
}
-func cgoLookupPort(net, service string) (port int, err os.Error, completed bool) {
+func cgoLookupPort(net, service string) (port int, err error, completed bool) {
var res *syscall.Addrinfo
var hints syscall.Addrinfo
return 0, &AddrError{"unknown port", net + "/" + service}, true
}
-func cgoLookupIPCNAME(name string) (addrs []IP, cname string, err os.Error, completed bool) {
+func cgoLookupIPCNAME(name string) (addrs []IP, cname string, err error, completed bool) {
var res *syscall.Addrinfo
var hints syscall.Addrinfo
} else {
str = bytePtrToString(libc_gai_strerror(gerrno))
}
- return nil, "", &DNSError{Error: str, Name: name}, true
+ return nil, "", &DNSError{Err: str, Name: name}, true
}
defer libc_freeaddrinfo(res)
if res != nil {
return addrs, cname, nil, true
}
-func cgoLookupIP(name string) (addrs []IP, err os.Error, completed bool) {
+func cgoLookupIP(name string) (addrs []IP, err error, completed bool) {
addrs, _, err, completed = cgoLookupIPCNAME(name)
return
}
-func cgoLookupCNAME(name string) (cname string, err os.Error, completed bool) {
+func cgoLookupCNAME(name string) (cname string, err error, completed bool) {
_, cname, err, completed = cgoLookupIPCNAME(name)
return
}
package net
-import "os"
-
-func resolveNetAddr(op, net, addr string) (a Addr, err os.Error) {
+func resolveNetAddr(op, net, addr string) (a Addr, err error) {
if addr == "" {
return nil, &OpError{op, net, nil, errMissingAddress}
}
// Dial("tcp", "google.com:80")
// Dial("tcp", "[de:ad:be:ef::ca:fe]:80")
//
-func Dial(net, addr string) (c Conn, err os.Error) {
+func Dial(net, addr string) (c Conn, err error) {
addri, err := resolveNetAddr("dial", net, addr)
if err != nil {
return nil, err
// Listen announces on the local network address laddr.
// The network string net must be a stream-oriented
// network: "tcp", "tcp4", "tcp6", or "unix", or "unixpacket".
-func Listen(net, laddr string) (l Listener, err os.Error) {
+func Listen(net, laddr string) (l Listener, err error) {
switch net {
case "tcp", "tcp4", "tcp6":
var la *TCPAddr
// ListenPacket announces on the local network address laddr.
// The network string net must be a packet-oriented network:
// "udp", "udp4", "udp6", or "unixgram".
-func ListenPacket(net, laddr string) (c PacketConn, err os.Error) {
+func ListenPacket(net, laddr string) (c PacketConn, err error) {
switch net {
case "udp", "udp4", "udp6":
var la *UDPAddr
import (
"net/textproto"
- "os"
"strconv"
"strings"
)
// Dial returns a new client connected to a dictionary server at
// addr on the given network.
-func Dial(network, addr string) (*Client, os.Error) {
+func Dial(network, addr string) (*Client, error) {
text, err := textproto.Dial(network, addr)
if err != nil {
return nil, err
}
// Close closes the connection to the dictionary server.
-func (c *Client) Close() os.Error {
+func (c *Client) Close() error {
return c.text.Close()
}
}
// Dicts returns a list of the dictionaries available on the server.
-func (c *Client) Dicts() ([]Dict, os.Error) {
+func (c *Client) Dicts() ([]Dict, error) {
id, err := c.text.Cmd("SHOW DB")
if err != nil {
return nil, err
// The special dictionary name "!" means to look in all the
// server's dictionaries in turn, stopping after finding the word
// in one of them.
-func (c *Client) Define(dict, word string) ([]*Defn, os.Error) {
+func (c *Client) Define(dict, word string) ([]*Defn, error) {
id, err := c.text.Cmd("DEFINE %s %q", dict, word)
if err != nil {
return nil, err
// Fields returns the fields in s.
// Fields are space separated unquoted words
// or quoted with single or double quote.
-func fields(s string) ([]string, os.Error) {
+func fields(s string) ([]string, error) {
var v []string
i := 0
for {
import (
"bytes"
"fmt"
- "os"
"rand"
"sort"
)
// DNSError represents a DNS lookup error.
type DNSError struct {
- Error string // description of the error
+ Err string // description of the error
Name string // name looked for
Server string // server used
IsTimeout bool
}
-func (e *DNSError) String() string {
+func (e *DNSError) Error() string {
if e == nil {
return "<nil>"
}
if e.Server != "" {
s += " on " + e.Server
}
- s += ": " + e.Error
+ s += ": " + e.Err
return s
}
// reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
// address addr suitable for rDNS (PTR) record lookup or an error if it fails
// to parse the IP address.
-func reverseaddr(addr string) (arpa string, err os.Error) {
+func reverseaddr(addr string) (arpa string, err error) {
ip := ParseIP(addr)
if ip == nil {
- return "", &DNSError{Error: "unrecognized address", Name: addr}
+ return "", &DNSError{Err: "unrecognized address", Name: addr}
}
if ip.To4() != nil {
return fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", ip[15], ip[14], ip[13], ip[12]), nil
// Find answer for name in dns message.
// On return, if err == nil, addrs != nil.
-func answer(name, server string, dns *dnsMsg, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
+func answer(name, server string, dns *dnsMsg, qtype uint16) (cname string, addrs []dnsRR, err error) {
addrs = make([]dnsRR, 0, len(dns.answer))
if dns.rcode == dnsRcodeNameError && dns.recursion_available {
- return "", nil, &DNSError{Error: noSuchHost, Name: name}
+ return "", nil, &DNSError{Err: noSuchHost, Name: name}
}
if dns.rcode != dnsRcodeSuccess {
// None of the error codes make sense
// for the query we sent. If we didn't get
// a name error and we didn't get success,
// the server is behaving incorrectly.
- return "", nil, &DNSError{Error: "server misbehaving", Name: name, Server: server}
+ return "", nil, &DNSError{Err: "server misbehaving", Name: name, Server: server}
}
// Look for the name.
}
}
if len(addrs) == 0 {
- return "", nil, &DNSError{Error: noSuchHost, Name: name, Server: server}
+ return "", nil, &DNSError{Err: noSuchHost, Name: name, Server: server}
}
return name, addrs, nil
}
- return "", nil, &DNSError{Error: "too many redirects", Name: name, Server: server}
+ return "", nil, &DNSError{Err: "too many redirects", Name: name, Server: server}
}
func isDomainName(s string) bool {
package net
import (
- "os"
"rand"
"sync"
"time"
// Send a request on the connection and hope for a reply.
// Up to cfg.attempts attempts.
-func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Error) {
+func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, error) {
if len(name) >= 256 {
- return nil, &DNSError{Error: "name too long", Name: name}
+ return nil, &DNSError{Err: "name too long", Name: name}
}
out := new(dnsMsg)
out.id = uint16(rand.Int()) ^ uint16(time.Nanoseconds())
out.recursion_desired = true
msg, ok := out.Pack()
if !ok {
- return nil, &DNSError{Error: "internal error - cannot pack message", Name: name}
+ return nil, &DNSError{Err: "internal error - cannot pack message", Name: name}
}
for attempt := 0; attempt < cfg.attempts; attempt++ {
if a := c.RemoteAddr(); a != nil {
server = a.String()
}
- return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true}
+ return nil, &DNSError{Err: "no answer from server", Name: name, Server: server, IsTimeout: true}
}
// Do a lookup for a single name, which must be rooted
// (otherwise answer will not find the answers).
-func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
+func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err error) {
if len(cfg.servers) == 0 {
- return "", nil, &DNSError{Error: "no DNS servers", Name: name}
+ return "", nil, &DNSError{Err: "no DNS servers", Name: name}
}
for i := 0; i < len(cfg.servers); i++ {
// Calling Dial here is scary -- we have to be sure
continue
}
cname, addrs, err = answer(name, server, msg, qtype)
- if err == nil || err.(*DNSError).Error == noSuchHost {
+ if err == nil || err.(*DNSError).Err == noSuchHost {
break
}
}
}
var cfg *dnsConfig
-var dnserr os.Error
+var dnserr error
func loadConfig() { cfg, dnserr = dnsReadConfig() }
var onceLoadConfig sync.Once
-func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) {
+func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err error) {
if !isDomainName(name) {
- return name, nil, &DNSError{Error: "invalid domain name", Name: name}
+ return name, nil, &DNSError{Err: "invalid domain name", Name: name}
}
onceLoadConfig.Do(loadConfig)
if dnserr != nil || cfg == nil {
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
-func goLookupHost(name string) (addrs []string, err os.Error) {
+func goLookupHost(name string) (addrs []string, err error) {
// Use entries from /etc/hosts if they match.
addrs = lookupStaticHost(name)
if len(addrs) > 0 {
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
-func goLookupIP(name string) (addrs []IP, err os.Error) {
+func goLookupIP(name string) (addrs []IP, err error) {
// Use entries from /etc/hosts if possible.
haddrs := lookupStaticHost(name)
if len(haddrs) > 0 {
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
-func goLookupCNAME(name string) (cname string, err os.Error) {
+func goLookupCNAME(name string) (cname string, err error) {
onceLoadConfig.Do(loadConfig)
if dnserr != nil || cfg == nil {
err = dnserr
package net
-import "os"
-
type dnsConfig struct {
servers []string // servers to use
search []string // suffixes to append to local name
rotate bool // round robin among servers
}
-var dnsconfigError os.Error
+var dnsconfigError error
type DNSConfigError struct {
- Error os.Error
+ Err error
}
-func (e *DNSConfigError) String() string {
- return "error reading DNS config: " + e.Error.String()
+func (e *DNSConfigError) Error() string {
+ return "error reading DNS config: " + e.Err.Error()
}
func (e *DNSConfigError) Timeout() bool { return false }
// TODO(rsc): Supposed to call uname() and chop the beginning
// of the host name to get the default search domain.
// We assume it's in resolv.conf anyway.
-func dnsReadConfig() (*dnsConfig, os.Error) {
+func dnsReadConfig() (*dnsConfig, error) {
file, err := open("/etc/resolv.conf")
if err != nil {
return nil, &DNSConfigError{err}
type InvalidConnError struct{}
-func (e *InvalidConnError) String() string { return "invalid net.Conn" }
+func (e *InvalidConnError) Error() string { return "invalid net.Conn" }
func (e *InvalidConnError) Temporary() bool { return false }
func (e *InvalidConnError) Timeout() bool { return false }
wake, err := s.poll.AddFD(intfd, mode, false)
if err != nil {
- panic("pollServer AddFD " + err.String())
+ panic("pollServer AddFD " + err.Error())
}
if wake {
doWakeup = true
}
fd, mode, err := s.poll.WaitFD(s, t)
if err != nil {
- print("pollServer WaitFD: ", err.String(), "\n")
+ print("pollServer WaitFD: ", err.Error(), "\n")
return
}
if fd < 0 {
func startServer() {
p, err := newPollServer()
if err != nil {
- print("Start pollServer: ", err.String(), "\n")
+ print("Start pollServer: ", err.Error(), "\n")
}
pollserver = p
}
-func newFD(fd, family, proto int, net string) (f *netFD, err os.Error) {
+func newFD(fd, family, proto int, net string) (f *netFD, err error) {
onceStartServer.Do(startServer)
if e := syscall.SetNonblock(fd, true); e != 0 {
return nil, os.Errno(e)
fd.sysfile = os.NewFile(fd.sysfd, fd.net+":"+ls+"->"+rs)
}
-func (fd *netFD) connect(ra syscall.Sockaddr) (err os.Error) {
+func (fd *netFD) connect(ra syscall.Sockaddr) (err error) {
e := syscall.Connect(fd.sysfd, ra)
if e == syscall.EINPROGRESS {
var errno int
fd.sysmu.Unlock()
}
-func (fd *netFD) Close() os.Error {
+func (fd *netFD) Close() error {
if fd == nil || fd.sysfile == nil {
return os.EINVAL
}
return nil
}
-func (fd *netFD) shutdown(how int) os.Error {
+func (fd *netFD) shutdown(how int) error {
if fd == nil || fd.sysfile == nil {
return os.EINVAL
}
return nil
}
-func (fd *netFD) CloseRead() os.Error {
+func (fd *netFD) CloseRead() error {
return fd.shutdown(syscall.SHUT_RD)
}
-func (fd *netFD) CloseWrite() os.Error {
+func (fd *netFD) CloseWrite() error {
return fd.shutdown(syscall.SHUT_WR)
}
-func (fd *netFD) Read(p []byte) (n int, err os.Error) {
+func (fd *netFD) Read(p []byte) (n int, err error) {
if fd == nil {
return 0, os.EINVAL
}
} else {
fd.rdeadline = 0
}
- var oserr os.Error
+ var oserr error
for {
var errno int
n, errno = syscall.Read(fd.sysfile.Fd(), p)
n = 0
oserr = os.Errno(errno)
} else if n == 0 && errno == 0 && fd.proto != syscall.SOCK_DGRAM {
- err = os.EOF
+ err = io.EOF
}
break
}
return
}
-func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err os.Error) {
+func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err error) {
if fd == nil || fd.sysfile == nil {
return 0, nil, os.EINVAL
}
} else {
fd.rdeadline = 0
}
- var oserr os.Error
+ var oserr error
for {
var errno int
n, sa, errno = syscall.Recvfrom(fd.sysfd, p, 0)
return
}
-func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err os.Error) {
+func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error) {
if fd == nil || fd.sysfile == nil {
return 0, 0, 0, nil, os.EINVAL
}
} else {
fd.rdeadline = 0
}
- var oserr os.Error
+ var oserr error
for {
var errno int
n, oobn, flags, sa, errno = syscall.Recvmsg(fd.sysfd, p, oob, 0)
oserr = os.Errno(errno)
}
if n == 0 {
- oserr = os.EOF
+ oserr = io.EOF
}
break
}
return
}
-func (fd *netFD) Write(p []byte) (n int, err os.Error) {
+func (fd *netFD) Write(p []byte) (n int, err error) {
if fd == nil {
return 0, os.EINVAL
}
fd.wdeadline = 0
}
nn := 0
- var oserr os.Error
+ var oserr error
for {
n, errno := syscall.Write(fd.sysfile.Fd(), p[nn:])
return nn, err
}
-func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err os.Error) {
+func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err error) {
if fd == nil || fd.sysfile == nil {
return 0, os.EINVAL
}
} else {
fd.wdeadline = 0
}
- var oserr os.Error
+ var oserr error
for {
errno := syscall.Sendto(fd.sysfd, p, 0, sa)
if errno == syscall.EAGAIN && fd.wdeadline >= 0 {
return
}
-func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err os.Error) {
+func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) {
if fd == nil || fd.sysfile == nil {
return 0, 0, os.EINVAL
}
} else {
fd.wdeadline = 0
}
- var oserr os.Error
+ var oserr error
for {
var errno int
errno = syscall.Sendmsg(fd.sysfd, p, oob, sa, 0)
return
}
-func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os.Error) {
+func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err error) {
if fd == nil || fd.sysfile == nil {
return nil, os.EINVAL
}
return nfd, nil
}
-func (fd *netFD) dup() (f *os.File, err os.Error) {
+func (fd *netFD) dup() (f *os.File, err error) {
ns, e := syscall.Dup(fd.sysfd)
if e != 0 {
return nil, &OpError{"dup", fd.net, fd.laddr, os.Errno(e)}
ctlEvent syscall.EpollEvent
}
-func newpollster() (p *pollster, err os.Error) {
+func newpollster() (p *pollster, err error) {
p = new(pollster)
var e int
return p, nil
}
-func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) {
+func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, error) {
// pollServer is locked.
var already bool
p.ctlEvent.Fd = int32(fd)
p.ctlEvent.Events = events
if e := syscall.EpollCtl(p.epfd, syscall.EPOLL_CTL_MOD, fd, &p.ctlEvent); e != 0 {
- print("Epoll modify fd=", fd, ": ", os.Errno(e).String(), "\n")
+ print("Epoll modify fd=", fd, ": ", os.Errno(e).Error(), "\n")
}
p.events[fd] = events
} else {
if e := syscall.EpollCtl(p.epfd, syscall.EPOLL_CTL_DEL, fd, nil); e != 0 {
- print("Epoll delete fd=", fd, ": ", os.Errno(e).String(), "\n")
+ print("Epoll delete fd=", fd, ": ", os.Errno(e).Error(), "\n")
}
delete(p.events, fd)
}
}
}
-func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.Error) {
+func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err error) {
for len(p.waitEvents) == 0 {
var msec int = -1
if nsec > 0 {
return fd, 'r', nil
}
-func (p *pollster) Close() os.Error {
+func (p *pollster) Close() error {
return os.NewSyscallError("close", syscall.Close(p.epfd))
}
kbuf [1]syscall.Kevent_t
}
-func newpollster() (p *pollster, err os.Error) {
+func newpollster() (p *pollster, err error) {
p = new(pollster)
var e int
if p.kq, e = syscall.Kqueue(); e != 0 {
return p, nil
}
-func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) {
+func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, error) {
// pollServer is locked.
var kmode int
syscall.Kevent(p.kq, p.kbuf[:], nil, nil)
}
-func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.Error) {
+func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err error) {
var t *syscall.Timespec
for len(p.events) == 0 {
if nsec > 0 {
return fd, mode, nil
}
-func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) }
+func (p *pollster) Close() error { return os.NewSyscallError("close", syscall.Close(p.kq)) }
package net
import (
+ "io"
"os"
"runtime"
"sync"
type InvalidConnError struct{}
-func (e *InvalidConnError) String() string { return "invalid net.Conn" }
+func (e *InvalidConnError) Error() string { return "invalid net.Conn" }
func (e *InvalidConnError) Temporary() bool { return false }
func (e *InvalidConnError) Timeout() bool { return false }
-var initErr os.Error
+var initErr error
func init() {
var d syscall.WSAData
// ExecIO executes a single io operation. It either executes it
// inline, or, if timeouts are employed, passes the request onto
// a special goroutine and waits for completion or cancels request.
-func (s *ioSrv) ExecIO(oi anOpIface, deadline_delta int64) (n int, err os.Error) {
+func (s *ioSrv) ExecIO(oi anOpIface, deadline_delta int64) (n int, err error) {
var e int
o := oi.Op()
if deadline_delta > 0 {
return f
}
-func newFD(fd syscall.Handle, family, proto int, net string) (f *netFD, err os.Error) {
+func newFD(fd syscall.Handle, family, proto int, net string) (f *netFD, err error) {
if initErr != nil {
return nil, initErr
}
fd.raddr = raddr
}
-func (fd *netFD) connect(ra syscall.Sockaddr) (err os.Error) {
+func (fd *netFD) connect(ra syscall.Sockaddr) (err error) {
e := syscall.Connect(fd.sysfd, ra)
if e != 0 {
return os.Errno(e)
fd.sysmu.Unlock()
}
-func (fd *netFD) Close() os.Error {
+func (fd *netFD) Close() error {
if fd == nil || fd.sysfd == syscall.InvalidHandle {
return os.EINVAL
}
return nil
}
-func (fd *netFD) shutdown(how int) os.Error {
+func (fd *netFD) shutdown(how int) error {
if fd == nil || fd.sysfd == syscall.InvalidHandle {
return os.EINVAL
}
return nil
}
-func (fd *netFD) CloseRead() os.Error {
+func (fd *netFD) CloseRead() error {
return fd.shutdown(syscall.SHUT_RD)
}
-func (fd *netFD) CloseWrite() os.Error {
+func (fd *netFD) CloseWrite() error {
return fd.shutdown(syscall.SHUT_WR)
}
return "WSARecv"
}
-func (fd *netFD) Read(buf []byte) (n int, err os.Error) {
+func (fd *netFD) Read(buf []byte) (n int, err error) {
if fd == nil {
return 0, os.EINVAL
}
o.Init(fd, buf, 'r')
n, err = iosrv.ExecIO(&o, fd.rdeadline_delta)
if err == nil && n == 0 {
- err = os.EOF
+ err = io.EOF
}
return
}
return "WSARecvFrom"
}
-func (fd *netFD) ReadFrom(buf []byte) (n int, sa syscall.Sockaddr, err os.Error) {
+func (fd *netFD) ReadFrom(buf []byte) (n int, sa syscall.Sockaddr, err error) {
if fd == nil {
return 0, nil, os.EINVAL
}
return "WSASend"
}
-func (fd *netFD) Write(buf []byte) (n int, err os.Error) {
+func (fd *netFD) Write(buf []byte) (n int, err error) {
if fd == nil {
return 0, os.EINVAL
}
return "WSASendto"
}
-func (fd *netFD) WriteTo(buf []byte, sa syscall.Sockaddr) (n int, err os.Error) {
+func (fd *netFD) WriteTo(buf []byte, sa syscall.Sockaddr) (n int, err error) {
if fd == nil {
return 0, os.EINVAL
}
return "AcceptEx"
}
-func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os.Error) {
+func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err error) {
if fd == nil || fd.sysfd == syscall.InvalidHandle {
return nil, os.EINVAL
}
// Unimplemented functions.
-func (fd *netFD) dup() (f *os.File, err os.Error) {
+func (fd *netFD) dup() (f *os.File, err error) {
// TODO: Implement this
return nil, os.NewSyscallError("dup", syscall.EWINDOWS)
}
-func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err os.Error) {
+func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error) {
return 0, 0, 0, nil, os.EAFNOSUPPORT
}
-func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err os.Error) {
+func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) {
return 0, 0, os.EAFNOSUPPORT
}
"syscall"
)
-func newFileFD(f *os.File) (nfd *netFD, err os.Error) {
+func newFileFD(f *os.File) (nfd *netFD, err error) {
fd, errno := syscall.Dup(f.Fd())
if errno != 0 {
return nil, os.NewSyscallError("dup", errno)
// the open file f. It is the caller's responsibility to close f when
// finished. Closing c does not affect f, and closing f does not
// affect c.
-func FileConn(f *os.File) (c Conn, err os.Error) {
+func FileConn(f *os.File) (c Conn, err error) {
fd, err := newFileFD(f)
if err != nil {
return nil, err
// to the open file f. It is the caller's responsibility to close l
// when finished. Closing c does not affect l, and closing l does not
// affect c.
-func FileListener(f *os.File) (l Listener, err os.Error) {
+func FileListener(f *os.File) (l Listener, err error) {
fd, err := newFileFD(f)
if err != nil {
return nil, err
// corresponding to the open file f. It is the caller's
// responsibility to close f when finished. Closing c does not affect
// f, and closing f does not affect c.
-func FilePacketConn(f *os.File) (c PacketConn, err os.Error) {
+func FilePacketConn(f *os.File) (c PacketConn, err error) {
fd, err := newFileFD(f)
if err != nil {
return nil, err
// the open file f. It is the caller's responsibility to close f when
// finished. Closing c does not affect f, and closing f does not
// affect c.
-func FileConn(f *os.File) (c Conn, err os.Error) {
+func FileConn(f *os.File) (c Conn, err error) {
return nil, os.EPLAN9
}
// to the open file f. It is the caller's responsibility to close l
// when finished. Closing c does not affect l, and closing l does not
// affect c.
-func FileListener(f *os.File) (l Listener, err os.Error) {
+func FileListener(f *os.File) (l Listener, err error) {
return nil, os.EPLAN9
}
// corresponding to the open file f. It is the caller's
// responsibility to close f when finished. Closing c does not affect
// f, and closing f does not affect c.
-func FilePacketConn(f *os.File) (c PacketConn, err os.Error) {
+func FilePacketConn(f *os.File) (c PacketConn, err error) {
return nil, os.EPLAN9
}
type listenerFile interface {
Listener
- File() (f *os.File, err os.Error)
+ File() (f *os.File, err error)
}
type packetConnFile interface {
PacketConn
- File() (f *os.File, err os.Error)
+ File() (f *os.File, err error)
}
type connFile interface {
Conn
- File() (f *os.File, err os.Error)
+ File() (f *os.File, err error)
}
func testFileListener(t *testing.T, net, laddr string) {
"syscall"
)
-func FileConn(f *os.File) (c Conn, err os.Error) {
+func FileConn(f *os.File) (c Conn, err error) {
// TODO: Implement this
return nil, os.NewSyscallError("FileConn", syscall.EWINDOWS)
}
-func FileListener(f *os.File) (l Listener, err os.Error) {
+func FileListener(f *os.File) (l Listener, err error) {
// TODO: Implement this
return nil, os.NewSyscallError("FileListener", syscall.EWINDOWS)
}
-func FilePacketConn(f *os.File) (c PacketConn, err os.Error) {
+func FilePacketConn(f *os.File) (c PacketConn, err error) {
// TODO: Implement this
return nil, os.NewSyscallError("FilePacketConn", syscall.EWINDOWS)
}
import (
"bytes"
+ "errors"
"fmt"
- "os"
)
// A HardwareAddr represents a physical hardware address.
// 01-23-45-67-89-ab-cd-ef
// 0123.4567.89ab
// 0123.4567.89ab.cdef
-func ParseMAC(s string) (hw HardwareAddr, err os.Error) {
+func ParseMAC(s string) (hw HardwareAddr, err error) {
if len(s) < 14 {
goto error
}
return hw, nil
error:
- return nil, os.NewError("invalid MAC address: " + s)
+ return nil, errors.New("invalid MAC address: " + s)
}
// Interface represents a mapping between network interface name
}
// Addrs returns interface addresses for a specific interface.
-func (ifi *Interface) Addrs() ([]Addr, os.Error) {
+func (ifi *Interface) Addrs() ([]Addr, error) {
if ifi == nil {
- return nil, os.NewError("net: invalid interface")
+ return nil, errors.New("net: invalid interface")
}
return interfaceAddrTable(ifi.Index)
}
// MulticastAddrs returns multicast, joined group addresses for
// a specific interface.
-func (ifi *Interface) MulticastAddrs() ([]Addr, os.Error) {
+func (ifi *Interface) MulticastAddrs() ([]Addr, error) {
if ifi == nil {
- return nil, os.NewError("net: invalid interface")
+ return nil, errors.New("net: invalid interface")
}
return interfaceMulticastAddrTable(ifi.Index)
}
// Interfaces returns a list of the systems's network interfaces.
-func Interfaces() ([]Interface, os.Error) {
+func Interfaces() ([]Interface, error) {
return interfaceTable(0)
}
// InterfaceAddrs returns a list of the system's network interface
// addresses.
-func InterfaceAddrs() ([]Addr, os.Error) {
+func InterfaceAddrs() ([]Addr, error) {
return interfaceAddrTable(0)
}
// InterfaceByIndex returns the interface specified by index.
-func InterfaceByIndex(index int) (*Interface, os.Error) {
+func InterfaceByIndex(index int) (*Interface, error) {
if index <= 0 {
- return nil, os.NewError("net: invalid interface index")
+ return nil, errors.New("net: invalid interface index")
}
ift, err := interfaceTable(index)
if err != nil {
for _, ifi := range ift {
return &ifi, nil
}
- return nil, os.NewError("net: no such interface")
+ return nil, errors.New("net: no such interface")
}
// InterfaceByName returns the interface specified by name.
-func InterfaceByName(name string) (*Interface, os.Error) {
+func InterfaceByName(name string) (*Interface, error) {
if name == "" {
- return nil, os.NewError("net: invalid interface name")
+ return nil, errors.New("net: invalid interface name")
}
ift, err := interfaceTable(0)
if err != nil {
return &ifi, nil
}
}
- return nil, os.NewError("net: no such interface")
+ return nil, errors.New("net: no such interface")
}
// If the ifindex is zero, interfaceTable returns mappings of all
// network interfaces. Otheriwse it returns a mapping of a specific
// interface.
-func interfaceTable(ifindex int) ([]Interface, os.Error) {
+func interfaceTable(ifindex int) ([]Interface, error) {
var (
tab []byte
e int
return ift, nil
}
-func newLink(m *syscall.InterfaceMessage) ([]Interface, os.Error) {
+func newLink(m *syscall.InterfaceMessage) ([]Interface, error) {
var ift []Interface
sas, e := syscall.ParseRoutingSockaddr(m)
// If the ifindex is zero, interfaceAddrTable returns addresses
// for all network interfaces. Otherwise it returns addresses
// for a specific interface.
-func interfaceAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceAddrTable(ifindex int) ([]Addr, error) {
var (
tab []byte
e int
return ifat, nil
}
-func newAddr(m *syscall.InterfaceAddrMessage) ([]Addr, os.Error) {
+func newAddr(m *syscall.InterfaceAddrMessage) ([]Addr, error) {
var ifat []Addr
sas, e := syscall.ParseRoutingSockaddr(m)
// If the ifindex is zero, interfaceMulticastAddrTable returns
// addresses for all network interfaces. Otherwise it returns
// addresses for a specific interface.
-func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) {
var (
tab []byte
e int
return ifmat, nil
}
-func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, os.Error) {
+func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, error) {
var ifmat []Addr
sas, e := syscall.ParseRoutingSockaddr(m)
// If the ifindex is zero, interfaceMulticastAddrTable returns
// addresses for all network interfaces. Otherwise it returns
// addresses for a specific interface.
-func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) {
var (
tab []byte
e int
return ifmat, nil
}
-func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, os.Error) {
+func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, error) {
var ifmat []Addr
sas, e := syscall.ParseRoutingSockaddr(m)
// If the ifindex is zero, interfaceTable returns mappings of all
// network interfaces. Otheriwse it returns a mapping of a specific
// interface.
-func interfaceTable(ifindex int) ([]Interface, os.Error) {
+func interfaceTable(ifindex int) ([]Interface, error) {
var (
ift []Interface
tab []byte
// If the ifindex is zero, interfaceAddrTable returns addresses
// for all network interfaces. Otherwise it returns addresses
// for a specific interface.
-func interfaceAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceAddrTable(ifindex int) ([]Addr, error) {
var (
tab []byte
e int
- err os.Error
+ err error
ifat []Addr
msgs []syscall.NetlinkMessage
)
return ifat, nil
}
-func addrTable(msgs []syscall.NetlinkMessage, ifindex int) ([]Addr, os.Error) {
+func addrTable(msgs []syscall.NetlinkMessage, ifindex int) ([]Addr, error) {
var ifat []Addr
for _, m := range msgs {
// If the ifindex is zero, interfaceMulticastAddrTable returns
// addresses for all network interfaces. Otherwise it returns
// addresses for a specific interface.
-func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) {
var (
ifi *Interface
- err os.Error
+ err error
)
if ifindex > 0 {
package net
-import "os"
-
// If the ifindex is zero, interfaceMulticastAddrTable returns
// addresses for all network interfaces. Otherwise it returns
// addresses for a specific interface.
-func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) {
return nil, nil
}
package net
-import "os"
-
// If the ifindex is zero, interfaceTable returns mappings of all
// network interfaces. Otheriwse it returns a mapping of a specific
// interface.
-func interfaceTable(ifindex int) ([]Interface, os.Error) {
+func interfaceTable(ifindex int) ([]Interface, error) {
return nil, nil
}
// If the ifindex is zero, interfaceAddrTable returns addresses
// for all network interfaces. Otherwise it returns addresses
// for a specific interface.
-func interfaceAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceAddrTable(ifindex int) ([]Addr, error) {
return nil, nil
}
// If the ifindex is zero, interfaceMulticastAddrTable returns
// addresses for all network interfaces. Otherwise it returns
// addresses for a specific interface.
-func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) {
return nil, nil
}
import (
"bytes"
- "os"
"reflect"
"strings"
"testing"
{"0123.4567.89AB.CDEF", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, ""},
}
-func match(err os.Error, s string) bool {
+func match(err error, s string) bool {
if s == "" {
return err == nil
}
- return err != nil && strings.Contains(err.String(), s)
+ return err != nil && strings.Contains(err.Error(), s)
}
func TestParseMAC(t *testing.T) {
return string(a[:i])
}
-func getAdapterList() (*syscall.IpAdapterInfo, os.Error) {
+func getAdapterList() (*syscall.IpAdapterInfo, error) {
b := make([]byte, 1000)
l := uint32(len(b))
a := (*syscall.IpAdapterInfo)(unsafe.Pointer(&b[0]))
return a, nil
}
-func getInterfaceList() ([]syscall.InterfaceInfo, os.Error) {
+func getInterfaceList() ([]syscall.InterfaceInfo, error) {
s, e := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
if e != 0 {
return nil, os.NewSyscallError("Socket", e)
// If the ifindex is zero, interfaceTable returns mappings of all
// network interfaces. Otheriwse it returns a mapping of a specific
// interface.
-func interfaceTable(ifindex int) ([]Interface, os.Error) {
+func interfaceTable(ifindex int) ([]Interface, error) {
ai, e := getAdapterList()
if e != nil {
return nil, e
// If the ifindex is zero, interfaceAddrTable returns addresses
// for all network interfaces. Otherwise it returns addresses
// for a specific interface.
-func interfaceAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceAddrTable(ifindex int) ([]Addr, error) {
ai, e := getAdapterList()
if e != nil {
return nil, e
// If the ifindex is zero, interfaceMulticastAddrTable returns
// addresses for all network interfaces. Otherwise it returns
// addresses for a specific interface.
-func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) {
+func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) {
return nil, nil
}
package net
-import "os"
-
// IP address lengths (bytes).
const (
IPv4len = 4
Text string
}
-func (e *ParseError) String() string {
+func (e *ParseError) Error() string {
return "invalid " + e.Type + ": " + e.Text
}
// It returns the IP address and the network implied by the IP
// and mask. For example, ParseCIDR("192.168.100.1/16") returns
// the IP address 192.168.100.1 and the network 192.168.0.0/16.
-func ParseCIDR(s string) (IP, *IPNet, os.Error) {
+func ParseCIDR(s string) (IP, *IPNet, error) {
i := byteIndex(s, '/')
if i < 0 {
return nil, nil, &ParseError{"CIDR address", s}
"bytes"
"reflect"
"testing"
- "os"
"runtime"
)
in string
ip IP
net *IPNet
- err os.Error
+ err error
}{
{"135.104.0.0/32", IPv4(135, 104, 0, 0), &IPNet{IPv4(135, 104, 0, 0), IPv4Mask(255, 255, 255, 255)}, nil},
{"0.0.0.0/24", IPv4(0, 0, 0, 0), &IPNet{IPv4(0, 0, 0, 0), IPv4Mask(255, 255, 255, 0)}, nil},
var (
laddr *IPAddr
- err os.Error
+ err error
)
if *srchost != "" {
laddr, err = ResolveIPAddr("ip4", *srchost)
package net
-import (
- "os"
-)
-
// IPAddr represents the address of a IP end point.
type IPAddr struct {
IP IP
// names to numeric addresses on the network net, which must be
// "ip", "ip4" or "ip6". A literal IPv6 host address must be
// enclosed in square brackets, as in "[::]".
-func ResolveIPAddr(net, addr string) (*IPAddr, os.Error) {
+func ResolveIPAddr(net, addr string) (*IPAddr, error) {
ip, err := hostToIP(net, addr)
if err != nil {
return nil, err
}
// Convert "host" into IP address.
-func hostToIP(net, host string) (ip IP, err os.Error) {
+func hostToIP(net, host string) (ip IP, err error) {
var addr IP
// Try as an IP address.
addr = ParseIP(host)
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *IPConn) Read(b []byte) (n int, err os.Error) {
+func (c *IPConn) Read(b []byte) (n int, err error) {
return 0, os.EPLAN9
}
// Write implements the net.Conn Write method.
-func (c *IPConn) Write(b []byte) (n int, err os.Error) {
+func (c *IPConn) Write(b []byte) (n int, err error) {
return 0, os.EPLAN9
}
// Close closes the IP connection.
-func (c *IPConn) Close() os.Error {
+func (c *IPConn) Close() error {
return os.EPLAN9
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *IPConn) SetTimeout(nsec int64) os.Error {
+func (c *IPConn) SetTimeout(nsec int64) error {
return os.EPLAN9
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *IPConn) SetReadTimeout(nsec int64) os.Error {
+func (c *IPConn) SetReadTimeout(nsec int64) error {
return os.EPLAN9
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *IPConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *IPConn) SetWriteTimeout(nsec int64) error {
return os.EPLAN9
}
// IP-specific methods.
// ReadFrom implements the net.PacketConn ReadFrom method.
-func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
+func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err error) {
err = os.EPLAN9
return
}
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
-func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err os.Error) {
+func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err error) {
return 0, os.EPLAN9
}
// WriteTo implements the net.PacketConn WriteTo method.
-func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
+func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err error) {
return 0, os.EPLAN9
}
-func splitNetProto(netProto string) (net string, proto int, err os.Error) {
+func splitNetProto(netProto string) (net string, proto int, err error) {
err = os.EPLAN9
return
}
// DialIP connects to the remote address raddr on the network net,
// which must be "ip", "ip4", or "ip6".
-func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) {
+func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err error) {
return nil, os.EPLAN9
}
// local address laddr. The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send IP
// packets with per-packet addressing.
-func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) {
+func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err error) {
return nil, os.EPLAN9
}
package net
import (
+ "errors"
"os"
"syscall"
)
return syscall.AF_INET6
}
-func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) {
+func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
return ipToSockaddr(family, a.IP, 0)
}
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *IPConn) Read(b []byte) (n int, err os.Error) {
+func (c *IPConn) Read(b []byte) (n int, err error) {
n, _, err = c.ReadFrom(b)
return
}
// Write implements the net.Conn Write method.
-func (c *IPConn) Write(b []byte) (n int, err os.Error) {
+func (c *IPConn) Write(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Close closes the IP connection.
-func (c *IPConn) Close() os.Error {
+func (c *IPConn) Close() error {
if !c.ok() {
return os.EINVAL
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *IPConn) SetTimeout(nsec int64) os.Error {
+func (c *IPConn) SetTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *IPConn) SetReadTimeout(nsec int64) os.Error {
+func (c *IPConn) SetReadTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *IPConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *IPConn) SetWriteTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
-func (c *IPConn) SetReadBuffer(bytes int) os.Error {
+func (c *IPConn) SetReadBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
-func (c *IPConn) SetWriteBuffer(bytes int) os.Error {
+func (c *IPConn) SetWriteBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
// ReadFromIP can be made to time out and return an error with
// Timeout() == true after a fixed time limit; see SetTimeout and
// SetReadTimeout.
-func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err os.Error) {
+func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
}
// ReadFrom implements the net.PacketConn ReadFrom method.
-func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
+func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
-func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err os.Error) {
+func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
sa, err1 := addr.sockaddr(c.fd.family)
if err1 != nil {
- return 0, &OpError{Op: "write", Net: "ip", Addr: addr, Error: err1}
+ return 0, &OpError{Op: "write", Net: "ip", Addr: addr, Err: err1}
}
return c.fd.WriteTo(b, sa)
}
// WriteTo implements the net.PacketConn WriteTo method.
-func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
+func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
return c.WriteToIP(b, a)
}
-func splitNetProto(netProto string) (net string, proto int, err os.Error) {
+func splitNetProto(netProto string) (net string, proto int, err error) {
i := last(netProto, ':')
if i < 0 { // no colon
- return "", 0, os.NewError("no IP protocol specified")
+ return "", 0, errors.New("no IP protocol specified")
}
net = netProto[0:i]
protostr := netProto[i+1:]
// DialIP connects to the remote address raddr on the network net,
// which must be "ip", "ip4", or "ip6".
-func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) {
+func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err error) {
net, proto, err := splitNetProto(netProto)
if err != nil {
return
// local address laddr. The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send IP
// packets with per-packet addressing.
-func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) {
+func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err error) {
net, proto, err := splitNetProto(netProto)
if err != nil {
return
}
// BindToDevice binds an IPConn to a network interface.
-func (c *IPConn) BindToDevice(device string) os.Error {
+func (c *IPConn) BindToDevice(device string) error {
if !c.ok() {
return os.EINVAL
}
// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
-func (c *IPConn) File() (f *os.File, err os.Error) { return c.fd.dup() }
+func (c *IPConn) File() (f *os.File, err error) { return c.fd.dup() }
package net
-import (
- "os"
-)
-
var supportsIPv6, supportsIPv4map = probeIPv6Stack()
func firstFavoriteAddr(filter func(IP) IP, addrs []string) (addr IP) {
type InvalidAddrError string
-func (e InvalidAddrError) String() string { return string(e) }
+func (e InvalidAddrError) Error() string { return string(e) }
func (e InvalidAddrError) Timeout() bool { return false }
func (e InvalidAddrError) Temporary() bool { return false }
// SplitHostPort splits a network address of the form
// "host:port" or "[host]:port" into host and port.
// The latter form must be used when host contains a colon.
-func SplitHostPort(hostport string) (host, port string, err os.Error) {
+func SplitHostPort(hostport string) (host, port string, err error) {
// The port starts after the last colon.
i := last(hostport, ':')
if i < 0 {
}
// Convert "host:port" into IP address and port.
-func hostPortToIP(net, hostport string) (ip IP, iport int, err os.Error) {
+func hostPortToIP(net, hostport string) (ip IP, iport int, err error) {
var (
addr IP
p, i int
package net
import (
+ "errors"
+ "io"
"os"
)
}
// parsePlan9Addr parses address of the form [ip!]port (e.g. 127.0.0.1!80).
-func parsePlan9Addr(s string) (ip IP, iport int, err os.Error) {
+func parsePlan9Addr(s string) (ip IP, iport int, err error) {
var (
addr IP
p, i int
if i >= 0 {
addr = ParseIP(s[:i])
if addr == nil {
- err = os.NewError("net: parsing IP failed")
+ err = errors.New("net: parsing IP failed")
goto Error
}
}
p, _, ok = dtoi(s[i+1:], 0)
if !ok {
- err = os.NewError("net: parsing port failed")
+ err = errors.New("net: parsing port failed")
goto Error
}
if p < 0 || p > 0xFFFF {
return nil, 0, err
}
-func readPlan9Addr(proto, filename string) (addr Addr, err os.Error) {
+func readPlan9Addr(proto, filename string) (addr Addr, err error) {
var buf [128]byte
f, err := os.Open(filename)
case "udp":
addr = &UDPAddr{ip, port}
default:
- return nil, os.NewError("unknown protocol " + proto)
+ return nil, errors.New("unknown protocol " + proto)
}
return addr, nil
}
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *plan9Conn) Read(b []byte) (n int, err os.Error) {
+func (c *plan9Conn) Read(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
}
n, err = c.data.Read(b)
- if c.proto == "udp" && err == os.EOF {
+ if c.proto == "udp" && err == io.EOF {
n = 0
err = nil
}
}
// Write implements the net.Conn Write method.
-func (c *plan9Conn) Write(b []byte) (n int, err os.Error) {
+func (c *plan9Conn) Write(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Close closes the connection.
-func (c *plan9Conn) Close() os.Error {
+func (c *plan9Conn) Close() error {
if !c.ok() {
return os.EINVAL
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *plan9Conn) SetTimeout(nsec int64) os.Error {
+func (c *plan9Conn) SetTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *plan9Conn) SetReadTimeout(nsec int64) os.Error {
+func (c *plan9Conn) SetReadTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *plan9Conn) SetWriteTimeout(nsec int64) os.Error {
+func (c *plan9Conn) SetWriteTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
return os.EPLAN9
}
-func startPlan9(net string, addr Addr) (ctl *os.File, dest, proto, name string, err os.Error) {
+func startPlan9(net string, addr Addr) (ctl *os.File, dest, proto, name string, err error) {
var (
ip IP
port int
return f, dest, proto, string(buf[:n]), nil
}
-func dialPlan9(net string, laddr, raddr Addr) (c *plan9Conn, err os.Error) {
+func dialPlan9(net string, laddr, raddr Addr) (c *plan9Conn, err error) {
f, dest, proto, name, err := startPlan9(net, raddr)
if err != nil {
return
laddr Addr
}
-func listenPlan9(net string, laddr Addr) (l *plan9Listener, err os.Error) {
+func listenPlan9(net string, laddr Addr) (l *plan9Listener, err error) {
f, dest, proto, name, err := startPlan9(net, laddr)
if err != nil {
return
return newPlan9Conn(l.proto, l.name, l.ctl, l.laddr, nil)
}
-func (l *plan9Listener) acceptPlan9() (c *plan9Conn, err os.Error) {
+func (l *plan9Listener) acceptPlan9() (c *plan9Conn, err error) {
f, err := os.Open(l.dir + "/listen")
if err != nil {
return
return newPlan9Conn(l.proto, name, f, laddr, raddr), nil
}
-func (l *plan9Listener) Accept() (c Conn, err os.Error) {
+func (l *plan9Listener) Accept() (c Conn, err error) {
c1, err := l.acceptPlan9()
if err != nil {
return
return c1, nil
}
-func (l *plan9Listener) Close() os.Error {
+func (l *plan9Listener) Close() error {
if l == nil || l.ctl == nil {
return os.EINVAL
}
package net
-import (
- "os"
- "syscall"
-)
+import "syscall"
// Should we try to use the IPv4 socket interface if we're
// only dealing with IPv4 sockets? As long as the host system
// be converted into a syscall.Sockaddr.
type sockaddr interface {
Addr
- sockaddr(family int) (syscall.Sockaddr, os.Error)
+ sockaddr(family int) (syscall.Sockaddr, error)
family() int
}
-func internetSocket(net string, laddr, raddr sockaddr, socktype, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) {
- var oserr os.Error
+func internetSocket(net string, laddr, raddr sockaddr, socktype, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err error) {
+ var oserr error
var la, ra syscall.Sockaddr
family := favoriteAddrFamily(net, raddr, laddr, mode)
if laddr != nil {
return nil, &OpError{mode, net, addr, oserr}
}
-func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) {
+func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, error) {
switch family {
case syscall.AF_INET:
if len(ip) == 0 {
package net
import (
+ "errors"
"os"
)
-func query(filename, query string, bufSize int) (res []string, err os.Error) {
+func query(filename, query string, bufSize int) (res []string, err error) {
file, err := os.OpenFile(filename, os.O_RDWR, 0)
if err != nil {
return
return
}
-func queryCS(net, host, service string) (res []string, err os.Error) {
+func queryCS(net, host, service string) (res []string, err error) {
switch net {
case "tcp4", "tcp6":
net = "tcp"
return query("/net/cs", net+"!"+host+"!"+service, 128)
}
-func queryCS1(net string, ip IP, port int) (clone, dest string, err os.Error) {
+func queryCS1(net string, ip IP, port int) (clone, dest string, err error) {
ips := "*"
if len(ip) != 0 && !ip.IsUnspecified() {
ips = ip.String()
}
f := getFields(lines[0])
if len(f) < 2 {
- return "", "", os.NewError("net: bad response from ndb/cs")
+ return "", "", errors.New("net: bad response from ndb/cs")
}
clone, dest = f[0], f[1]
return
}
-func queryDNS(addr string, typ string) (res []string, err os.Error) {
+func queryDNS(addr string, typ string) (res []string, err error) {
return query("/net/dns", addr+" "+typ, 1024)
}
// LookupHost looks up the given host using the local resolver.
// It returns an array of that host's addresses.
-func LookupHost(host string) (addrs []string, err os.Error) {
+func LookupHost(host string) (addrs []string, err error) {
// Use /net/cs insead of /net/dns because cs knows about
// host names in local network (e.g. from /lib/ndb/local)
lines, err := queryCS("tcp", host, "1")
// LookupIP looks up host using the local resolver.
// It returns an array of that host's IPv4 and IPv6 addresses.
-func LookupIP(host string) (ips []IP, err os.Error) {
+func LookupIP(host string) (ips []IP, err error) {
addrs, err := LookupHost(host)
if err != nil {
return
}
// LookupPort looks up the port for the given network and service.
-func LookupPort(network, service string) (port int, err os.Error) {
+func LookupPort(network, service string) (port int, err error) {
switch network {
case "tcp4", "tcp6":
network = "tcp"
// Callers that do not care about the canonical name can call
// LookupHost or LookupIP directly; both take care of resolving
// the canonical name as part of the lookup.
-func LookupCNAME(name string) (cname string, err os.Error) {
+func LookupCNAME(name string) (cname string, err error) {
lines, err := queryDNS(name, "cname")
if err != nil {
return
return f[2] + ".", nil
}
}
- return "", os.NewError("net: bad response from ndb/dns")
+ return "", errors.New("net: bad response from ndb/dns")
}
// LookupSRV tries to resolve an SRV query of the given service,
// That is, it looks up _service._proto.name. To accommodate services
// publishing SRV records under non-standard names, if both service
// and proto are empty strings, LookupSRV looks up name directly.
-func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) {
+func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) {
var target string
if service == "" && proto == "" {
target = name
}
// LookupMX returns the DNS MX records for the given domain name sorted by preference.
-func LookupMX(name string) (mx []*MX, err os.Error) {
+func LookupMX(name string) (mx []*MX, err error) {
lines, err := queryDNS(name, "mx")
if err != nil {
return
}
// LookupTXT returns the DNS TXT records for the given domain name.
-func LookupTXT(name string) (txt []string, err os.Error) {
+func LookupTXT(name string) (txt []string, err error) {
lines, err := queryDNS(name, "txt")
if err != nil {
return
// LookupAddr performs a reverse lookup for the given address, returning a list
// of names mapping to that address.
-func LookupAddr(addr string) (name []string, err os.Error) {
+func LookupAddr(addr string) (name []string, err error) {
arpa, err := reverseaddr(addr)
if err != nil {
return
package net
import (
- "os"
+ "errors"
"sync"
)
// lookupProtocol looks up IP protocol name in /etc/protocols and
// returns correspondent protocol number.
-func lookupProtocol(name string) (proto int, err os.Error) {
+func lookupProtocol(name string) (proto int, err error) {
onceReadProtocols.Do(readProtocols)
proto, found := protocols[name]
if !found {
- return 0, os.NewError("unknown IP protocol specified: " + name)
+ return 0, errors.New("unknown IP protocol specified: " + name)
}
return
}
// LookupHost looks up the given host using the local resolver.
// It returns an array of that host's addresses.
-func LookupHost(host string) (addrs []string, err os.Error) {
+func LookupHost(host string) (addrs []string, err error) {
addrs, err, ok := cgoLookupHost(host)
if !ok {
addrs, err = goLookupHost(host)
// LookupIP looks up host using the local resolver.
// It returns an array of that host's IPv4 and IPv6 addresses.
-func LookupIP(host string) (addrs []IP, err os.Error) {
+func LookupIP(host string) (addrs []IP, err error) {
addrs, err, ok := cgoLookupIP(host)
if !ok {
addrs, err = goLookupIP(host)
}
// LookupPort looks up the port for the given network and service.
-func LookupPort(network, service string) (port int, err os.Error) {
+func LookupPort(network, service string) (port int, err error) {
port, err, ok := cgoLookupPort(network, service)
if !ok {
port, err = goLookupPort(network, service)
// Callers that do not care about the canonical name can call
// LookupHost or LookupIP directly; both take care of resolving
// the canonical name as part of the lookup.
-func LookupCNAME(name string) (cname string, err os.Error) {
+func LookupCNAME(name string) (cname string, err error) {
cname, err, ok := cgoLookupCNAME(name)
if !ok {
cname, err = goLookupCNAME(name)
// That is, it looks up _service._proto.name. To accommodate services
// publishing SRV records under non-standard names, if both service
// and proto are empty strings, LookupSRV looks up name directly.
-func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) {
+func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) {
var target string
if service == "" && proto == "" {
target = name
}
// LookupMX returns the DNS MX records for the given domain name sorted by preference.
-func LookupMX(name string) (mx []*MX, err os.Error) {
+func LookupMX(name string) (mx []*MX, err error) {
_, records, err := lookup(name, dnsTypeMX)
if err != nil {
return
}
// LookupTXT returns the DNS TXT records for the given domain name.
-func LookupTXT(name string) (txt []string, err os.Error) {
+func LookupTXT(name string) (txt []string, err error) {
_, records, err := lookup(name, dnsTypeTXT)
if err != nil {
return
// LookupAddr performs a reverse lookup for the given address, returning a list
// of names mapping to that address.
-func LookupAddr(addr string) (name []string, err os.Error) {
+func LookupAddr(addr string) (name []string, err error) {
name = lookupStaticAddr(addr)
if len(name) > 0 {
return
package net
import (
+ "errors"
"syscall"
"unsafe"
"os"
)
// lookupProtocol looks up IP protocol name and returns correspondent protocol number.
-func lookupProtocol(name string) (proto int, err os.Error) {
+func lookupProtocol(name string) (proto int, err error) {
protoentLock.Lock()
defer protoentLock.Unlock()
p, e := syscall.GetProtoByName(name)
return int(p.Proto), nil
}
-func LookupHost(name string) (addrs []string, err os.Error) {
+func LookupHost(name string) (addrs []string, err error) {
ips, err := LookupIP(name)
if err != nil {
return
return
}
-func LookupIP(name string) (addrs []IP, err os.Error) {
+func LookupIP(name string) (addrs []IP, err error) {
hostentLock.Lock()
defer hostentLock.Unlock()
h, e := syscall.GetHostByName(name)
return addrs, nil
}
-func LookupPort(network, service string) (port int, err os.Error) {
+func LookupPort(network, service string) (port int, err error) {
switch network {
case "tcp4", "tcp6":
network = "tcp"
return int(syscall.Ntohs(s.Port)), nil
}
-func LookupCNAME(name string) (cname string, err os.Error) {
+func LookupCNAME(name string) (cname string, err error) {
var r *syscall.DNSRecord
e := syscall.DnsQuery(name, syscall.DNS_TYPE_CNAME, 0, nil, &r, nil)
if int(e) != 0 {
// That is, it looks up _service._proto.name. To accommodate services
// publishing SRV records under non-standard names, if both service
// and proto are empty strings, LookupSRV looks up name directly.
-func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) {
+func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) {
var target string
if service == "" && proto == "" {
target = name
return name, addrs, nil
}
-func LookupMX(name string) (mx []*MX, err os.Error) {
+func LookupMX(name string) (mx []*MX, err error) {
var r *syscall.DNSRecord
e := syscall.DnsQuery(name, syscall.DNS_TYPE_MX, 0, nil, &r, nil)
if int(e) != 0 {
return mx, nil
}
-func LookupTXT(name string) (txt []string, err os.Error) {
- return nil, os.NewError("net.LookupTXT is not implemented on Windows")
+func LookupTXT(name string) (txt []string, err error) {
+ return nil, errors.New("net.LookupTXT is not implemented on Windows")
}
-func LookupAddr(addr string) (name []string, err os.Error) {
+func LookupAddr(addr string) (name []string, err error) {
arpa, err := reverseaddr(addr)
if err != nil {
return nil, err
// TODO(rsc):
// support for raw ethernet sockets
-import "os"
+import "errors"
// Addr represents a network end point address.
type Addr interface {
// Read reads data from the connection.
// Read can be made to time out and return a net.Error with Timeout() == true
// after a fixed time limit; see SetTimeout and SetReadTimeout.
- Read(b []byte) (n int, err os.Error)
+ Read(b []byte) (n int, err error)
// Write writes data to the connection.
// Write can be made to time out and return a net.Error with Timeout() == true
// after a fixed time limit; see SetTimeout and SetWriteTimeout.
- Write(b []byte) (n int, err os.Error)
+ Write(b []byte) (n int, err error)
// Close closes the connection.
- Close() os.Error
+ Close() error
// LocalAddr returns the local network address.
LocalAddr() Addr
// SetTimeout sets the read and write deadlines associated
// with the connection.
- SetTimeout(nsec int64) os.Error
+ SetTimeout(nsec int64) error
// SetReadTimeout sets the time (in nanoseconds) that
// Read will wait for data before returning an error with Timeout() == true.
// Setting nsec == 0 (the default) disables the deadline.
- SetReadTimeout(nsec int64) os.Error
+ SetReadTimeout(nsec int64) error
// SetWriteTimeout sets the time (in nanoseconds) that
// Write will wait to send its data before returning an error with Timeout() == true.
// Setting nsec == 0 (the default) disables the deadline.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
- SetWriteTimeout(nsec int64) os.Error
+ SetWriteTimeout(nsec int64) error
}
// An Error represents a network error.
type Error interface {
- os.Error
+ error
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
}
// ReadFrom can be made to time out and return
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetReadTimeout.
- ReadFrom(b []byte) (n int, addr Addr, err os.Error)
+ ReadFrom(b []byte) (n int, addr Addr, err error)
// WriteTo writes a packet with payload b to addr.
// WriteTo can be made to time out and return
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
- WriteTo(b []byte, addr Addr) (n int, err os.Error)
+ WriteTo(b []byte, addr Addr) (n int, err error)
// Close closes the connection.
- Close() os.Error
+ Close() error
// LocalAddr returns the local network address.
LocalAddr() Addr
// SetTimeout sets the read and write deadlines associated
// with the connection.
- SetTimeout(nsec int64) os.Error
+ SetTimeout(nsec int64) error
// SetReadTimeout sets the time (in nanoseconds) that
// Read will wait for data before returning an error with Timeout() == true.
// Setting nsec == 0 (the default) disables the deadline.
- SetReadTimeout(nsec int64) os.Error
+ SetReadTimeout(nsec int64) error
// SetWriteTimeout sets the time (in nanoseconds) that
// Write will wait to send its data before returning an error with Timeout() == true.
// Setting nsec == 0 (the default) disables the deadline.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
- SetWriteTimeout(nsec int64) os.Error
+ SetWriteTimeout(nsec int64) error
}
// A Listener is a generic network listener for stream-oriented protocols.
type Listener interface {
// Accept waits for and returns the next connection to the listener.
- Accept() (c Conn, err os.Error)
+ Accept() (c Conn, err error)
// Close closes the listener.
- Close() os.Error
+ Close() error
// Addr returns the listener's network address.
Addr() Addr
}
-var errMissingAddress = os.NewError("missing address")
+var errMissingAddress = errors.New("missing address")
type OpError struct {
- Op string
- Net string
- Addr Addr
- Error os.Error
+ Op string
+ Net string
+ Addr Addr
+ Err error
}
-func (e *OpError) String() string {
+func (e *OpError) Error() string {
if e == nil {
return "<nil>"
}
if e.Addr != nil {
s += " " + e.Addr.String()
}
- s += ": " + e.Error.String()
+ s += ": " + e.Err.Error()
return s
}
}
func (e *OpError) Temporary() bool {
- t, ok := e.Error.(temporary)
+ t, ok := e.Err.(temporary)
return ok && t.Temporary()
}
}
func (e *OpError) Timeout() bool {
- t, ok := e.Error.(timeout)
+ t, ok := e.Err.(timeout)
return ok && t.Timeout()
}
type AddrError struct {
- Error string
- Addr string
+ Err string
+ Addr string
}
-func (e *AddrError) String() string {
+func (e *AddrError) Error() string {
if e == nil {
return "<nil>"
}
- s := e.Error
+ s := e.Err
if e.Addr != "" {
s += " " + e.Addr
}
type UnknownNetworkError string
-func (e UnknownNetworkError) String() string { return "unknown network " + string(e) }
+func (e UnknownNetworkError) Error() string { return "unknown network " + string(e) }
func (e UnknownNetworkError) Temporary() bool { return false }
func (e UnknownNetworkError) Timeout() bool { return false }
import (
"flag"
- "os"
+ "io"
"regexp"
"runtime"
"testing"
t.Errorf("#%d: nil error, want match for %#q", i, tt.Pattern)
continue
}
- s := e.String()
+ s := e.Error()
match, _ := regexp.MatchString(tt.Pattern, s)
if !match {
t.Errorf("#%d: %q, want match for %#q", i, s, tt.Pattern)
if len(tt.ErrPrefix) == 0 && e != nil {
t.Errorf("#%d: expected <nil>, got %q (error)", i, e)
}
- if e != nil && e.(*DNSError).Error != tt.ErrPrefix {
- t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, e.(*DNSError).Error)
+ if e != nil && e.(*DNSError).Err != tt.ErrPrefix {
+ t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, e.(*DNSError).Err)
}
if a != tt.Reverse {
t.Errorf("#%d: expected %q, got %q (reverse address)", i, tt.Reverse, a)
}
var buf [10]byte
n, err := c.Read(buf[:])
- if n != 0 || err != os.EOF {
+ if n != 0 || err != io.EOF {
t.Fatalf("server Read = %d, %v; want 0, os.EOF", n, err)
}
c.Write([]byte("response"))
"syscall"
)
-func newPollServer() (s *pollServer, err os.Error) {
+func newPollServer() (s *pollServer, err error) {
s = new(pollServer)
s.cr = make(chan *netFD, 1)
s.cw = make(chan *netFD, 1)
if n >= 0 {
f.data = f.data[0 : ln+n]
}
- if err == os.EOF {
+ if err == io.EOF {
f.atEOF = true
}
}
return
}
-func open(name string) (*file, os.Error) {
+func open(name string) (*file, error) {
fd, err := os.Open(name)
if err != nil {
return nil, err
package net
import (
+ "errors"
"io"
- "os"
)
// Pipe creates a synchronous, in-memory, full duplex
return "pipe"
}
-func (p *pipe) Close() os.Error {
+func (p *pipe) Close() error {
err := p.PipeReader.Close()
err1 := p.PipeWriter.Close()
if err == nil {
return pipeAddr(0)
}
-func (p *pipe) SetTimeout(nsec int64) os.Error {
- return os.NewError("net.Pipe does not support timeouts")
+func (p *pipe) SetTimeout(nsec int64) error {
+ return errors.New("net.Pipe does not support timeouts")
}
-func (p *pipe) SetReadTimeout(nsec int64) os.Error {
- return os.NewError("net.Pipe does not support timeouts")
+func (p *pipe) SetReadTimeout(nsec int64) error {
+ return errors.New("net.Pipe does not support timeouts")
}
-func (p *pipe) SetWriteTimeout(nsec int64) os.Error {
- return os.NewError("net.Pipe does not support timeouts")
+func (p *pipe) SetWriteTimeout(nsec int64) error {
+ return errors.New("net.Pipe does not support timeouts")
}
import (
"bytes"
"io"
- "os"
"testing"
)
c <- 0
}
-func checkRead(t *testing.T, r io.Reader, data []byte, wantErr os.Error) {
+func checkRead(t *testing.T, r io.Reader, data []byte, wantErr error) {
buf := make([]byte, len(data)+10)
n, err := r.Read(buf)
if err != wantErr {
checkRead(t, srv, []byte("a third line"), nil)
<-c
go srv.Close()
- checkRead(t, cli, nil, os.EOF)
+ checkRead(t, cli, nil, io.EOF)
cli.Close()
}
package net
-import (
- "os"
- "sync"
-)
+import "sync"
var services map[string]map[string]int
-var servicesError os.Error
+var servicesError error
var onceReadServices sync.Once
func readServices() {
}
// goLookupPort is the native Go implementation of LookupPort.
-func goLookupPort(network, service string) (port int, err os.Error) {
+func goLookupPort(network, service string) (port int, err error) {
onceReadServices.Do(readServices)
switch network {
// non-EOF error.
//
// if handled == false, sendFile performed no work.
-func sendFile(c *netFD, r io.Reader) (written int64, err os.Error, handled bool) {
+func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool) {
var remain int64 = 1 << 62 // by default, copy until EOF
lr, ok := r.(*io.LimitedReader)
package net
-import (
- "io"
- "os"
-)
+import "io"
-func sendFile(c *netFD, r io.Reader) (n int64, err os.Error, handled bool) {
+func sendFile(c *netFD, r io.Reader) (n int64, err error, handled bool) {
return 0, nil, false
}
// if handled == false, sendFile performed no work.
//
// Note that sendfile for windows does not suppport >2GB file.
-func sendFile(c *netFD, r io.Reader) (written int64, err os.Error, handled bool) {
+func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool) {
var n int64 = 0 // by default, copy until EOF
lr, ok := r.(*io.LimitedReader)
func connect(t *testing.T, network, addr string, isEmpty bool) {
var fd Conn
- var err os.Error
+ var err error
if network == "unixgram" {
fd, err = DialUnix(network, &UnixAddr{addr + ".local", network}, &UnixAddr{addr, network})
} else {
}
// Generic socket creation.
-func socket(net string, f, p, t int, la, ra syscall.Sockaddr, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) {
+func socket(net string, f, p, t int, la, ra syscall.Sockaddr, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err error) {
// See ../syscall/exec.go for description of ForkLock.
syscall.ForkLock.RLock()
s, e := syscall.Socket(f, p, t)
return fd, nil
}
-func setsockoptInt(fd *netFD, level, opt int, value int) os.Error {
+func setsockoptInt(fd *netFD, level, opt int, value int) error {
return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, level, opt, value))
}
-func setsockoptNsec(fd *netFD, level, opt int, nsec int64) os.Error {
+func setsockoptNsec(fd *netFD, level, opt int, nsec int64) error {
var tv = syscall.NsecToTimeval(nsec)
return os.NewSyscallError("setsockopt", syscall.SetsockoptTimeval(fd.sysfd, level, opt, &tv))
}
-func setReadBuffer(fd *netFD, bytes int) os.Error {
+func setReadBuffer(fd *netFD, bytes int) error {
fd.incref()
defer fd.decref()
return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes)
}
-func setWriteBuffer(fd *netFD, bytes int) os.Error {
+func setWriteBuffer(fd *netFD, bytes int) error {
fd.incref()
defer fd.decref()
return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes)
}
-func setReadTimeout(fd *netFD, nsec int64) os.Error {
+func setReadTimeout(fd *netFD, nsec int64) error {
fd.rdeadline_delta = nsec
return nil
}
-func setWriteTimeout(fd *netFD, nsec int64) os.Error {
+func setWriteTimeout(fd *netFD, nsec int64) error {
fd.wdeadline_delta = nsec
return nil
}
-func setTimeout(fd *netFD, nsec int64) os.Error {
+func setTimeout(fd *netFD, nsec int64) error {
if e := setReadTimeout(fd, nsec); e != nil {
return e
}
return setWriteTimeout(fd, nsec)
}
-func setReuseAddr(fd *netFD, reuse bool) os.Error {
+func setReuseAddr(fd *netFD, reuse bool) error {
fd.incref()
defer fd.decref()
return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, boolint(reuse))
}
-func bindToDevice(fd *netFD, dev string) os.Error {
+func bindToDevice(fd *netFD, dev string) error {
// TODO(rsc): call setsockopt with null-terminated string pointer
return os.EINVAL
}
-func setDontRoute(fd *netFD, dontroute bool) os.Error {
+func setDontRoute(fd *netFD, dontroute bool) error {
fd.incref()
defer fd.decref()
return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_DONTROUTE, boolint(dontroute))
}
-func setKeepAlive(fd *netFD, keepalive bool) os.Error {
+func setKeepAlive(fd *netFD, keepalive bool) error {
fd.incref()
defer fd.decref()
return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive))
}
-func setNoDelay(fd *netFD, noDelay bool) os.Error {
+func setNoDelay(fd *netFD, noDelay bool) error {
fd.incref()
defer fd.decref()
return setsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_NODELAY, boolint(noDelay))
}
-func setLinger(fd *netFD, sec int) os.Error {
+func setLinger(fd *netFD, sec int) error {
var l syscall.Linger
if sec >= 0 {
l.Onoff = 1
sa syscall.Sockaddr
}
-func (e *UnknownSocketError) String() string {
+func (e *UnknownSocketError) Error() string {
return "unknown socket address type " + reflect.TypeOf(e.sa).String()
}
// Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't
// applicable.
-func genericReadFrom(w io.Writer, r io.Reader) (n int64, err os.Error) {
+func genericReadFrom(w io.Writer, r io.Reader) (n int64, err error) {
// Use wrapper to hide existing r.ReadFrom from io.Copy.
return io.Copy(writerOnly{w}, r)
}
package net
-import (
- "os"
-)
-
// TCPAddr represents the address of a TCP end point.
type TCPAddr struct {
IP IP
// numeric addresses on the network net, which must be "tcp",
// "tcp4" or "tcp6". A literal IPv6 host address must be
// enclosed in square brackets, as in "[::]:80".
-func ResolveTCPAddr(net, addr string) (*TCPAddr, os.Error) {
+func ResolveTCPAddr(net, addr string) (*TCPAddr, error) {
ip, port, err := hostPortToIP(net, addr)
if err != nil {
return nil, err
// CloseRead shuts down the reading side of the TCP connection.
// Most callers should just use Close.
-func (c *TCPConn) CloseRead() os.Error {
+func (c *TCPConn) CloseRead() error {
if !c.ok() {
return os.EINVAL
}
// CloseWrite shuts down the writing side of the TCP connection.
// Most callers should just use Close.
-func (c *TCPConn) CloseWrite() os.Error {
+func (c *TCPConn) CloseWrite() error {
if !c.ok() {
return os.EINVAL
}
// DialTCP connects to the remote address raddr on the network net,
// which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
// as the local address for the connection.
-func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) {
+func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err error) {
switch net {
case "tcp", "tcp4", "tcp6":
default:
// Net must be "tcp", "tcp4", or "tcp6".
// If laddr has a port of 0, it means to listen on some available port.
// The caller can use l.Addr() to retrieve the chosen address.
-func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) {
+func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err error) {
switch net {
case "tcp", "tcp4", "tcp6":
default:
return syscall.AF_INET6
}
-func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) {
+func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
return ipToSockaddr(family, a.IP, a.Port)
}
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *TCPConn) Read(b []byte) (n int, err os.Error) {
+func (c *TCPConn) Read(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// ReadFrom implements the io.ReaderFrom ReadFrom method.
-func (c *TCPConn) ReadFrom(r io.Reader) (int64, os.Error) {
+func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) {
if n, err, handled := sendFile(c.fd, r); handled {
return n, err
}
}
// Write implements the net.Conn Write method.
-func (c *TCPConn) Write(b []byte) (n int, err os.Error) {
+func (c *TCPConn) Write(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Close closes the TCP connection.
-func (c *TCPConn) Close() os.Error {
+func (c *TCPConn) Close() error {
if !c.ok() {
return os.EINVAL
}
// CloseRead shuts down the reading side of the TCP connection.
// Most callers should just use Close.
-func (c *TCPConn) CloseRead() os.Error {
+func (c *TCPConn) CloseRead() error {
if !c.ok() {
return os.EINVAL
}
// CloseWrite shuts down the writing side of the TCP connection.
// Most callers should just use Close.
-func (c *TCPConn) CloseWrite() os.Error {
+func (c *TCPConn) CloseWrite() error {
if !c.ok() {
return os.EINVAL
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *TCPConn) SetTimeout(nsec int64) os.Error {
+func (c *TCPConn) SetTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *TCPConn) SetReadTimeout(nsec int64) os.Error {
+func (c *TCPConn) SetReadTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *TCPConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *TCPConn) SetWriteTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
-func (c *TCPConn) SetReadBuffer(bytes int) os.Error {
+func (c *TCPConn) SetReadBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
-func (c *TCPConn) SetWriteBuffer(bytes int) os.Error {
+func (c *TCPConn) SetWriteBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
//
// If sec > 0, Close blocks for at most sec seconds waiting for
// data to be sent and acknowledged.
-func (c *TCPConn) SetLinger(sec int) os.Error {
+func (c *TCPConn) SetLinger(sec int) error {
if !c.ok() {
return os.EINVAL
}
// SetKeepAlive sets whether the operating system should send
// keepalive messages on the connection.
-func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error {
+func (c *TCPConn) SetKeepAlive(keepalive bool) error {
if !c.ok() {
return os.EINVAL
}
// packet transmission in hopes of sending fewer packets
// (Nagle's algorithm). The default is true (no delay), meaning
// that data is sent as soon as possible after a Write.
-func (c *TCPConn) SetNoDelay(noDelay bool) os.Error {
+func (c *TCPConn) SetNoDelay(noDelay bool) error {
if !c.ok() {
return os.EINVAL
}
// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
-func (c *TCPConn) File() (f *os.File, err os.Error) { return c.fd.dup() }
+func (c *TCPConn) File() (f *os.File, err error) { return c.fd.dup() }
// DialTCP connects to the remote address raddr on the network net,
// which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
// as the local address for the connection.
-func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) {
+func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err error) {
if raddr == nil {
return nil, &OpError{"dial", "tcp", nil, errMissingAddress}
}
// Net must be "tcp", "tcp4", or "tcp6".
// If laddr has a port of 0, it means to listen on some available port.
// The caller can use l.Addr() to retrieve the chosen address.
-func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) {
+func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err error) {
fd, err := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_STREAM, 0, "listen", sockaddrToTCP)
if err != nil {
return nil, err
// AcceptTCP accepts the next incoming call and returns the new connection
// and the remote address.
-func (l *TCPListener) AcceptTCP() (c *TCPConn, err os.Error) {
+func (l *TCPListener) AcceptTCP() (c *TCPConn, err error) {
if l == nil || l.fd == nil || l.fd.sysfd < 0 {
return nil, os.EINVAL
}
// Accept implements the Accept method in the Listener interface;
// it waits for the next call and returns a generic Conn.
-func (l *TCPListener) Accept() (c Conn, err os.Error) {
+func (l *TCPListener) Accept() (c Conn, err error) {
c1, err := l.AcceptTCP()
if err != nil {
return nil, err
// Close stops listening on the TCP address.
// Already Accepted connections are not closed.
-func (l *TCPListener) Close() os.Error {
+func (l *TCPListener) Close() error {
if l == nil || l.fd == nil {
return os.EINVAL
}
func (l *TCPListener) Addr() Addr { return l.fd.laddr }
// SetTimeout sets the deadline associated with the listener
-func (l *TCPListener) SetTimeout(nsec int64) os.Error {
+func (l *TCPListener) SetTimeout(nsec int64) error {
if l == nil || l.fd == nil {
return os.EINVAL
}
// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
-func (l *TCPListener) File() (f *os.File, err os.Error) { return l.fd.dup() }
+func (l *TCPListener) File() (f *os.File, err error) { return l.fd.dup() }
"bytes"
"io"
"io/ioutil"
- "os"
"strconv"
"strings"
)
// ReadLine reads a single line from r,
// eliding the final \n or \r\n from the returned string.
-func (r *Reader) ReadLine() (string, os.Error) {
+func (r *Reader) ReadLine() (string, error) {
line, err := r.readLineSlice()
return string(line), err
}
// ReadLineBytes is like ReadLine but returns a []byte instead of a string.
-func (r *Reader) ReadLineBytes() ([]byte, os.Error) {
+func (r *Reader) ReadLineBytes() ([]byte, error) {
line, err := r.readLineSlice()
if line != nil {
buf := make([]byte, len(line))
return line, err
}
-func (r *Reader) readLineSlice() ([]byte, os.Error) {
+func (r *Reader) readLineSlice() ([]byte, error) {
r.closeDot()
var line []byte
for {
//
// A line consisting of only white space is never continued.
//
-func (r *Reader) ReadContinuedLine() (string, os.Error) {
+func (r *Reader) ReadContinuedLine() (string, error) {
line, err := r.readContinuedLineSlice()
return string(line), err
}
// ReadContinuedLineBytes is like ReadContinuedLine but
// returns a []byte instead of a string.
-func (r *Reader) ReadContinuedLineBytes() ([]byte, os.Error) {
+func (r *Reader) ReadContinuedLineBytes() ([]byte, error) {
line, err := r.readContinuedLineSlice()
if line != nil {
buf := make([]byte, len(line))
return line, err
}
-func (r *Reader) readContinuedLineSlice() ([]byte, os.Error) {
+func (r *Reader) readContinuedLineSlice() ([]byte, error) {
// Read the first line.
line, err := r.readLineSlice()
if err != nil {
return line, err
}
-func (r *Reader) readCodeLine(expectCode int) (code int, continued bool, message string, err os.Error) {
+func (r *Reader) readCodeLine(expectCode int) (code int, continued bool, message string, err error) {
line, err := r.ReadLine()
if err != nil {
return
return parseCodeLine(line, expectCode)
}
-func parseCodeLine(line string, expectCode int) (code int, continued bool, message string, err os.Error) {
+func parseCodeLine(line string, expectCode int) (code int, continued bool, message string, err error) {
if len(line) < 4 || line[3] != ' ' && line[3] != '-' {
err = ProtocolError("short response: " + line)
return
//
// An expectCode <= 0 disables the check of the status code.
//
-func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err os.Error) {
+func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error) {
code, continued, message, err := r.readCodeLine(expectCode)
if err == nil && continued {
err = ProtocolError("unexpected multi-line response: " + message)
//
// An expectCode <= 0 disables the check of the status code.
//
-func (r *Reader) ReadResponse(expectCode int) (code int, message string, err os.Error) {
+func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error) {
code, continued, message, err := r.readCodeLine(expectCode)
for err == nil && continued {
line, err := r.ReadLine()
}
// Read satisfies reads by decoding dot-encoded data read from d.r.
-func (d *dotReader) Read(b []byte) (n int, err os.Error) {
+func (d *dotReader) Read(b []byte) (n int, err error) {
// Run data through a simple state machine to
// elide leading dots, rewrite trailing \r\n into \n,
// and detect ending .\r\n line.
var c byte
c, err = br.ReadByte()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
break
n++
}
if err == nil && d.state == stateEOF {
- err = os.EOF
+ err = io.EOF
}
if err != nil && d.r.dot == d {
d.r.dot = nil
// ReadDotBytes reads a dot-encoding and returns the decoded data.
//
// See the documentation for the DotReader method for details about dot-encoding.
-func (r *Reader) ReadDotBytes() ([]byte, os.Error) {
+func (r *Reader) ReadDotBytes() ([]byte, error) {
return ioutil.ReadAll(r.DotReader())
}
// containing the decoded lines, with the final \r\n or \n elided from each.
//
// See the documentation for the DotReader method for details about dot-encoding.
-func (r *Reader) ReadDotLines() ([]string, os.Error) {
+func (r *Reader) ReadDotLines() ([]string, error) {
// We could use ReadDotBytes and then Split it,
// but reading a line at a time avoids needing a
// large contiguous block of memory and is simpler.
var v []string
- var err os.Error
+ var err error
for {
var line string
line, err = r.ReadLine()
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
break
// "Long-Key": {"Even Longer Value"},
// }
//
-func (r *Reader) ReadMIMEHeader() (MIMEHeader, os.Error) {
+func (r *Reader) ReadMIMEHeader() (MIMEHeader, error) {
m := make(MIMEHeader)
for {
kv, err := r.readContinuedLineSlice()
import (
"bufio"
"io"
- "os"
"reflect"
"strings"
"testing"
t.Fatalf("Line 2: %s, %v", s, err)
}
s, err = r.ReadLine()
- if s != "" || err != os.EOF {
+ if s != "" || err != io.EOF {
t.Fatalf("EOF: %s, %v", s, err)
}
}
t.Fatalf("Line 3: %s, %v", s, err)
}
s, err = r.ReadContinuedLine()
- if s != "" || err != os.EOF {
+ if s != "" || err != io.EOF {
t.Fatalf("EOF: %s, %v", s, err)
}
}
t.Fatalf("Line 3: wrong error %v\n", err)
}
code, msg, err = r.ReadCodeLine(1)
- if code != 0 || msg != "" || err != os.EOF {
+ if code != 0 || msg != "" || err != io.EOF {
t.Fatalf("EOF: %d, %s, %v", code, msg, err)
}
}
"fmt"
"io"
"net"
- "os"
)
// An Error represents a numeric error response from a server.
Msg string
}
-func (e *Error) String() string {
+func (e *Error) Error() string {
return fmt.Sprintf("%03d %s", e.Code, e.Msg)
}
// as an invalid response or a hung-up connection.
type ProtocolError string
-func (p ProtocolError) String() string {
+func (p ProtocolError) Error() string {
return string(p)
}
}
// Close closes the connection.
-func (c *Conn) Close() os.Error {
+func (c *Conn) Close() error {
return c.conn.Close()
}
// Dial connects to the given address on the given network using net.Dial
// and then returns a new Conn for the connection.
-func Dial(network, addr string) (*Conn, os.Error) {
+func Dial(network, addr string) (*Conn, error) {
c, err := net.Dial(network, addr)
if err != nil {
return nil, err
// }
// return c.ReadCodeLine(250)
//
-func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err os.Error) {
+func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err error) {
id = c.Next()
c.StartRequest(id)
err = c.PrintfLine(format, args...)
"bufio"
"fmt"
"io"
- "os"
)
// A Writer implements convenience methods for writing
var dotcrnl = []byte{'.', '\r', '\n'}
// PrintfLine writes the formatted output followed by \r\n.
-func (w *Writer) PrintfLine(format string, args ...interface{}) os.Error {
+func (w *Writer) PrintfLine(format string, args ...interface{}) error {
w.closeDot()
fmt.Fprintf(w.W, format, args...)
w.W.Write(crnl)
wstateData // writing data in middle of line
)
-func (d *dotWriter) Write(b []byte) (n int, err os.Error) {
+func (d *dotWriter) Write(b []byte) (n int, err error) {
bw := d.w.W
for n < len(b) {
c := b[n]
return
}
-func (d *dotWriter) Close() os.Error {
+func (d *dotWriter) Close() error {
if d.w.dot == d {
d.w.dot = nil
}
package net
import (
- "os"
"runtime"
"testing"
"time"
fd.SetReadTimeout(1e8) // 100ms
var b [100]byte
var n int
- var err1 os.Error
+ var err1 error
if readFrom {
n, _, err1 = fd.(PacketConn).ReadFrom(b[0:])
} else {
package net
-import (
- "os"
-)
-
// UDPAddr represents the address of a UDP end point.
type UDPAddr struct {
IP IP
// numeric addresses on the network net, which must be "udp",
// "udp4" or "udp6". A literal IPv6 host address must be
// enclosed in square brackets, as in "[::]:80".
-func ResolveUDPAddr(net, addr string) (*UDPAddr, os.Error) {
+func ResolveUDPAddr(net, addr string) (*UDPAddr, error) {
ip, port, err := hostPortToIP(net, addr)
if err != nil {
return nil, err
package net
import (
+ "errors"
"os"
)
//
// ReadFromUDP can be made to time out and return an error with Timeout() == true
// after a fixed time limit; see SetTimeout and SetReadTimeout.
-func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) {
+func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
return
}
if m < udpHeaderSize {
- return 0, nil, os.NewError("short read reading UDP header")
+ return 0, nil, errors.New("short read reading UDP header")
}
buf = buf[:m]
}
// ReadFrom implements the net.PacketConn ReadFrom method.
-func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
+func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
-func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) {
+func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// WriteTo implements the net.PacketConn WriteTo method.
-func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
+func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
// DialUDP connects to the remote address raddr on the network net,
// which must be "udp", "udp4", or "udp6". If laddr is not nil, it is used
// as the local address for the connection.
-func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error) {
+func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err error) {
switch net {
case "udp", "udp4", "udp6":
default:
// local address laddr. The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send UDP
// packets with per-packet addressing.
-func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) {
+func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err error) {
switch net {
case "udp", "udp4", "udp6":
default:
// JoinGroup joins the IP multicast group named by addr on ifi,
// which specifies the interface to join. JoinGroup uses the
// default multicast interface if ifi is nil.
-func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) os.Error {
+func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) error {
if !c.ok() {
return os.EINVAL
}
}
// LeaveGroup exits the IP multicast group named by addr on ifi.
-func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) os.Error {
+func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) error {
if !c.ok() {
return os.EINVAL
}
return syscall.AF_INET6
}
-func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) {
+func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
return ipToSockaddr(family, a.IP, a.Port)
}
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *UDPConn) Read(b []byte) (n int, err os.Error) {
+func (c *UDPConn) Read(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Write implements the net.Conn Write method.
-func (c *UDPConn) Write(b []byte) (n int, err os.Error) {
+func (c *UDPConn) Write(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Close closes the UDP connection.
-func (c *UDPConn) Close() os.Error {
+func (c *UDPConn) Close() error {
if !c.ok() {
return os.EINVAL
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *UDPConn) SetTimeout(nsec int64) os.Error {
+func (c *UDPConn) SetTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *UDPConn) SetReadTimeout(nsec int64) os.Error {
+func (c *UDPConn) SetReadTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *UDPConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *UDPConn) SetWriteTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
-func (c *UDPConn) SetReadBuffer(bytes int) os.Error {
+func (c *UDPConn) SetReadBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
-func (c *UDPConn) SetWriteBuffer(bytes int) os.Error {
+func (c *UDPConn) SetWriteBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
//
// ReadFromUDP can be made to time out and return an error with Timeout() == true
// after a fixed time limit; see SetTimeout and SetReadTimeout.
-func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) {
+func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
}
// ReadFrom implements the net.PacketConn ReadFrom method.
-func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
+func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
-func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) {
+func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
sa, err1 := addr.sockaddr(c.fd.family)
if err1 != nil {
- return 0, &OpError{Op: "write", Net: "udp", Addr: addr, Error: err1}
+ return 0, &OpError{Op: "write", Net: "udp", Addr: addr, Err: err1}
}
return c.fd.WriteTo(b, sa)
}
// WriteTo implements the net.PacketConn WriteTo method.
-func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
+func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
// DialUDP connects to the remote address raddr on the network net,
// which must be "udp", "udp4", or "udp6". If laddr is not nil, it is used
// as the local address for the connection.
-func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error) {
+func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err error) {
switch net {
case "udp", "udp4", "udp6":
default:
// local address laddr. The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send UDP
// packets with per-packet addressing.
-func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) {
+func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err error) {
switch net {
case "udp", "udp4", "udp6":
default:
}
// BindToDevice binds a UDPConn to a network interface.
-func (c *UDPConn) BindToDevice(device string) os.Error {
+func (c *UDPConn) BindToDevice(device string) error {
if !c.ok() {
return os.EINVAL
}
// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
-func (c *UDPConn) File() (f *os.File, err os.Error) { return c.fd.dup() }
+func (c *UDPConn) File() (f *os.File, err error) { return c.fd.dup() }
// JoinGroup joins the IP multicast group named by addr on ifi,
// which specifies the interface to join. JoinGroup uses the
// default multicast interface if ifi is nil.
-func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) os.Error {
+func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) error {
if !c.ok() {
return os.EINVAL
}
}
// LeaveGroup exits the IP multicast group named by addr on ifi.
-func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) os.Error {
+func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) error {
if !c.ok() {
return os.EINVAL
}
return leaveIPv6GroupUDP(c, ifi, addr)
}
-func joinIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error {
+func joinIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) error {
mreq := &syscall.IPMreq{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}}
if err := setIPv4InterfaceToJoin(mreq, ifi); err != nil {
return &OpError{"joinipv4group", "udp", &IPAddr{ip}, err}
return nil
}
-func leaveIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error {
+func leaveIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) error {
mreq := &syscall.IPMreq{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}}
if err := setIPv4InterfaceToJoin(mreq, ifi); err != nil {
return &OpError{"leaveipv4group", "udp", &IPAddr{ip}, err}
return nil
}
-func setIPv4InterfaceToJoin(mreq *syscall.IPMreq, ifi *Interface) os.Error {
+func setIPv4InterfaceToJoin(mreq *syscall.IPMreq, ifi *Interface) error {
if ifi == nil {
return nil
}
return nil
}
-func joinIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error {
+func joinIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) error {
mreq := &syscall.IPv6Mreq{}
copy(mreq.Multiaddr[:], ip)
if ifi != nil {
return nil
}
-func leaveIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error {
+func leaveIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) error {
mreq := &syscall.IPv6Mreq{}
copy(mreq.Multiaddr[:], ip)
if ifi != nil {
package net
-import (
- "os"
-)
-
// UnixAddr represents the address of a Unix domain socket end point.
type UnixAddr struct {
Name string
// ResolveUnixAddr parses addr as a Unix domain socket address.
// The string net gives the network name, "unix", "unixgram" or
// "unixpacket".
-func ResolveUnixAddr(net, addr string) (*UnixAddr, os.Error) {
+func ResolveUnixAddr(net, addr string) (*UnixAddr, error) {
switch net {
case "unix":
case "unixpacket":
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *UnixConn) Read(b []byte) (n int, err os.Error) {
+func (c *UnixConn) Read(b []byte) (n int, err error) {
return 0, os.EPLAN9
}
// Write implements the net.Conn Write method.
-func (c *UnixConn) Write(b []byte) (n int, err os.Error) {
+func (c *UnixConn) Write(b []byte) (n int, err error) {
return 0, os.EPLAN9
}
// Close closes the Unix domain connection.
-func (c *UnixConn) Close() os.Error {
+func (c *UnixConn) Close() error {
return os.EPLAN9
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *UnixConn) SetTimeout(nsec int64) os.Error {
+func (c *UnixConn) SetTimeout(nsec int64) error {
return os.EPLAN9
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *UnixConn) SetReadTimeout(nsec int64) os.Error {
+func (c *UnixConn) SetReadTimeout(nsec int64) error {
return os.EPLAN9
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *UnixConn) SetWriteTimeout(nsec int64) error {
return os.EPLAN9
}
// ReadFrom implements the net.PacketConn ReadFrom method.
-func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
+func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err error) {
err = os.EPLAN9
return
}
// WriteTo implements the net.PacketConn WriteTo method.
-func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
+func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error) {
err = os.EPLAN9
return
}
// DialUnix connects to the remote address raddr on the network net,
// which must be "unix" or "unixgram". If laddr is not nil, it is used
// as the local address for the connection.
-func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err os.Error) {
+func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err error) {
return nil, os.EPLAN9
}
// ListenUnix announces on the Unix domain socket laddr and returns a Unix listener.
// Net must be "unix" (stream sockets).
-func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) {
+func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err error) {
return nil, os.EPLAN9
}
// Accept implements the Accept method in the Listener interface;
// it waits for the next call and returns a generic Conn.
-func (l *UnixListener) Accept() (c Conn, err os.Error) {
+func (l *UnixListener) Accept() (c Conn, err error) {
return nil, os.EPLAN9
}
// Close stops listening on the Unix address.
// Already accepted connections are not closed.
-func (l *UnixListener) Close() os.Error {
+func (l *UnixListener) Close() error {
return os.EPLAN9
}
"syscall"
)
-func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err os.Error) {
+func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err error) {
var proto int
switch net {
default:
if raddr != nil {
ra = &syscall.SockaddrUnix{Name: raddr.Name}
} else if proto != syscall.SOCK_DGRAM || laddr == nil {
- return nil, &OpError{Op: mode, Net: net, Error: errMissingAddress}
+ return nil, &OpError{Op: mode, Net: net, Err: errMissingAddress}
}
case "listen":
}
la = &syscall.SockaddrUnix{Name: laddr.Name}
if raddr != nil {
- return nil, &OpError{Op: mode, Net: net, Addr: raddr, Error: &AddrError{Error: "unexpected remote address", Addr: raddr.String()}}
+ return nil, &OpError{Op: mode, Net: net, Addr: raddr, Err: &AddrError{Err: "unexpected remote address", Addr: raddr.String()}}
}
}
if mode == "listen" {
addr = laddr
}
- return nil, &OpError{Op: mode, Net: net, Addr: addr, Error: oserr}
+ return nil, &OpError{Op: mode, Net: net, Addr: addr, Err: oserr}
}
func sockaddrToUnix(sa syscall.Sockaddr) Addr {
// Implementation of the Conn interface - see Conn for documentation.
// Read implements the net.Conn Read method.
-func (c *UnixConn) Read(b []byte) (n int, err os.Error) {
+func (c *UnixConn) Read(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Write implements the net.Conn Write method.
-func (c *UnixConn) Write(b []byte) (n int, err os.Error) {
+func (c *UnixConn) Write(b []byte) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// Close closes the Unix domain connection.
-func (c *UnixConn) Close() os.Error {
+func (c *UnixConn) Close() error {
if !c.ok() {
return os.EINVAL
}
}
// SetTimeout implements the net.Conn SetTimeout method.
-func (c *UnixConn) SetTimeout(nsec int64) os.Error {
+func (c *UnixConn) SetTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetReadTimeout implements the net.Conn SetReadTimeout method.
-func (c *UnixConn) SetReadTimeout(nsec int64) os.Error {
+func (c *UnixConn) SetReadTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
}
// SetWriteTimeout implements the net.Conn SetWriteTimeout method.
-func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error {
+func (c *UnixConn) SetWriteTimeout(nsec int64) error {
if !c.ok() {
return os.EINVAL
}
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
-func (c *UnixConn) SetReadBuffer(bytes int) os.Error {
+func (c *UnixConn) SetReadBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
-func (c *UnixConn) SetWriteBuffer(bytes int) os.Error {
+func (c *UnixConn) SetWriteBuffer(bytes int) error {
if !c.ok() {
return os.EINVAL
}
// ReadFromUnix can be made to time out and return
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetReadTimeout.
-func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err os.Error) {
+func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
}
// ReadFrom implements the net.PacketConn ReadFrom method.
-func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) {
+func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err error) {
if !c.ok() {
return 0, nil, os.EINVAL
}
// an error with Timeout() == true after a fixed time limit;
// see SetTimeout and SetWriteTimeout.
// On packet-oriented connections, write timeouts are rare.
-func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err os.Error) {
+func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
}
// WriteTo implements the net.PacketConn WriteTo method.
-func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) {
+func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error) {
if !c.ok() {
return 0, os.EINVAL
}
return c.WriteToUnix(b, a)
}
-func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err os.Error) {
+func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error) {
if !c.ok() {
return 0, 0, 0, nil, os.EINVAL
}
return
}
-func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err os.Error) {
+func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error) {
if !c.ok() {
return 0, 0, os.EINVAL
}
// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
-func (c *UnixConn) File() (f *os.File, err os.Error) { return c.fd.dup() }
+func (c *UnixConn) File() (f *os.File, err error) { return c.fd.dup() }
// DialUnix connects to the remote address raddr on the network net,
// which must be "unix" or "unixgram". If laddr is not nil, it is used
// as the local address for the connection.
-func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err os.Error) {
+func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err error) {
fd, e := unixSocket(net, laddr, raddr, "dial")
if e != nil {
return nil, e
// ListenUnix announces on the Unix domain socket laddr and returns a Unix listener.
// Net must be "unix" (stream sockets).
-func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) {
+func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err error) {
if net != "unix" && net != "unixgram" && net != "unixpacket" {
return nil, UnknownNetworkError(net)
}
e1 := syscall.Listen(fd.sysfd, 8) // listenBacklog());
if e1 != 0 {
closesocket(fd.sysfd)
- return nil, &OpError{Op: "listen", Net: "unix", Addr: laddr, Error: os.Errno(e1)}
+ return nil, &OpError{Op: "listen", Net: "unix", Addr: laddr, Err: os.Errno(e1)}
}
return &UnixListener{fd, laddr.Name}, nil
}
// AcceptUnix accepts the next incoming call and returns the new connection
// and the remote address.
-func (l *UnixListener) AcceptUnix() (c *UnixConn, err os.Error) {
+func (l *UnixListener) AcceptUnix() (c *UnixConn, err error) {
if l == nil || l.fd == nil {
return nil, os.EINVAL
}
// Accept implements the Accept method in the Listener interface;
// it waits for the next call and returns a generic Conn.
-func (l *UnixListener) Accept() (c Conn, err os.Error) {
+func (l *UnixListener) Accept() (c Conn, err error) {
c1, err := l.AcceptUnix()
if err != nil {
return nil, err
// Close stops listening on the Unix address.
// Already accepted connections are not closed.
-func (l *UnixListener) Close() os.Error {
+func (l *UnixListener) Close() error {
if l == nil || l.fd == nil {
return os.EINVAL
}
func (l *UnixListener) Addr() Addr { return l.fd.laddr }
// SetTimeout sets the deadline associated wuth the listener
-func (l *UnixListener) SetTimeout(nsec int64) (err os.Error) {
+func (l *UnixListener) SetTimeout(nsec int64) (err error) {
if l == nil || l.fd == nil {
return os.EINVAL
}
// File returns a copy of the underlying os.File, set to blocking mode.
// It is the caller's responsibility to close f when finished.
// Closing c does not affect f, and closing f does not affect c.
-func (l *UnixListener) File() (f *os.File, err os.Error) { return l.fd.dup() }
+func (l *UnixListener) File() (f *os.File, err error) { return l.fd.dup() }
// ListenUnixgram listens for incoming Unix datagram packets addressed to the
// local address laddr. The returned connection c's ReadFrom
// and WriteTo methods can be used to receive and send UDP
// packets with per-packet addressing. The network net must be "unixgram".
-func ListenUnixgram(net string, laddr *UnixAddr) (c *UDPConn, err os.Error) {
+func ListenUnixgram(net string, laddr *UnixAddr) (c *UDPConn, err error) {
switch net {
case "unixgram":
default:
package netchan
import (
+ "errors"
"gob"
"io"
- "os"
"reflect"
"sync"
"time"
}
// Sent with a header to report an error.
-type error struct {
+type error_ struct {
Error string
}
}
// Decode an item from the connection.
-func (ed *encDec) decode(value reflect.Value) os.Error {
+func (ed *encDec) decode(value reflect.Value) error {
ed.decLock.Lock()
err := ed.dec.DecodeValue(value)
if err != nil {
}
// Encode a header and payload onto the connection.
-func (ed *encDec) encode(hdr *header, payloadType int, payload interface{}) os.Error {
+func (ed *encDec) encode(hdr *header, payloadType int, payload interface{}) error {
ed.encLock.Lock()
hdr.PayloadType = payloadType
err := ed.enc.Encode(hdr)
}
// See the comment for Exporter.Drain.
-func (cs *clientSet) drain(timeout int64) os.Error {
+func (cs *clientSet) drain(timeout int64) error {
startTime := time.Nanoseconds()
for {
pending := false
break
}
if timeout > 0 && time.Nanoseconds()-startTime >= timeout {
- return os.NewError("timeout")
+ return errors.New("timeout")
}
time.Sleep(100 * 1e6) // 100 milliseconds
}
}
// See the comment for Exporter.Sync.
-func (cs *clientSet) sync(timeout int64) os.Error {
+func (cs *clientSet) sync(timeout int64) error {
startTime := time.Nanoseconds()
// seq remembers the clients and their seqNum at point of entry.
seq := make(map[unackedCounter]int64)
break
}
if timeout > 0 && time.Nanoseconds()-startTime >= timeout {
- return os.NewError("timeout")
+ return errors.New("timeout")
}
time.Sleep(100 * 1e6) // 100 milliseconds
}
// BUG: can't use range clause to receive when using ImportNValues to limit the count.
import (
+ "errors"
"log"
"io"
"net"
- "os"
"reflect"
"strconv"
"sync"
}
func (client *expClient) sendError(hdr *header, err string) {
- error := &error{err}
+ error := &error_{err}
expLog("sending error to client:", error.Error)
client.encode(hdr, payError, error) // ignore any encode error, hope client gets it
client.mu.Lock()
hdrValue := reflect.ValueOf(hdr)
req := new(request)
reqValue := reflect.ValueOf(req)
- error := new(error)
+ error := new(error_)
for {
*hdr = header{}
if err := client.decode(hdrValue); err != nil {
- if err != os.EOF {
+ if err != io.EOF {
expLog("error decoding client header:", err)
}
break
client.seqLock.Unlock()
if err != nil {
expLog("error encoding client response:", err)
- client.sendError(&hdr, err.String())
+ client.sendError(&hdr, err.Error())
break
}
// Negative count means run forever.
// ListenAndServe exports the exporter's channels through the
// given network and local address defined as in net.Listen.
-func (exp *Exporter) ListenAndServe(network, localaddr string) os.Error {
+func (exp *Exporter) ListenAndServe(network, localaddr string) error {
listener, err := net.Listen(network, localaddr)
if err != nil {
return err
// waits until all the exporter's messages have been received by a client.
// If the timeout (measured in nanoseconds) is positive and Drain takes
// longer than that to complete, an error is returned.
-func (exp *Exporter) Drain(timeout int64) os.Error {
+func (exp *Exporter) Drain(timeout int64) error {
// This wrapper function is here so the method's comment will appear in godoc.
return exp.clientSet.drain(timeout)
}
// dispatched to any client. If the timeout (measured in nanoseconds) is
// positive and Sync takes longer than that to complete, an error is
// returned.
-func (exp *Exporter) Sync(timeout int64) os.Error {
+func (exp *Exporter) Sync(timeout int64) error {
// This wrapper function is here so the method's comment will appear in godoc.
return exp.clientSet.sync(timeout)
}
-func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) {
+func checkChan(chT interface{}, dir Dir) (reflect.Value, error) {
chanType := reflect.TypeOf(chT)
if chanType.Kind() != reflect.Chan {
- return reflect.Value{}, os.NewError("not a channel")
+ return reflect.Value{}, errors.New("not a channel")
}
if dir != Send && dir != Recv {
- return reflect.Value{}, os.NewError("unknown channel direction")
+ return reflect.Value{}, errors.New("unknown channel direction")
}
switch chanType.ChanDir() {
case reflect.BothDir:
case reflect.SendDir:
if dir != Recv {
- return reflect.Value{}, os.NewError("to import/export with Send, must provide <-chan")
+ return reflect.Value{}, errors.New("to import/export with Send, must provide <-chan")
}
case reflect.RecvDir:
if dir != Send {
- return reflect.Value{}, os.NewError("to import/export with Recv, must provide chan<-")
+ return reflect.Value{}, errors.New("to import/export with Recv, must provide chan<-")
}
}
return reflect.ValueOf(chT), nil
// channel type.
// Despite the literal signature, the effective signature is
// Export(name string, chT chan T, dir Dir)
-func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error {
+func (exp *Exporter) Export(name string, chT interface{}, dir Dir) error {
ch, err := checkChan(chT, dir)
if err != nil {
return err
defer exp.mu.Unlock()
_, present := exp.names[name]
if present {
- return os.NewError("channel name already being exported:" + name)
+ return errors.New("channel name already being exported:" + name)
}
exp.names[name] = &chanDir{ch, dir}
return nil
// Hangup disassociates the named channel from the Exporter and closes
// the channel. Messages in flight for the channel may be dropped.
-func (exp *Exporter) Hangup(name string) os.Error {
+func (exp *Exporter) Hangup(name string) error {
exp.mu.Lock()
chDir, ok := exp.names[name]
if ok {
// TODO drop all instances of channel from client sets
exp.mu.Unlock()
if !ok {
- return os.NewError("netchan export: hangup: no such channel: " + name)
+ return errors.New("netchan export: hangup: no such channel: " + name)
}
chDir.ch.Close()
return nil
package netchan
import (
+ "errors"
"io"
"log"
"net"
- "os"
"reflect"
"sync"
"time"
chanLock sync.Mutex // protects access to channel map
names map[string]*netChan
chans map[int]*netChan
- errors chan os.Error
+ errors chan error
maxId int
mu sync.Mutex // protects remaining fields
unacked int64 // number of unacknowledged sends.
imp.encDec = newEncDec(conn)
imp.chans = make(map[int]*netChan)
imp.names = make(map[string]*netChan)
- imp.errors = make(chan os.Error, 10)
+ imp.errors = make(chan error, 10)
imp.unacked = 0
go imp.run()
return imp
}
// Import imports a set of channels from the given network and address.
-func Import(network, remoteaddr string) (*Importer, os.Error) {
+func Import(network, remoteaddr string) (*Importer, error) {
conn, err := net.Dial(network, remoteaddr)
if err != nil {
return nil, err
hdr := new(header)
hdrValue := reflect.ValueOf(hdr)
ackHdr := new(header)
- err := new(error)
+ err := new(error_)
errValue := reflect.ValueOf(err)
for {
*hdr = header{}
if e := imp.decode(hdrValue); e != nil {
- if e != os.EOF {
+ if e != io.EOF {
impLog("header:", e)
imp.shutdown()
}
if err.Error != "" {
impLog("response error:", err.Error)
select {
- case imp.errors <- os.NewError(err.Error):
+ case imp.errors <- errors.New(err.Error):
continue // errors are not acknowledged
default:
imp.shutdown()
// can be read. Clients of the importer are not required to read the error
// channel for correct execution. However, if too many errors occur
// without being read from the error channel, the importer will shut down.
-func (imp *Importer) Errors() chan os.Error {
+func (imp *Importer) Errors() chan error {
return imp.errors
}
// Import imports a channel of the given type, size and specified direction.
// It is equivalent to ImportNValues with a count of -1, meaning unbounded.
-func (imp *Importer) Import(name string, chT interface{}, dir Dir, size int) os.Error {
+func (imp *Importer) Import(name string, chT interface{}, dir Dir, size int) error {
return imp.ImportNValues(name, chT, dir, size, -1)
}
// The channel to be bound to the remote site's channel is provided
// in the call and may be of arbitrary channel type.
// Despite the literal signature, the effective signature is
-// ImportNValues(name string, chT chan T, dir Dir, size, n int) os.Error
+// ImportNValues(name string, chT chan T, dir Dir, size, n int) error
// Example usage:
// imp, err := NewImporter("tcp", "netchanserver.mydomain.com:1234")
// if err != nil { log.Fatal(err) }
// err = imp.ImportNValues("name", ch, Recv, 1, 1)
// if err != nil { log.Fatal(err) }
// fmt.Printf("%+v\n", <-ch)
-func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size, n int) os.Error {
+func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size, n int) error {
ch, err := checkChan(chT, dir)
if err != nil {
return err
defer imp.chanLock.Unlock()
_, present := imp.names[name]
if present {
- return os.NewError("channel name already being imported:" + name)
+ return errors.New("channel name already being imported:" + name)
}
if size < 1 {
size = 1
// Hangup disassociates the named channel from the Importer and closes
// the channel. Messages in flight for the channel may be dropped.
-func (imp *Importer) Hangup(name string) os.Error {
+func (imp *Importer) Hangup(name string) error {
imp.chanLock.Lock()
defer imp.chanLock.Unlock()
nc := imp.names[name]
if nc == nil {
- return os.NewError("netchan import: hangup: no such channel: " + name)
+ return errors.New("netchan import: hangup: no such channel: " + name)
}
delete(imp.names, name)
delete(imp.chans, nc.id)
// waits until all the importer's messages have been received.
// If the timeout (measured in nanoseconds) is positive and Drain takes
// longer than that to complete, an error is returned.
-func (imp *Importer) Drain(timeout int64) os.Error {
+func (imp *Importer) Drain(timeout int64) error {
startTime := time.Nanoseconds()
for imp.unackedCount() > 0 {
if timeout > 0 && time.Nanoseconds()-startTime >= timeout {
- return os.NewError("timeout")
+ return errors.New("timeout")
}
time.Sleep(100 * 1e6)
}
}()
select {
case err = <-imp.Errors():
- if strings.Index(err.String(), "no such channel") < 0 {
+ if strings.Index(err.Error(), "no such channel") < 0 {
t.Error("wrong error for nonexistent channel:", err)
}
case <-timeout:
package regexp
import (
- "os"
"strings"
"testing"
)
type stringError struct {
re string
- err os.Error
+ err error
}
var bad_re = []stringError{
{`\x`, ErrBadBackslash},
}
-func compileTest(t *testing.T, expr string, error os.Error) *Regexp {
+func compileTest(t *testing.T, expr string, error error) *Regexp {
re, err := Compile(expr)
if err != error {
- t.Error("compiling `", expr, "`; unexpected error: ", err.String())
+ t.Error("compiling `", expr, "`; unexpected error: ", err.Error())
}
return re
}
import (
"bytes"
"io"
- "os"
"strings"
"utf8"
)
// Error is the local type for a parsing error.
type Error string
-func (e Error) String() string {
+func (e Error) Error() string {
return string(e)
}
// Compile parses a regular expression and returns, if successful, a Regexp
// object that can be used to match against text.
-func Compile(str string) (regexp *Regexp, error os.Error) {
+func Compile(str string) (regexp *Regexp, error error) {
regexp = new(Regexp)
// doParse will panic if there is a parse error.
defer func() {
func MustCompile(str string) *Regexp {
regexp, error := Compile(str)
if error != nil {
- panic(`regexp: compiling "` + str + `": ` + error.String())
+ panic(`regexp: compiling "` + str + `": ` + error.Error())
}
return regexp
}
// MatchReader checks whether a textual regular expression matches the text
// read by the RuneReader. More complicated queries need to use Compile and
// the full Regexp interface.
-func MatchReader(pattern string, r io.RuneReader) (matched bool, error os.Error) {
+func MatchReader(pattern string, r io.RuneReader) (matched bool, error error) {
re, err := Compile(pattern)
if err != nil {
return false, err
// MatchString checks whether a textual regular expression
// matches a string. More complicated queries need
// to use Compile and the full Regexp interface.
-func MatchString(pattern string, s string) (matched bool, error os.Error) {
+func MatchString(pattern string, s string) (matched bool, error error) {
re, err := Compile(pattern)
if err != nil {
return false, err
// Match checks whether a textual regular expression
// matches a byte slice. More complicated queries need
// to use Compile and the full Regexp interface.
-func Match(pattern string, b []byte) (matched bool, error os.Error) {
+func Match(pattern string, b []byte) (matched bool, error error) {
re, err := Compile(pattern)
if err != nil {
return false, err
"fmt"
"io"
"io/ioutil"
- "os"
"reflect"
"strconv"
"strings"
Msg string
}
-func (e *Error) String() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) }
+func (e *Error) Error() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) }
// checkError is a deferred function to turn a panic with type *Error into a plain error return.
// Other panics are unexpected and so are re-enabled.
-func checkError(error *os.Error) {
+func checkError(error *error) {
if v := recover(); v != nil {
if e, ok := v.(*Error); ok {
*error = e
// Build argument list, processing any literals
for i, word := range words {
- var lerr os.Error
+ var lerr error
switch word[0] {
case '"', '`', '\'':
v, err := strconv.Unquote(word)
// Parse initializes a Template by parsing its definition. The string
// s contains the template text. If any errors occur, Parse returns
// the error.
-func (t *Template) Parse(s string) (err os.Error) {
+func (t *Template) Parse(s string) (err error) {
if t.elems == nil {
return &Error{1, "template not allocated with New"}
}
// ParseFile is like Parse but reads the template definition from the
// named file.
-func (t *Template) ParseFile(filename string) (err os.Error) {
+func (t *Template) ParseFile(filename string) (err error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return err
// Execute applies a parsed template to the specified data object,
// generating output to wr.
-func (t *Template) Execute(wr io.Writer, data interface{}) (err os.Error) {
+func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
// Extract the driver data.
val := reflect.ValueOf(data)
defer checkError(&err)
// the formatter map fmap, which may be nil, defines auxiliary functions
// for formatting variables. The template is returned. If any errors
// occur, err will be non-nil.
-func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) {
+func Parse(s string, fmap FormatterMap) (t *Template, err error) {
t = New(fmap)
err = t.Parse(s)
if err != nil {
// a file containing the template text, while the formatter map fmap, which
// may be nil, defines auxiliary functions for formatting variables.
// The template is returned. If any errors occur, err will be non-nil.
-func ParseFile(filename string, fmap FormatterMap) (t *Template, err os.Error) {
+func ParseFile(filename string, fmap FormatterMap) (t *Template, err error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
func MustParse(s string, fmap FormatterMap) *Template {
t, err := Parse(s, fmap)
if err != nil {
- panic("template.MustParse error: " + err.String())
+ panic("template.MustParse error: " + err.Error())
}
return t
}
func MustParseFile(filename string, fmap FormatterMap) *Template {
b, err := ioutil.ReadFile(filename)
if err != nil {
- panic("template.MustParseFile error: " + err.String())
+ panic("template.MustParseFile error: " + err.Error())
}
return MustParse(string(b), fmap)
}
"io"
"io/ioutil"
"json"
- "os"
"strings"
"testing"
)
func TestAll(t *testing.T) {
// Parse
- testAll(t, func(test *Test) (*Template, os.Error) { return Parse(test.in, formatters) })
+ testAll(t, func(test *Test) (*Template, error) { return Parse(test.in, formatters) })
// ParseFile
- testAll(t, func(test *Test) (*Template, os.Error) {
+ testAll(t, func(test *Test) (*Template, error) {
err := ioutil.WriteFile("_test/test.tmpl", []byte(test.in), 0600)
if err != nil {
t.Error("unexpected write error:", err)
return ParseFile("_test/test.tmpl", formatters)
})
// tmpl.ParseFile
- testAll(t, func(test *Test) (*Template, os.Error) {
+ testAll(t, func(test *Test) (*Template, error) {
err := ioutil.WriteFile("_test/test.tmpl", []byte(test.in), 0600)
if err != nil {
t.Error("unexpected write error:", err)
})
}
-func testAll(t *testing.T, parseFunc func(*Test) (*Template, os.Error)) {
+func testAll(t *testing.T, parseFunc func(*Test) (*Template, error)) {
s := new(S)
// initialized by hand for clarity.
s.Header = "Header"
} else {
if err == nil {
t.Errorf("expected execute error %q, got nil", test.err)
- } else if err.String() != test.err {
- t.Errorf("expected execute error %q, got %q", test.err, err.String())
+ } else if err.Error() != test.err {
+ t.Errorf("expected execute error %q, got %q", test.err, err.Error())
}
}
if buf.String() != test.out {
if err == nil {
t.Fatal("expected execute error, got none")
}
- if strings.Index(err.String(), "not exported") < 0 {
+ if strings.Index(err.Error(), "not exported") < 0 {
t.Fatal("expected unexported error; got", err)
}
}
t.Error("unexpected parse error:", err)
continue
}
- if strings.Index(err.String(), c.err) < 0 {
- t.Errorf("unexpected error: expected %q, got %q", c.err, err.String())
+ if strings.Index(err.Error(), c.err) < 0 {
+ t.Errorf("unexpected error: expected %q, got %q", c.err, err.Error())
continue
}
} else {
package os
import (
+ "io"
"syscall"
"unsafe"
)
// nil os.Error. If it encounters an error before the end of the
// directory, Readdirnames returns the names read until that point and
// a non-nil error.
-func (file *File) Readdirnames(n int) (names []string, err Error) {
+func (file *File) Readdirnames(n int) (names []string, err error) {
if elen == 0 {
var dummy syscall.Dirent;
elen = (unsafe.Offsetof(dummy.Name) +
n--
}
if n >= 0 && len(names) == 0 {
- return names, EOF
+ return names, io.EOF
}
return names, nil
}
package os
import (
+ "errors"
+ "io"
"syscall"
)
//
// If n > 0, Readdir returns at most n FileInfo structures. In this case, if
// Readdirnames returns an empty slice, it will return a non-nil error
-// explaining why. At the end of a directory, the error is os.EOF.
+// explaining why. At the end of a directory, the error is io.EOF.
//
// If n <= 0, Readdir returns all the FileInfo from the directory in
// a single slice. In this case, if Readdir succeeds (reads all
// the way to the end of the directory), it returns the slice and a
-// nil os.Error. If it encounters an error before the end of the
+// nil error. If it encounters an error before the end of the
// directory, Readdir returns the FileInfo read until that point
// and a non-nil error.
-func (file *File) Readdir(n int) (fi []FileInfo, err Error) {
+func (file *File) Readdir(n int) (fi []FileInfo, err error) {
// If this file has no dirinfo, create one.
if file.dirinfo == nil {
file.dirinfo = new(dirInfo)
// Refill the buffer if necessary
if d.bufp >= d.nbuf {
d.bufp = 0
- var e Error
+ var e error
d.nbuf, e = file.Read(d.buf[:])
- if e != nil && e != EOF {
+ if e != nil && e != io.EOF {
return result, &PathError{"readdir", file.name, e}
}
- if e == EOF {
+ if e == io.EOF {
break
}
if d.nbuf < syscall.STATFIXLEN {
}
if n >= 0 && len(result) == 0 {
- return result, EOF
+ return result, io.EOF
}
return result, nil
}
//
// If n > 0, Readdirnames returns at most n names. In this case, if
// Readdirnames returns an empty slice, it will return a non-nil error
-// explaining why. At the end of a directory, the error is os.EOF.
+// explaining why. At the end of a directory, the error is io.EOF.
//
// If n <= 0, Readdirnames returns all the names from the directory in
// a single slice. In this case, if Readdirnames succeeds (reads all
// the way to the end of the directory), it returns the slice and a
-// nil os.Error. If it encounters an error before the end of the
+// nil error. If it encounters an error before the end of the
// directory, Readdirnames returns the names read until that point and
// a non-nil error.
-func (file *File) Readdirnames(n int) (names []string, err Error) {
+func (file *File) Readdirnames(n int) (names []string, err error) {
fi, err := file.Readdir(n)
names = make([]string, len(fi))
for i := range fi {
// UnmarshalDir reads a 9P Stat message from a 9P protocol message stored in b,
// returning the corresponding Dir struct.
-func UnmarshalDir(b []byte) (d *Dir, err Error) {
+func UnmarshalDir(b []byte) (d *Dir, err error) {
n := uint16(0)
n, b = gbit16(b)
// pstring appends a Go string s to a 9P message b.
func pstring(b []byte, s string) []byte {
if len(s) >= 1<<16 {
- panic(NewError("string too long"))
+ panic(errors.New("string too long"))
}
b = pbit16(b, uint16(len(s)))
b = append(b, s...)
package os
import (
+ "io"
"syscall"
)
// If n <= 0, Readdirnames returns all the names from the directory in
// a single slice. In this case, if Readdirnames succeeds (reads all
// the way to the end of the directory), it returns the slice and a
-// nil os.Error. If it encounters an error before the end of the
+// nil error. If it encounters an error before the end of the
// directory, Readdirnames returns the names read until that point and
// a non-nil error.
-func (f *File) Readdirnames(n int) (names []string, err Error) {
+func (f *File) Readdirnames(n int) (names []string, err error) {
// If this file has no dirinfo, create one.
if f.dirinfo == nil {
f.dirinfo = new(dirInfo)
n -= nc
}
if n >= 0 && len(names) == 0 {
- return names, EOF
+ return names, io.EOF
}
return names, nil
}
package os
-import "syscall"
+import (
+ "error"
+ "syscall"
+)
-// ENOENV is the Error indicating that an environment variable does not exist.
-var ENOENV = NewError("no such environment variable")
+// ENOENV is the error indicating that an environment variable does not exist.
+var ENOENV = errors.New("no such environment variable")
// Getenverror retrieves the value of the environment variable named by the key.
// It returns the value and an error, if any.
-func Getenverror(key string) (value string, err Error) {
+func Getenverror(key string) (value string, err error) {
if len(key) == 0 {
return "", EINVAL
}
}
// Setenv sets the value of the environment variable named by the key.
-// It returns an Error, if any.
-func Setenv(key, value string) Error {
+// It returns an error, if any.
+func Setenv(key, value string) error {
if len(key) == 0 {
return EINVAL
}
package os
import (
+ "errors"
"sync"
)
-// ENOENV is the Error indicating that an environment variable does not exist.
-var ENOENV = NewError("no such environment variable")
+// ENOENV is the error indicating that an environment variable does not exist.
+var ENOENV = errors.New("no such environment variable")
var env map[string]string
var once sync.Once
// Getenverror retrieves the value of the environment variable named by the key.
// It returns the value and an error, if any.
-func Getenverror(key string) (value string, err Error) {
+func Getenverror(key string) (value string, err error) {
once.Do(copyenv)
if len(key) == 0 {
}
// Setenv sets the value of the environment variable named by the key.
-// It returns an Error, if any.
-func Setenv(key, value string) Error {
+// It returns an error, if any.
+func Setenv(key, value string) error {
once.Do(copyenv)
if len(key) == 0 {
return EINVAL
package os
import (
+ "errors"
"syscall"
"utf16"
"unsafe"
)
-// ENOENV is the Error indicating that an environment variable does not exist.
-var ENOENV = NewError("no such environment variable")
+// ENOENV is the error indicating that an environment variable does not exist.
+var ENOENV = errors.New("no such environment variable")
// Getenverror retrieves the value of the environment variable named by the key.
// It returns the value and an error, if any.
-func Getenverror(key string) (value string, err Error) {
+func Getenverror(key string) (value string, err error) {
b := make([]uint16, 100)
n, e := syscall.GetEnvironmentVariable(syscall.StringToUTF16Ptr(key), &b[0], uint32(len(b)))
if n == 0 && e == syscall.ERROR_ENVVAR_NOT_FOUND {
}
// Setenv sets the value of the environment variable named by the key.
-// It returns an Error, if any.
-func Setenv(key, value string) Error {
+// It returns an error, if any.
+func Setenv(key, value string) error {
var v *uint16
if len(value) > 0 {
v = syscall.StringToUTF16Ptr(value)
package os
-// An Error can represent any printable error condition.
-type Error interface {
- String() string
-}
-
-// // errorString is a helper type used by NewError.
-type errorString string
-
-func (e errorString) String() string { return string(e) }
-
-// Note: If the name of the function NewError changes,
-// pkg/go/doc/doc.go should be adjusted since it hardwires
-// this name in a heuristic.
-
-// // NewError returns a new error with error.String() == s.
-func NewError(s string) Error { return errorString(s) }
-
// PathError records an error and the operation and file path that caused it.
type PathError struct {
- Op string
- Path string
- Error Error
+ Op string
+ Path string
+ Err error
}
-func (e *PathError) String() string { return e.Op + " " + e.Path + ": " + e.Error.String() }
+func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
package os
-import syscall "syscall"
+import (
+ "errors"
+ "syscall"
+)
// SyscallError records an error from a specific system call.
type SyscallError struct {
Err string
}
-func (e *SyscallError) String() string { return e.Syscall + ": " + e.Err }
+func (e *SyscallError) Error() string { return e.Syscall + ": " + e.Err }
// Note: If the name of the function NewSyscallError changes,
// pkg/go/doc/doc.go should be adjusted since it hardwires
// this name in a heuristic.
-// NewSyscallError returns, as an Error, a new SyscallError
+// NewSyscallError returns, as an error, a new SyscallError
// with the given system call name and error details.
// As a convenience, if err is nil, NewSyscallError returns nil.
-func NewSyscallError(syscall string, err syscall.Error) Error {
+func NewSyscallError(syscall string, err syscall.Error) error {
if err == nil {
return nil
}
}
var (
- Eshortstat = NewError("stat buffer too small")
- Ebadstat = NewError("malformed stat buffer")
- Ebadfd = NewError("fd out of range or not open")
- Ebadarg = NewError("bad arg in system call")
- Enotdir = NewError("not a directory")
- Enonexist = NewError("file does not exist")
- Eexist = NewError("file already exists")
- Eio = NewError("i/o error")
- Eperm = NewError("permission denied")
+ Eshortstat = errors.New("stat buffer too small")
+ Ebadstat = errors.New("malformed stat buffer")
+ Ebadfd = errors.New("fd out of range or not open")
+ Ebadarg = errors.New("bad arg in system call")
+ Enotdir = errors.New("not a directory")
+ Enonexist = errors.New("file does not exist")
+ Eexist = errors.New("file already exists")
+ Eio = errors.New("i/o error")
+ Eperm = errors.New("permission denied")
EINVAL = Ebadarg
ENOTDIR = Enotdir
EPERM = Eperm
EISDIR = syscall.EISDIR
- EBADF = NewError("bad file descriptor")
- ENAMETOOLONG = NewError("file name too long")
- ERANGE = NewError("math result not representable")
- EPIPE = NewError("Broken Pipe")
- EPLAN9 = NewError("not supported by plan 9")
+ EBADF = errors.New("bad file descriptor")
+ ENAMETOOLONG = errors.New("file name too long")
+ ERANGE = errors.New("math result not representable")
+ EPIPE = errors.New("Broken Pipe")
+ EPLAN9 = errors.New("not supported by plan 9")
)
func iserror(err syscall.Error) bool {
import syscall "syscall"
// Errno is the Unix error number. Names such as EINVAL are simple
-// wrappers to convert the error number into an Error.
+// wrappers to convert the error number into an error.
type Errno int64
-func (e Errno) String() string { return syscall.Errstr(int(e)) }
+func (e Errno) Error() string { return syscall.Errstr(int(e)) }
func (e Errno) Temporary() bool {
return e == Errno(syscall.EINTR) || e == Errno(syscall.EMFILE) || e.Timeout()
// Commonly known Unix errors.
var (
- EPERM Error = Errno(syscall.EPERM)
- ENOENT Error = Errno(syscall.ENOENT)
- ESRCH Error = Errno(syscall.ESRCH)
- EINTR Error = Errno(syscall.EINTR)
- EIO Error = Errno(syscall.EIO)
- ENXIO Error = Errno(syscall.ENXIO)
- E2BIG Error = Errno(syscall.E2BIG)
- ENOEXEC Error = Errno(syscall.ENOEXEC)
- EBADF Error = Errno(syscall.EBADF)
- ECHILD Error = Errno(syscall.ECHILD)
- EDEADLK Error = Errno(syscall.EDEADLK)
- ENOMEM Error = Errno(syscall.ENOMEM)
- EACCES Error = Errno(syscall.EACCES)
- EFAULT Error = Errno(syscall.EFAULT)
- EBUSY Error = Errno(syscall.EBUSY)
- EEXIST Error = Errno(syscall.EEXIST)
- EXDEV Error = Errno(syscall.EXDEV)
- ENODEV Error = Errno(syscall.ENODEV)
- ENOTDIR Error = Errno(syscall.ENOTDIR)
- EISDIR Error = Errno(syscall.EISDIR)
- EINVAL Error = Errno(syscall.EINVAL)
- ENFILE Error = Errno(syscall.ENFILE)
- EMFILE Error = Errno(syscall.EMFILE)
- ENOTTY Error = Errno(syscall.ENOTTY)
- EFBIG Error = Errno(syscall.EFBIG)
- ENOSPC Error = Errno(syscall.ENOSPC)
- ESPIPE Error = Errno(syscall.ESPIPE)
- EROFS Error = Errno(syscall.EROFS)
- EMLINK Error = Errno(syscall.EMLINK)
- EPIPE Error = Errno(syscall.EPIPE)
- EAGAIN Error = Errno(syscall.EAGAIN)
- EDOM Error = Errno(syscall.EDOM)
- ERANGE Error = Errno(syscall.ERANGE)
- EADDRINUSE Error = Errno(syscall.EADDRINUSE)
- ECONNREFUSED Error = Errno(syscall.ECONNREFUSED)
- ENAMETOOLONG Error = Errno(syscall.ENAMETOOLONG)
- EAFNOSUPPORT Error = Errno(syscall.EAFNOSUPPORT)
- ETIMEDOUT Error = Errno(syscall.ETIMEDOUT)
- ENOTCONN Error = Errno(syscall.ENOTCONN)
+ EPERM error = Errno(syscall.EPERM)
+ ENOENT error = Errno(syscall.ENOENT)
+ ESRCH error = Errno(syscall.ESRCH)
+ EINTR error = Errno(syscall.EINTR)
+ EIO error = Errno(syscall.EIO)
+ ENXIO error = Errno(syscall.ENXIO)
+ E2BIG error = Errno(syscall.E2BIG)
+ ENOEXEC error = Errno(syscall.ENOEXEC)
+ EBADF error = Errno(syscall.EBADF)
+ ECHILD error = Errno(syscall.ECHILD)
+ EDEADLK error = Errno(syscall.EDEADLK)
+ ENOMEM error = Errno(syscall.ENOMEM)
+ EACCES error = Errno(syscall.EACCES)
+ EFAULT error = Errno(syscall.EFAULT)
+ EBUSY error = Errno(syscall.EBUSY)
+ EEXIST error = Errno(syscall.EEXIST)
+ EXDEV error = Errno(syscall.EXDEV)
+ ENODEV error = Errno(syscall.ENODEV)
+ ENOTDIR error = Errno(syscall.ENOTDIR)
+ EISDIR error = Errno(syscall.EISDIR)
+ EINVAL error = Errno(syscall.EINVAL)
+ ENFILE error = Errno(syscall.ENFILE)
+ EMFILE error = Errno(syscall.EMFILE)
+ ENOTTY error = Errno(syscall.ENOTTY)
+ EFBIG error = Errno(syscall.EFBIG)
+ ENOSPC error = Errno(syscall.ENOSPC)
+ ESPIPE error = Errno(syscall.ESPIPE)
+ EROFS error = Errno(syscall.EROFS)
+ EMLINK error = Errno(syscall.EMLINK)
+ EPIPE error = Errno(syscall.EPIPE)
+ EAGAIN error = Errno(syscall.EAGAIN)
+ EDOM error = Errno(syscall.EDOM)
+ ERANGE error = Errno(syscall.ERANGE)
+ EADDRINUSE error = Errno(syscall.EADDRINUSE)
+ ECONNREFUSED error = Errno(syscall.ECONNREFUSED)
+ ENAMETOOLONG error = Errno(syscall.ENAMETOOLONG)
+ EAFNOSUPPORT error = Errno(syscall.EAFNOSUPPORT)
+ ETIMEDOUT error = Errno(syscall.ETIMEDOUT)
+ ENOTCONN error = Errno(syscall.ENOTCONN)
)
// SyscallError records an error from a specific system call.
Errno Errno
}
-func (e *SyscallError) String() string { return e.Syscall + ": " + e.Errno.String() }
+func (e *SyscallError) Error() string { return e.Syscall + ": " + e.Errno.Error() }
// Note: If the name of the function NewSyscallError changes,
// pkg/go/doc/doc.go should be adjusted since it hardwires
// this name in a heuristic.
-// NewSyscallError returns, as an Error, a new SyscallError
+// NewSyscallError returns, as an error, a new SyscallError
// with the given system call name and error details.
// As a convenience, if errno is 0, NewSyscallError returns nil.
-func NewSyscallError(syscall string, errno int) Error {
+func NewSyscallError(syscall string, errno int) error {
if errno == 0 {
return nil
}
// StartProcess starts a new process with the program, arguments and attributes
// specified by name, argv and attr.
-func StartProcess(name string, argv []string, attr *ProcAttr) (p *Process, err Error) {
+func StartProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error) {
sysattr := &syscall.ProcAttr{
Dir: attr.Dir,
Env: attr.Env,
return string(note)
}
-func (p *Process) Signal(sig Signal) Error {
+func (p *Process) Signal(sig Signal) error {
if p.done {
return NewError("os: process already finished")
}
}
// Kill causes the Process to exit immediately.
-func (p *Process) Kill() Error {
+func (p *Process) Kill() error {
f, e := OpenFile("/proc/"+itoa(p.Pid)+"/ctl", O_WRONLY, 0)
if iserror(e) {
return NewSyscallError("kill", e)
// Exec replaces the current process with an execution of the
// named binary, with arguments argv and environment envv.
-// If successful, Exec never returns. If it fails, it returns an Error.
+// If successful, Exec never returns. If it fails, it returns an error.
// ForkExec is almost always a better way to execute a program.
-func Exec(name string, argv []string, envv []string) Error {
+func Exec(name string, argv []string, envv []string) error {
e := syscall.Exec(name, argv, envv)
if iserror(e) {
return &PathError{"exec", name, e}
}
// Wait waits for the Process to exit or stop, and then returns a
-// Waitmsg describing its status and an Error, if any. The options
+// Waitmsg describing its status and an error, if any. The options
// (WNOHANG etc.) affect the behavior of the Wait call.
-func (p *Process) Wait(options int) (w *Waitmsg, err Error) {
+func (p *Process) Wait(options int) (w *Waitmsg, err error) {
var waitmsg syscall.Waitmsg
if p.Pid == -1 {
}
// Wait waits for process pid to exit or stop, and then returns a
-// Waitmsg describing its status and an Error, if any. The options
+// Waitmsg describing its status and an error, if any. The options
// (WNOHANG etc.) affect the behavior of the Wait call.
// Wait is equivalent to calling FindProcess and then Wait
// and Release on the result.
-func Wait(pid int, options int) (w *Waitmsg, err Error) {
+func Wait(pid int, options int) (w *Waitmsg, err error) {
p, e := FindProcess(pid)
if e != nil {
return nil, e
}
// Release releases any resources associated with the Process.
-func (p *Process) Release() Error {
+func (p *Process) Release() error {
// NOOP for Plan 9.
p.Pid = -1
// no need for a finalizer anymore
// FindProcess looks for a running process by its pid.
// The Process it returns can be used to obtain information
// about the underlying operating system process.
-func FindProcess(pid int) (p *Process, err Error) {
+func FindProcess(pid int) (p *Process, err error) {
// NOOP for Plan 9.
return newProcess(pid, 0), nil
}
//
// StartProcess is a low-level interface. The exec package provides
// higher-level interfaces.
-func StartProcess(name string, argv []string, attr *ProcAttr) (p *Process, err Error) {
+func StartProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error) {
sysattr := &syscall.ProcAttr{
Dir: attr.Dir,
Env: attr.Env,
}
// Kill causes the Process to exit immediately.
-func (p *Process) Kill() Error {
+func (p *Process) Kill() error {
return p.Signal(SIGKILL)
}
// Exec replaces the current process with an execution of the
// named binary, with arguments argv and environment envv.
-// If successful, Exec never returns. If it fails, it returns an Error.
+// If successful, Exec never returns. If it fails, it returns an error.
//
// To run a child process, see StartProcess (for a low-level interface)
// or the exec package (for higher-level interfaces).
-func Exec(name string, argv []string, envv []string) Error {
+func Exec(name string, argv []string, envv []string) error {
if envv == nil {
envv = Environ()
}
}
// Wait waits for process pid to exit or stop, and then returns a
-// Waitmsg describing its status and an Error, if any. The options
+// Waitmsg describing its status and an error, if any. The options
// (WNOHANG etc.) affect the behavior of the Wait call.
// Wait is equivalent to calling FindProcess and then Wait
// and Release on the result.
-func Wait(pid int, options int) (w *Waitmsg, err Error) {
+func Wait(pid int, options int) (w *Waitmsg, err error) {
p, e := FindProcess(pid)
if e != nil {
return nil, e
package os
import (
+ "errors"
"runtime"
"syscall"
)
// the options
// Wait waits for the Process to exit or stop, and then returns a
-// Waitmsg describing its status and an Error, if any. The options
+// Waitmsg describing its status and an error, if any. The options
// (WNOHANG etc.) affect the behavior of the Wait call.
-func (p *Process) Wait(options int) (w *Waitmsg, err Error) {
+func (p *Process) Wait(options int) (w *Waitmsg, err error) {
if p.Pid == -1 {
return nil, EINVAL
}
}
// Signal sends a signal to the Process.
-func (p *Process) Signal(sig Signal) Error {
+func (p *Process) Signal(sig Signal) error {
if p.done {
- return NewError("os: process already finished")
+ return errors.New("os: process already finished")
}
if e := syscall.Kill(p.Pid, int(sig.(UnixSignal))); e != 0 {
return Errno(e)
}
// Release releases any resources associated with the Process.
-func (p *Process) Release() Error {
+func (p *Process) Release() error {
// NOOP for unix.
p.Pid = -1
// no need for a finalizer anymore
// FindProcess looks for a running process by its pid.
// The Process it returns can be used to obtain information
// about the underlying operating system process.
-func FindProcess(pid int) (p *Process, err Error) {
+func FindProcess(pid int) (p *Process, err error) {
// NOOP for unix.
return newProcess(pid, 0), nil
}
package os
import (
+ "errors"
"runtime"
"syscall"
)
-func (p *Process) Wait(options int) (w *Waitmsg, err Error) {
+func (p *Process) Wait(options int) (w *Waitmsg, err error) {
s, e := syscall.WaitForSingleObject(syscall.Handle(p.handle), syscall.INFINITE)
switch s {
case syscall.WAIT_OBJECT_0:
case syscall.WAIT_FAILED:
return nil, NewSyscallError("WaitForSingleObject", e)
default:
- return nil, NewError("os: unexpected result from WaitForSingleObject")
+ return nil, errors.New("os: unexpected result from WaitForSingleObject")
}
var ec uint32
e = syscall.GetExitCodeProcess(syscall.Handle(p.handle), &ec)
}
// Signal sends a signal to the Process.
-func (p *Process) Signal(sig Signal) Error {
+func (p *Process) Signal(sig Signal) error {
if p.done {
- return NewError("os: process already finished")
+ return errors.New("os: process already finished")
}
switch sig.(UnixSignal) {
case SIGKILL:
return Errno(syscall.EWINDOWS)
}
-func (p *Process) Release() Error {
+func (p *Process) Release() error {
if p.handle == -1 {
return EINVAL
}
return nil
}
-func FindProcess(pid int) (p *Process, err Error) {
+func FindProcess(pid int) (p *Process, err error) {
const da = syscall.STANDARD_RIGHTS_READ |
syscall.PROCESS_QUERY_INFORMATION | syscall.SYNCHRONIZE
h, e := syscall.OpenProcess(da, false, uint32(pid))
package os
import (
+ "io"
"syscall"
)
SEEK_END int = 2 // seek relative to the end
)
-type eofError int
-
-func (eofError) String() string { return "EOF" }
-
-// EOF is the Error returned by Read when no more input is available.
-// Functions should return EOF only to signal a graceful end of input.
-// If the EOF occurs unexpectedly in a structured data stream,
-// the appropriate error is either io.ErrUnexpectedEOF or some other error
-// giving more detail.
-var EOF Error = eofError(0)
-
// Read reads up to len(b) bytes from the File.
-// It returns the number of bytes read and an Error, if any.
-// EOF is signaled by a zero count with err set to EOF.
-func (file *File) Read(b []byte) (n int, err Error) {
+// It returns the number of bytes read and an error, if any.
+// EOF is signaled by a zero count with err set to io.EOF.
+func (file *File) Read(b []byte) (n int, err error) {
if file == nil {
return 0, EINVAL
}
n = 0
}
if n == 0 && len(b) > 0 && !iserror(e) {
- return 0, EOF
+ return 0, io.EOF
}
if iserror(e) {
err = &PathError{"read", file.name, Errno(e)}
}
// ReadAt reads len(b) bytes from the File starting at byte offset off.
-// It returns the number of bytes read and the Error, if any.
-// EOF is signaled by a zero count with err set to EOF.
-// ReadAt always returns a non-nil Error when n != len(b).
-func (file *File) ReadAt(b []byte, off int64) (n int, err Error) {
+// It returns the number of bytes read and the error, if any.
+// EOF is signaled by a zero count with err set to io.EOF.
+// ReadAt always returns a non-nil error when n != len(b).
+func (file *File) ReadAt(b []byte, off int64) (n int, err error) {
if file == nil {
return 0, EINVAL
}
for len(b) > 0 {
m, e := file.pread(b, off)
if m == 0 && !iserror(e) {
- return n, EOF
+ return n, io.EOF
}
if iserror(e) {
err = &PathError{"read", file.name, Errno(e)}
}
// Write writes len(b) bytes to the File.
-// It returns the number of bytes written and an Error, if any.
-// Write returns a non-nil Error when n != len(b).
-func (file *File) Write(b []byte) (n int, err Error) {
+// It returns the number of bytes written and an error, if any.
+// Write returns a non-nil error when n != len(b).
+func (file *File) Write(b []byte) (n int, err error) {
if file == nil {
return 0, EINVAL
}
}
// WriteAt writes len(b) bytes to the File starting at byte offset off.
-// It returns the number of bytes written and an Error, if any.
-// WriteAt returns a non-nil Error when n != len(b).
-func (file *File) WriteAt(b []byte, off int64) (n int, err Error) {
+// It returns the number of bytes written and an error, if any.
+// WriteAt returns a non-nil error when n != len(b).
+func (file *File) WriteAt(b []byte, off int64) (n int, err error) {
if file == nil {
return 0, EINVAL
}
// Seek sets the offset for the next Read or Write on file to offset, interpreted
// according to whence: 0 means relative to the origin of the file, 1 means
// relative to the current offset, and 2 means relative to the end.
-// It returns the new offset and an Error, if any.
-func (file *File) Seek(offset int64, whence int) (ret int64, err Error) {
+// It returns the new offset and an error, if any.
+func (file *File) Seek(offset int64, whence int) (ret int64, err error) {
r, e := file.seek(offset, whence)
if !iserror(e) && file.dirinfo != nil && r != 0 {
e = syscall.EISDIR
// WriteString is like Write, but writes the contents of string s rather than
// an array of bytes.
-func (file *File) WriteString(s string) (ret int, err Error) {
+func (file *File) WriteString(s string) (ret int, err error) {
if file == nil {
return 0, EINVAL
}
// Mkdir creates a new directory with the specified name and permission bits.
// It returns an error, if any.
-func Mkdir(name string, perm uint32) Error {
+func Mkdir(name string, perm uint32) error {
e := syscall.Mkdir(name, perm)
if iserror(e) {
return &PathError{"mkdir", name, Errno(e)}
}
// Chdir changes the current working directory to the named directory.
-func Chdir(dir string) Error {
+func Chdir(dir string) error {
if e := syscall.Chdir(dir); iserror(e) {
return &PathError{"chdir", dir, Errno(e)}
}
// Chdir changes the current working directory to the file,
// which must be a directory.
-func (f *File) Chdir() Error {
+func (f *File) Chdir() error {
if e := syscall.Fchdir(f.fd); iserror(e) {
return &PathError{"chdir", f.name, Errno(e)}
}
// Open opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode O_RDONLY.
-// It returns the File and an Error, if any.
-func Open(name string) (file *File, err Error) {
+// It returns the File and an error, if any.
+func Open(name string) (file *File, err error) {
return OpenFile(name, O_RDONLY, 0)
}
// it if it already exists. If successful, methods on the returned
// File can be used for I/O; the associated file descriptor has mode
// O_RDWR.
-// It returns the File and an Error, if any.
-func Create(name string) (file *File, err Error) {
+// It returns the File and an error, if any.
+func Create(name string) (file *File, err error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
// or Create instead. It opens the named file with specified flag
// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
// methods on the returned File can be used for I/O.
-// It returns the File and an Error, if any.
-func OpenFile(name string, flag int, perm uint32) (file *File, err Error) {
+// It returns the File and an error, if any.
+func OpenFile(name string, flag int, perm uint32) (file *File, err error) {
var (
fd int
e syscall.Error
}
// Close closes the File, rendering it unusable for I/O.
-// It returns an Error, if any.
-func (file *File) Close() Error {
+// It returns an error, if any.
+func (file *File) Close() error {
if file == nil || file.fd < 0 {
return Ebadfd
}
- var err Error
+ var err error
syscall.ForkLock.RLock()
if e := syscall.Close(file.fd); e != nil {
err = &PathError{"close", file.name, e}
// Stat returns the FileInfo structure describing file.
// It returns the FileInfo and an error, if any.
-func (f *File) Stat() (fi *FileInfo, err Error) {
+func (f *File) Stat() (fi *FileInfo, err error) {
d, err := dirstat(f)
if iserror(err) {
return nil, err
// Truncate changes the size of the file.
// It does not change the I/O offset.
-func (f *File) Truncate(size int64) Error {
+func (f *File) Truncate(size int64) error {
var d Dir
d.Null()
}
// Chmod changes the mode of the file to mode.
-func (f *File) Chmod(mode uint32) Error {
+func (f *File) Chmod(mode uint32) error {
var d Dir
var mask = ^uint32(0777)
// Sync commits the current contents of the file to stable storage.
// Typically, this means flushing the file system's in-memory copy
// of recently written data to disk.
-func (f *File) Sync() (err Error) {
+func (f *File) Sync() (err error) {
if f == nil {
return EINVAL
}
// Truncate changes the size of the named file.
// If the file is a symbolic link, it changes the size of the link's target.
-func Truncate(name string, size int64) Error {
+func Truncate(name string, size int64) error {
var d Dir
d.Null()
}
// Remove removes the named file or directory.
-func Remove(name string) Error {
+func Remove(name string) error {
if e := syscall.Remove(name); iserror(e) {
return &PathError{"remove", name, e}
}
}
// Rename renames a file.
-func Rename(oldname, newname string) Error {
+func Rename(oldname, newname string) error {
var d Dir
d.Null()
}
// Chmod changes the mode of the named file to mode.
-func Chmod(name string, mode uint32) Error {
+func Chmod(name string, mode uint32) error {
var d Dir
var mask = ^uint32(0777)
// The argument times are in nanoseconds, although the underlying
// filesystem may truncate or round the values to a more
// coarse time unit.
-func Chtimes(name string, atimeNs int64, mtimeNs int64) Error {
+func Chtimes(name string, atimeNs int64, mtimeNs int64) error {
var d Dir
d.Null()
return nil
}
-func Pipe() (r *File, w *File, err Error) {
+func Pipe() (r *File, w *File, err error) {
var p [2]int
syscall.ForkLock.RLock()
// not supported on Plan 9
// Link creates a hard link.
-func Link(oldname, newname string) Error {
+func Link(oldname, newname string) error {
return EPLAN9
}
-func Symlink(oldname, newname string) Error {
+func Symlink(oldname, newname string) error {
return EPLAN9
}
-func Readlink(name string) (string, Error) {
+func Readlink(name string) (string, error) {
return "", EPLAN9
}
-func Chown(name string, uid, gid int) Error {
+func Chown(name string, uid, gid int) error {
return EPLAN9
}
-func Lchown(name string, uid, gid int) Error {
+func Lchown(name string, uid, gid int) error {
return EPLAN9
}
-func (f *File) Chown(uid, gid int) Error {
+func (f *File) Chown(uid, gid int) error {
return EPLAN9
}
}
// Remove removes the named file or directory.
-func Remove(name string) Error {
+func Remove(name string) error {
// System call interface forces us to know
// whether name is a file or directory.
// Try both: it is cheaper on average than
// LinkError records an error during a link or symlink or rename
// system call and the paths that caused it.
type LinkError struct {
- Op string
- Old string
- New string
- Error Error
+ Op string
+ Old string
+ New string
+ Err error
}
-func (e *LinkError) String() string {
- return e.Op + " " + e.Old + " " + e.New + ": " + e.Error.String()
+func (e *LinkError) Error() string {
+ return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
}
// Link creates a hard link.
-func Link(oldname, newname string) Error {
+func Link(oldname, newname string) error {
e := syscall.Link(oldname, newname)
if iserror(e) {
return &LinkError{"link", oldname, newname, Errno(e)}
}
// Symlink creates a symbolic link.
-func Symlink(oldname, newname string) Error {
+func Symlink(oldname, newname string) error {
e := syscall.Symlink(oldname, newname)
if iserror(e) {
return &LinkError{"symlink", oldname, newname, Errno(e)}
}
// Readlink reads the contents of a symbolic link: the destination of
-// the link. It returns the contents and an Error, if any.
-func Readlink(name string) (string, Error) {
+// the link. It returns the contents and an error, if any.
+func Readlink(name string) (string, error) {
for len := 128; ; len *= 2 {
b := make([]byte, len)
n, e := syscall.Readlink(name, b)
}
// Rename renames a file.
-func Rename(oldname, newname string) Error {
+func Rename(oldname, newname string) error {
e := syscall.Rename(oldname, newname)
if iserror(e) {
return &LinkError{"rename", oldname, newname, Errno(e)}
// Chmod changes the mode of the named file to mode.
// If the file is a symbolic link, it changes the mode of the link's target.
-func Chmod(name string, mode uint32) Error {
+func Chmod(name string, mode uint32) error {
if e := syscall.Chmod(name, mode); iserror(e) {
return &PathError{"chmod", name, Errno(e)}
}
}
// Chmod changes the mode of the file to mode.
-func (f *File) Chmod(mode uint32) Error {
+func (f *File) Chmod(mode uint32) error {
if e := syscall.Fchmod(f.fd, mode); iserror(e) {
return &PathError{"chmod", f.name, Errno(e)}
}
// Chown changes the numeric uid and gid of the named file.
// If the file is a symbolic link, it changes the uid and gid of the link's target.
-func Chown(name string, uid, gid int) Error {
+func Chown(name string, uid, gid int) error {
if e := syscall.Chown(name, uid, gid); iserror(e) {
return &PathError{"chown", name, Errno(e)}
}
// Lchown changes the numeric uid and gid of the named file.
// If the file is a symbolic link, it changes the uid and gid of the link itself.
-func Lchown(name string, uid, gid int) Error {
+func Lchown(name string, uid, gid int) error {
if e := syscall.Lchown(name, uid, gid); iserror(e) {
return &PathError{"lchown", name, Errno(e)}
}
}
// Chown changes the numeric uid and gid of the named file.
-func (f *File) Chown(uid, gid int) Error {
+func (f *File) Chown(uid, gid int) error {
if e := syscall.Fchown(f.fd, uid, gid); iserror(e) {
return &PathError{"chown", f.name, Errno(e)}
}
// Truncate changes the size of the file.
// It does not change the I/O offset.
-func (f *File) Truncate(size int64) Error {
+func (f *File) Truncate(size int64) error {
if e := syscall.Ftruncate(f.fd, size); iserror(e) {
return &PathError{"truncate", f.name, Errno(e)}
}
// Sync commits the current contents of the file to stable storage.
// Typically, this means flushing the file system's in-memory copy
// of recently written data to disk.
-func (file *File) Sync() (err Error) {
+func (file *File) Sync() (err error) {
if file == nil {
return EINVAL
}
// The argument times are in nanoseconds, although the underlying
// filesystem may truncate or round the values to a more
// coarse time unit.
-func Chtimes(name string, atime_ns int64, mtime_ns int64) Error {
+func Chtimes(name string, atime_ns int64, mtime_ns int64) error {
var utimes [2]syscall.Timeval
utimes[0] = syscall.NsecToTimeval(atime_ns)
utimes[1] = syscall.NsecToTimeval(mtime_ns)
// or Create instead. It opens the named file with specified flag
// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,
// methods on the returned File can be used for I/O.
-// It returns the File and an Error, if any.
-func OpenFile(name string, flag int, perm uint32) (file *File, err Error) {
+// It returns the File and an error, if any.
+func OpenFile(name string, flag int, perm uint32) (file *File, err error) {
r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm)
if e != 0 {
return nil, &PathError{"open", name, Errno(e)}
}
// Close closes the File, rendering it unusable for I/O.
-// It returns an Error, if any.
-func (file *File) Close() Error {
+// It returns an error, if any.
+func (file *File) Close() error {
if file == nil || file.fd < 0 {
return EINVAL
}
- var err Error
+ var err error
if e := syscall.Close(file.fd); e != 0 {
err = &PathError{"close", file.name, Errno(e)}
}
// Stat returns the FileInfo structure describing file.
// It returns the FileInfo and an error, if any.
-func (file *File) Stat() (fi *FileInfo, err Error) {
+func (file *File) Stat() (fi *FileInfo, err error) {
var stat syscall.Stat_t
e := syscall.Fstat(file.fd, &stat)
if e != 0 {
// the file pointed at by the link and has fi.FollowedSymlink set to true.
// If name names an invalid symbolic link, the returned FileInfo describes
// the link itself and has fi.FollowedSymlink set to false.
-func Stat(name string) (fi *FileInfo, err Error) {
+func Stat(name string) (fi *FileInfo, err error) {
var lstat, stat syscall.Stat_t
e := syscall.Lstat(name, &lstat)
if iserror(e) {
// Lstat returns the FileInfo structure describing the named file and an
// error, if any. If the file is a symbolic link, the returned FileInfo
// describes the symbolic link. Lstat makes no attempt to follow the link.
-func Lstat(name string) (fi *FileInfo, err Error) {
+func Lstat(name string) (fi *FileInfo, err error) {
var stat syscall.Stat_t
e := syscall.Lstat(name, &stat)
if iserror(e) {
// If n <= 0, Readdir returns all the FileInfo from the directory in
// a single slice. In this case, if Readdir succeeds (reads all
// the way to the end of the directory), it returns the slice and a
-// nil os.Error. If it encounters an error before the end of the
+// nil error. If it encounters an error before the end of the
// directory, Readdir returns the FileInfo read until that point
// and a non-nil error.
-func (file *File) Readdir(n int) (fi []FileInfo, err Error) {
+func (file *File) Readdir(n int) (fi []FileInfo, err error) {
dirname := file.name
if dirname == "" {
dirname = "."
// Truncate changes the size of the named file.
// If the file is a symbolic link, it changes the size of the link's target.
-func Truncate(name string, size int64) Error {
+func Truncate(name string, size int64) error {
if e := syscall.Truncate(name, size); e != 0 {
return &PathError{"truncate", name, Errno(e)}
}
}
// Pipe returns a connected pair of Files; reads from r return bytes written to w.
-// It returns the files and an Error, if any.
-func Pipe() (r *File, w *File, err Error) {
+// It returns the files and an error, if any.
+func Pipe() (r *File, w *File, err error) {
var p [2]int
// See ../syscall/exec.go for description of lock.
// current directory. If the current directory can be
// reached via multiple paths (due to symbolic links),
// Getwd may return any one of them.
-func Getwd() (string, Error) {
+func Getwd() (string, error) {
// If the operating system provides a Getwd call, use it.
if syscall.ImplementsGetwd {
s, e := syscall.Getwd()
for {
n, e := file.Read(buf[0:])
len += n
- if e == EOF {
+ if e == io.EOF {
break
}
if e != nil {
count := 0
for {
d, err := file.Readdirnames(1)
- if err == EOF {
+ if err == io.EOF {
break
}
if err != nil {
var d *File
openDir := func() {
- var err Error
+ var err error
d, err = Open(dir)
if err != nil {
t.Fatalf("Open directory: %v", err)
}
}
- readDirExpect := func(n, want int, wantErr Error) {
+ readDirExpect := func(n, want int, wantErr error) {
fi, err := d.Readdir(n)
if err != wantErr {
t.Fatalf("Readdir of %d got error %v, want %v", n, err, wantErr)
}
}
- readDirNamesExpect := func(n, want int, wantErr Error) {
+ readDirNamesExpect := func(n, want int, wantErr error) {
fi, err := d.Readdirnames(n)
if err != wantErr {
t.Fatalf("Readdirnames of %d got error %v, want %v", n, err, wantErr)
}
}
- for _, fn := range []func(int, int, Error){readDirExpect, readDirNamesExpect} {
+ for _, fn := range []func(int, int, error){readDirExpect, readDirNamesExpect} {
// Test the slurp case
openDir()
fn(0, 105, nil)
fn(1, 1, nil)
fn(2, 2, nil)
fn(105, 102, nil) // and tests buffer >100 case
- fn(3, 0, EOF)
+ fn(3, 0, io.EOF)
d.Close()
}
}
for i, tt := range tests {
off, err := f.Seek(tt.in, tt.whence)
if off != tt.out || err != nil {
- if e, ok := err.(*PathError); ok && e.Error == EINVAL && tt.out > 1<<32 {
+ if e, ok := err.(*PathError); ok && e.Err == EINVAL && tt.out > 1<<32 {
// Reiserfs rejects the big seeks.
// http://code.google.com/p/go/issues/detail?id=91
break
type openErrorTest struct {
path string
mode int
- error Error
+ error error
}
var openErrorTests = []openErrorTest{
if !ok {
t.Errorf("Open(%q, %d) returns error of %T type; want *os.PathError", tt.path, tt.mode, err)
}
- if perr.Error != tt.error {
+ if perr.Err != tt.error {
if syscall.OS == "plan9" {
- syscallErrStr := perr.Error.String()
- expectedErrStr := strings.Replace(tt.error.String(), "file ", "", 1)
+ syscallErrStr := perr.Err.Error()
+ expectedErrStr := strings.Replace(tt.error.Error(), "file ", "", 1)
if !strings.HasSuffix(syscallErrStr, expectedErrStr) {
t.Errorf("Open(%q, %d) = _, %q; want suffix %q", tt.path, tt.mode, syscallErrStr, expectedErrStr)
}
} else {
- t.Errorf("Open(%q, %d) = _, %q; want %q", tt.path, tt.mode, perr.Error.String(), tt.error.String())
+ t.Errorf("Open(%q, %d) = _, %q; want %q", tt.path, tt.mode, perr.Err.Error(), tt.error.Error())
}
}
}
package os
+import "io"
+
// MkdirAll creates a directory named path,
// along with any necessary parents, and returns nil,
// or else returns an error.
// directories that MkdirAll creates.
// If path is already a directory, MkdirAll does nothing
// and returns nil.
-func MkdirAll(path string, perm uint32) Error {
+func MkdirAll(path string, perm uint32) error {
// If path exists, stop with success or error.
dir, err := Stat(path)
if err == nil {
// It removes everything it can but returns the first error
// it encounters. If the path does not exist, RemoveAll
// returns nil (no error).
-func RemoveAll(path string) Error {
+func RemoveAll(path string) error {
// Simple case: if Remove works, we're done.
err := Remove(path)
if err == nil {
// Otherwise, is this a directory we need to recurse into?
dir, serr := Lstat(path)
if serr != nil {
- if serr, ok := serr.(*PathError); ok && (serr.Error == ENOENT || serr.Error == ENOTDIR) {
+ if serr, ok := serr.(*PathError); ok && (serr.Err == ENOENT || serr.Err == ENOTDIR) {
return nil
}
return serr
err = err1
}
}
- if err1 == EOF {
+ if err1 == io.EOF {
break
}
// If Readdirnames returned an error, use it.
if err != nil {
pathErr, ok := err.(*PathError)
// common for users not to be able to write to /
- if ok && pathErr.Error == EACCES {
+ if ok && pathErr.Err == EACCES {
return
}
t.Fatalf(`MkdirAll "/_go_os_test/dir": %v`, err)
func Getegid() int { return syscall.Getegid() }
// Getgroups returns a list of the numeric ids of groups that the caller belongs to.
-func Getgroups() ([]int, Error) {
+func Getgroups() ([]int, error) {
gids, e := syscall.Getgroups()
return gids, NewSyscallError("getgroups", e)
}
}
// arg is an open *File or a path string.
-func dirstat(arg interface{}) (d *Dir, err Error) {
+func dirstat(arg interface{}) (d *Dir, err error) {
var name string
nd := syscall.STATFIXLEN + 16*4
}
// Stat returns a FileInfo structure describing the named file and an error, if any.
-func Stat(name string) (fi *FileInfo, err Error) {
+func Stat(name string) (fi *FileInfo, err error) {
d, err := dirstat(name)
if iserror(err) {
return nil, err
// Lstat returns the FileInfo structure describing the named file and an
// error, if any. If the file is a symbolic link (though Plan 9 does not have symbolic links),
// the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link.
-func Lstat(name string) (fi *FileInfo, err Error) {
+func Lstat(name string) (fi *FileInfo, err error) {
d, err := dirstat(name)
if iserror(err) {
return nil, err
import "syscall"
-func Hostname() (name string, err Error) {
+func Hostname() (name string, err error) {
var errno int
name, errno = syscall.Sysctl("kern.hostname")
if errno != 0 {
package os
// Hostname returns the host name reported by the kernel.
-func Hostname() (name string, err Error) {
+func Hostname() (name string, err error) {
f, err := Open("/proc/sys/kernel/hostname")
if err != nil {
return "", err
package os
-func Hostname() (name string, err Error) {
+func Hostname() (name string, err error) {
f, err := Open("#c/sysname")
if err != nil {
return "", err
import "syscall"
// Time returns the current time, in whole seconds and
-// fractional nanoseconds, plus an Error if any. The current
+// fractional nanoseconds, plus an error if any. The current
// time is thus 1e9*sec+nsec, in nanoseconds. The zero of
// time is the Unix epoch.
-func Time() (sec int64, nsec int64, err Error) {
+func Time() (sec int64, nsec int64, err error) {
var tv syscall.Timeval
if e := syscall.Gettimeofday(&tv); iserror(e) {
return 0, 0, NewSyscallError("gettimeofday", e)
import (
"fmt"
- "os"
"runtime"
)
-func Lookup(username string) (*User, os.Error) {
+func Lookup(username string) (*User, error) {
return nil, fmt.Errorf("user: Lookup not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
-func LookupId(int) (*User, os.Error) {
+func LookupId(int) (*User, error) {
return nil, fmt.Errorf("user: LookupId not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
}
// Lookup looks up a user by username. If the user cannot be found,
// the returned error is of type UnknownUserError.
-func Lookup(username string) (*User, os.Error) {
+func Lookup(username string) (*User, error) {
return lookup(-1, username, true)
}
// LookupId looks up a user by userid. If the user cannot be found,
// the returned error is of type UnknownUserIdError.
-func LookupId(uid int) (*User, os.Error) {
+func LookupId(uid int) (*User, error) {
return lookup(uid, "", false)
}
-func lookup(uid int, username string, lookupByName bool) (*User, os.Error) {
+func lookup(uid int, username string, lookupByName bool) (*User, error) {
var pwd syscall.Passwd
var result *syscall.Passwd
// a user cannot be found.
type UnknownUserIdError int
-func (e UnknownUserIdError) String() string {
+func (e UnknownUserIdError) Error() string {
return "user: unknown userid " + strconv.Itoa(int(e))
}
// a user cannot be found.
type UnknownUserError string
-func (e UnknownUserError) String() string {
+func (e UnknownUserError) Error() string {
return "user: unknown user " + string(e)
}
// The function readFile should return the contents of the named file.
// Typically this function will be io.ReadFile.
//
-func (set *Set) Apply(readFile func(string) ([]byte, os.Error)) ([]Op, os.Error) {
+func (set *Set) Apply(readFile func(string) ([]byte, error)) ([]Op, error) {
op := make([]Op, len(set.File))
for i, f := range set.File {
// Clients assume o.Data == nil means no data diff.
// Start with a non-nil data.
var old []byte = make([]byte, 0) // not nil
- var err os.Error
+ var err error
if f.Src != "" {
old, err = readFile(f.Src)
if err != nil {
"compress/zlib"
"crypto/sha1"
"encoding/git85"
+ "errors"
"fmt"
"io"
- "os"
)
func gitSHA1(data []byte) []byte {
}
// Apply implements the Diff interface's Apply method.
-func (d *GitBinaryLiteral) Apply(old []byte) ([]byte, os.Error) {
+func (d *GitBinaryLiteral) Apply(old []byte) ([]byte, error) {
if sum := gitSHA1(old); !bytes.HasPrefix(sum, d.OldSHA1) {
return nil, ErrPatchFailure
}
}
// ParseGitBinary parses raw as a Git binary patch.
-func ParseGitBinary(raw []byte) (Diff, os.Error) {
+func ParseGitBinary(raw []byte) (Diff, error) {
var oldSHA1, newSHA1 []byte
var sawBinary bool
}
defer z.Close()
if _, err = io.ReadFull(z, data); err != nil {
- if err == os.EOF {
+ if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
var buf [1]byte
m, err := z.Read(buf[0:])
- if m != 0 || err != os.EOF {
- return nil, os.NewError("Git binary literal longer than expected")
+ if m != 0 || err != io.EOF {
+ return nil, errors.New("Git binary literal longer than expected")
}
if sum := gitSHA1(data); !bytes.HasPrefix(sum, newSHA1) {
- return nil, os.NewError("Git binary literal SHA1 mismatch")
+ return nil, errors.New("Git binary literal SHA1 mismatch")
}
return &GitBinaryLiteral{oldSHA1, data}, nil
}
if !sawBinary {
- return nil, os.NewError("unexpected Git patch header: " + string(first))
+ return nil, errors.New("unexpected Git patch header: " + string(first))
}
}
panic("unreachable")
import (
"bytes"
- "os"
"path"
"strings"
)
// Apply applies the changes listed in the diff
// to the string s, returning the new version of the string.
// Note that the string s need not be a text string.
- Apply(old []byte) (new []byte, err os.Error)
+ Apply(old []byte) (new []byte, err error)
}
// NoDiff is a no-op Diff implementation: it passes the
type noDiffType int
-func (noDiffType) Apply(old []byte) ([]byte, os.Error) {
+func (noDiffType) Apply(old []byte) ([]byte, error) {
return old, nil
}
// A SyntaxError represents a syntax error encountered while parsing a patch.
type SyntaxError string
-func (e SyntaxError) String() string { return string(e) }
+func (e SyntaxError) Error() string { return string(e) }
var newline = []byte{'\n'}
// The patch text typically comprises a textual header and a sequence
// of file patches, as would be generated by CVS, Subversion,
// Mercurial, or Git.
-func Parse(text []byte) (*Set, os.Error) {
+func Parse(text []byte) (*Set, error) {
// Split text into files.
// CVS and Subversion begin new files with
// Index: file name.
import (
"bytes"
- "os"
+ "errors"
)
type TextDiff []TextChunk
New []byte
}
-func ParseTextDiff(raw []byte) (TextDiff, os.Error) {
+func ParseTextDiff(raw []byte) (TextDiff, error) {
var chunkHeader []byte
// Copy raw so it is safe to keep references to slices.
return nil, SyntaxError("unexpected chunk header line: " + string(chunkHeader))
}
-var ErrPatchFailure = os.NewError("patch did not apply cleanly")
+var ErrPatchFailure = errors.New("patch did not apply cleanly")
// Apply applies the changes listed in the diff
// to the data, returning the new version.
-func (d TextDiff) Apply(data []byte) ([]byte, os.Error) {
+func (d TextDiff) Apply(data []byte) ([]byte, error) {
var buf bytes.Buffer
line := 1
for _, c := range d {
package filepath
import (
+ "errors"
"os"
"sort"
"strings"
"utf8"
)
-var ErrBadPattern = os.NewError("syntax error in pattern")
+var ErrBadPattern = errors.New("syntax error in pattern")
// Match returns true if name matches the shell file name pattern.
// The pattern syntax is:
// Match requires pattern to match all of name, not just a substring.
// The only possible error return occurs when the pattern is malformed.
//
-func Match(pattern, name string) (matched bool, err os.Error) {
+func Match(pattern, name string) (matched bool, err error) {
Pattern:
for len(pattern) > 0 {
var star bool
// matchChunk checks whether chunk matches the beginning of s.
// If so, it returns the remainder of s (after the match).
// Chunk is all single-character operators: literals, char classes, and ?.
-func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) {
+func matchChunk(chunk, s string) (rest string, ok bool, err error) {
for len(chunk) > 0 {
if len(s) == 0 {
return
}
// getEsc gets a possibly-escaped character from chunk, for a character class.
-func getEsc(chunk string) (r rune, nchunk string, err os.Error) {
+func getEsc(chunk string) (r rune, nchunk string, err error) {
if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' {
err = ErrBadPattern
return
// /usr/*/bin/ed (assuming the Separator is '/').
// The only possible error return occurs when the pattern is malformed.
//
-func Glob(pattern string) (matches []string, err os.Error) {
+func Glob(pattern string) (matches []string, err error) {
if !hasMeta(pattern) {
if _, err = os.Stat(pattern); err != nil {
return nil, nil
// opened, it returns the existing matches. New matches are
// added in lexicographical order.
// The only possible error return occurs when the pattern is malformed.
-func glob(dir, pattern string, matches []string) (m []string, e os.Error) {
+func glob(dir, pattern string, matches []string) (m []string, e error) {
m = matches
fi, err := os.Stat(dir)
if err != nil {
package filepath_test
import (
- "os"
. "path/filepath"
"testing"
"runtime"
type MatchTest struct {
pattern, s string
match bool
- err os.Error
+ err error
}
var matchTests = []MatchTest{
{"*x", "xxx", true, nil},
}
-func errp(e os.Error) string {
+func errp(e error) string {
if e == nil {
return "<nil>"
}
- return e.String()
+ return e.Error()
}
func TestMatch(t *testing.T) {
import (
"bytes"
+ "errors"
"os"
"runtime"
"sort"
// EvalSymlinks returns the path name after the evaluation of any symbolic
// links.
// If path is relative it will be evaluated relative to the current directory.
-func EvalSymlinks(path string) (string, os.Error) {
+func EvalSymlinks(path string) (string, error) {
if runtime.GOOS == "windows" {
// Symlinks are not supported under windows.
_, err := os.Lstat(path)
var b bytes.Buffer
for n := 0; path != ""; n++ {
if n > maxIter {
- return "", os.NewError("EvalSymlinks: too many links in " + originalPath)
+ return "", errors.New("EvalSymlinks: too many links in " + originalPath)
}
// find next path component, p
// If the path is not absolute it will be joined with the current
// working directory to turn it into an absolute path. The absolute
// path name for a given file is not guaranteed to be unique.
-func Abs(path string) (string, os.Error) {
+func Abs(path string) (string, error) {
if IsAbs(path) {
return Clean(path), nil
}
// Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
// An error is returned if targpath can't be made relative to basepath or if
// knowing the current working directory would be necessary to compute it.
-func Rel(basepath, targpath string) (string, os.Error) {
+func Rel(basepath, targpath string) (string, error) {
baseVol := VolumeName(basepath)
targVol := VolumeName(targpath)
base := Clean(basepath)
baseSlashed := len(base) > 0 && base[0] == Separator
targSlashed := len(targ) > 0 && targ[0] == Separator
if baseSlashed != targSlashed || baseVol != targVol {
- return "", os.NewError("Rel: can't make " + targ + " relative to " + base)
+ return "", errors.New("Rel: can't make " + targ + " relative to " + base)
}
// Position base[b0:bi] and targ[t0:ti] at the first differing elements.
bl := len(base)
t0 = ti
}
if base[b0:bi] == ".." {
- return "", os.NewError("Rel: can't make " + targ + " relative to " + base)
+ return "", errors.New("Rel: can't make " + targ + " relative to " + base)
}
if b0 != bl {
// Base elements left. Must go up before going down.
// SkipDir is used as a return value from WalkFuncs to indicate that
// the directory named in the call is to be skipped. It is not returned
// as an error by any function.
-var SkipDir = os.NewError("skip this directory")
+var SkipDir = errors.New("skip this directory")
// WalkFunc is the type of the function called for each file or directory
// visited by Walk. If there was a problem walking to the file or directory
// sole exception is that if path is a directory and the function returns the
// special value SkipDir, the contents of the directory are skipped
// and processing continues as usual on the next file.
-type WalkFunc func(path string, info *os.FileInfo, err os.Error) os.Error
+type WalkFunc func(path string, info *os.FileInfo, err error) error
// walk recursively descends path, calling w.
-func walk(path string, info *os.FileInfo, walkFn WalkFunc) os.Error {
+func walk(path string, info *os.FileInfo, walkFn WalkFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.IsDirectory() && err == SkipDir {
// and directories are filtered by walkFn. The files are walked in lexical
// order, which makes the output deterministic but means that for very
// large directories Walk can be inefficient.
-func Walk(root string, walkFn WalkFunc) os.Error {
+func Walk(root string, walkFn WalkFunc) error {
info, err := os.Lstat(root)
if err != nil {
return walkFn(root, nil, err)
// readDir reads the directory named by dirname and returns
// a sorted list of directory entries.
// Copied from io/ioutil to avoid the circular import.
-func readDir(dirname string) ([]*os.FileInfo, os.Error) {
+func readDir(dirname string) ([]*os.FileInfo, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
// Assumes that each node name is unique. Good enough for a test.
// If clear is true, any incoming error is cleared before return. The errors
// are always accumulated, though.
-func mark(path string, info *os.FileInfo, err os.Error, errors *[]os.Error, clear bool) os.Error {
+func mark(path string, info *os.FileInfo, err error, errors *[]error, clear bool) error {
if err != nil {
*errors = append(*errors, err)
if clear {
func TestWalk(t *testing.T) {
makeTree(t)
- errors := make([]os.Error, 0, 10)
+ errors := make([]error, 0, 10)
clear := true
- markFn := func(path string, info *os.FileInfo, err os.Error) os.Error {
+ markFn := func(path string, info *os.FileInfo, err error) error {
return mark(path, info, err, &errors, clear)
}
// Expect no errors.
func TestEvalSymlinks(t *testing.T) {
defer os.RemoveAll("test")
for _, d := range EvalSymlinksTestDirs {
- var err os.Error
+ var err error
if d.dest == "" {
err = os.Mkdir(d.path, 0755)
} else {
func TestAbs(t *testing.T) {
oldwd, err := os.Getwd()
if err != nil {
- t.Fatal("Getwd failed: " + err.String())
+ t.Fatal("Getwd failed: " + err.Error())
}
defer os.Chdir(oldwd)
goroot := os.Getenv("GOROOT")
package path
import (
- "os"
+ "errors"
"strings"
"utf8"
)
-var ErrBadPattern = os.NewError("syntax error in pattern")
+var ErrBadPattern = errors.New("syntax error in pattern")
// Match returns true if name matches the shell file name pattern.
// The pattern syntax is:
// Match requires pattern to match all of name, not just a substring.
// The only possible error return is when pattern is malformed.
//
-func Match(pattern, name string) (matched bool, err os.Error) {
+func Match(pattern, name string) (matched bool, err error) {
Pattern:
for len(pattern) > 0 {
var star bool
// matchChunk checks whether chunk matches the beginning of s.
// If so, it returns the remainder of s (after the match).
// Chunk is all single-character operators: literals, char classes, and ?.
-func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) {
+func matchChunk(chunk, s string) (rest string, ok bool, err error) {
for len(chunk) > 0 {
if len(s) == 0 {
return
}
// getEsc gets a possibly-escaped character from chunk, for a character class.
-func getEsc(chunk string) (r rune, nchunk string, err os.Error) {
+func getEsc(chunk string) (r rune, nchunk string, err error) {
if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' {
err = ErrBadPattern
return
package path
-import (
- "os"
- "testing"
-)
+import "testing"
type MatchTest struct {
pattern, s string
match bool
- err os.Error
+ err error
}
var matchTests = []MatchTest{
package rand
import (
+ "errors"
"math"
"fmt"
- "os"
"testing"
)
// checkSimilarDistribution returns success if the mean and stddev of the
// two statsResults are similar.
-func (this *statsResults) checkSimilarDistribution(expected *statsResults) os.Error {
+func (this *statsResults) checkSimilarDistribution(expected *statsResults) error {
if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) {
s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
fmt.Println(s)
- return os.NewError(s)
+ return errors.New(s)
}
if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) {
s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
fmt.Println(s)
- return os.NewError(s)
+ return errors.New(s)
}
return nil
}
actual := getStatsResults(samples)
err := actual.checkSimilarDistribution(expected)
if err != nil {
- t.Errorf(err.String())
+ t.Errorf(err.Error())
}
}
{make([]int, 10), make([]int, 10), true},
{&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
{Basic{1, 0.5}, Basic{1, 0.5}, true},
- {os.Error(nil), os.Error(nil), true},
+ {error(nil), error(nil), true},
{map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
// Inequalities
Kind Kind
}
-func (e *ValueError) String() string {
+func (e *ValueError) Error() string {
if e.Kind == 0 {
return "reflect: call of " + e.Method + " on zero Value"
}
package regexp
import (
- "os"
"strings"
"testing"
)
/*
type stringError struct {
re string
- err os.Error
+ err error
}
var bad_re = []stringError{
}
*/
-func compileTest(t *testing.T, expr string, error os.Error) *Regexp {
+func compileTest(t *testing.T, expr string, error error) *Regexp {
re, err := Compile(expr)
if err != error {
- t.Error("compiling `", expr, "`; unexpected error: ", err.String())
+ t.Error("compiling `", expr, "`; unexpected error: ", err.Error())
}
return re
}
for {
line, err := r.ReadString('\n')
if err != nil {
- if err == os.EOF {
+ if err == io.EOF {
break
}
t.Fatalf("%s:%d: %v", file, lineno, err)
}
re, err = tryCompile(q)
if err != nil {
- if err.String() == "error parsing regexp: invalid escape sequence: `\\C`" {
+ if err.Error() == "error parsing regexp: invalid escape sequence: `\\C`" {
// We don't and likely never will support \C; keep going.
continue
}
return true
}
-func tryCompile(s string) (re *Regexp, err os.Error) {
+func tryCompile(s string) (re *Regexp, err error) {
// Protect against panic during Compile.
defer func() {
if r := recover(); r != nil {
lineno++
line, err := b.ReadString('\n')
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("%s:%d: %v", file, lineno, err)
}
break Reading
return
}
var v = -1
- var err os.Error
+ var err error
if s[:i] != "?" {
v, err = strconv.Atoi(s[:i])
if err != nil {
import (
"bytes"
"io"
- "os"
"regexp/syntax"
"strconv"
"strings"
// Error is the local type for a parsing error.
type Error string
-func (e Error) String() string {
+func (e Error) Error() string {
return string(e)
}
// that Perl, Python, and other implementations use, although this
// package implements it without the expense of backtracking.
// For POSIX leftmost-longest matching, see CompilePOSIX.
-func Compile(expr string) (*Regexp, os.Error) {
+func Compile(expr string) (*Regexp, error) {
return compile(expr, syntax.Perl, false)
}
// subexpression, then the second, and so on from left to right.
// The POSIX rule is computationally prohibitive and not even well-defined.
// See http://swtch.com/~rsc/regexp/regexp2.html#posix for details.
-func CompilePOSIX(expr string) (*Regexp, os.Error) {
+func CompilePOSIX(expr string) (*Regexp, error) {
return compile(expr, syntax.POSIX, true)
}
-func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, os.Error) {
+func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, error) {
re, err := syntax.Parse(expr, mode)
if err != nil {
return nil, err
func MustCompile(str string) *Regexp {
regexp, error := Compile(str)
if error != nil {
- panic(`regexp: Compile(` + quote(str) + `): ` + error.String())
+ panic(`regexp: Compile(` + quote(str) + `): ` + error.Error())
}
return regexp
}
func MustCompilePOSIX(str string) *Regexp {
regexp, error := CompilePOSIX(str)
if error != nil {
- panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.String())
+ panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.Error())
}
return regexp
}
// MatchReader checks whether a textual regular expression matches the text
// read by the RuneReader. More complicated queries need to use Compile and
// the full Regexp interface.
-func MatchReader(pattern string, r io.RuneReader) (matched bool, error os.Error) {
+func MatchReader(pattern string, r io.RuneReader) (matched bool, error error) {
re, err := Compile(pattern)
if err != nil {
return false, err
// MatchString checks whether a textual regular expression
// matches a string. More complicated queries need
// to use Compile and the full Regexp interface.
-func MatchString(pattern string, s string) (matched bool, error os.Error) {
+func MatchString(pattern string, s string) (matched bool, error error) {
re, err := Compile(pattern)
if err != nil {
return false, err
// Match checks whether a textual regular expression
// matches a byte slice. More complicated queries need
// to use Compile and the full Regexp interface.
-func Match(pattern string, b []byte) (matched bool, error os.Error) {
+func Match(pattern string, b []byte) (matched bool, error error) {
re, err := Compile(pattern)
if err != nil {
return false, err
package syntax
-import (
- "os"
- "unicode"
-)
+import "unicode"
// A patchList is a list of instruction pointers that need to be filled in (patched).
// Because the pointers haven't been filled in yet, we can reuse their storage
// Compile compiles the regexp into a program to be executed.
// The regexp should have been simplified already (returned from re.Simplify).
-func Compile(re *Regexp) (*Prog, os.Error) {
+func Compile(re *Regexp) (*Prog, error) {
var c compiler
c.init()
f := c.compile(re)
package syntax
import (
- "os"
"sort"
"strings"
"unicode"
Expr string
}
-func (e *Error) String() string {
+func (e *Error) Error() string {
return "error parsing regexp: " + e.Code.String() + ": `" + e.Expr + "`"
}
// before is the regexp suffix starting at the repetition operator.
// after is the regexp suffix following after the repetition operator.
// repeat returns an updated 'after' and an error, if any.
-func (p *parser) repeat(op Op, min, max int, before, after, lastRepeat string) (string, os.Error) {
+func (p *parser) repeat(op Op, min, max int, before, after, lastRepeat string) (string, error) {
flags := p.flags
if p.flags&PerlX != 0 {
if len(after) > 0 && after[0] == '?' {
// Parsing.
-func Parse(s string, flags Flags) (*Regexp, os.Error) {
+func Parse(s string, flags Flags) (*Regexp, error) {
if flags&Literal != 0 {
// Trivial parser for literal string.
if err := checkUTF8(s); err != nil {
// Otherwise, must do real work.
var (
p parser
- err os.Error
+ err error
c rune
op Op
lastRepeat string
// parsePerlFlags parses a Perl flag setting or non-capturing group or both,
// like (?i) or (?: or (?i:. It removes the prefix from s and updates the parse state.
// The caller must have ensured that s begins with "(?".
-func (p *parser) parsePerlFlags(s string) (rest string, err os.Error) {
+func (p *parser) parsePerlFlags(s string) (rest string, err error) {
t := s
// Check for named captures, first introduced in Python's regexp library.
}
// parseVerticalBar handles a | in the input.
-func (p *parser) parseVerticalBar() os.Error {
+func (p *parser) parseVerticalBar() error {
p.concat()
// The concatenation we just parsed is on top of the stack.
}
// parseRightParen handles a ) in the input.
-func (p *parser) parseRightParen() os.Error {
+func (p *parser) parseRightParen() error {
p.concat()
if p.swapVerticalBar() {
// pop vertical bar
// parseEscape parses an escape sequence at the beginning of s
// and returns the rune.
-func (p *parser) parseEscape(s string) (r rune, rest string, err os.Error) {
+func (p *parser) parseEscape(s string) (r rune, rest string, err error) {
t := s[1:]
if t == "" {
return 0, "", &Error{ErrTrailingBackslash, ""}
// parseClassChar parses a character class character at the beginning of s
// and returns it.
-func (p *parser) parseClassChar(s, wholeClass string) (r rune, rest string, err os.Error) {
+func (p *parser) parseClassChar(s, wholeClass string) (r rune, rest string, err error) {
if s == "" {
return 0, "", &Error{Code: ErrMissingBracket, Expr: wholeClass}
}
// parseNamedClass parses a leading POSIX named character class like [:alnum:]
// from the beginning of s. If one is present, it appends the characters to r
// and returns the new slice r and the remainder of the string.
-func (p *parser) parseNamedClass(s string, r []rune) (out []rune, rest string, err os.Error) {
+func (p *parser) parseNamedClass(s string, r []rune) (out []rune, rest string, err error) {
if len(s) < 2 || s[0] != '[' || s[1] != ':' {
return
}
// parseUnicodeClass parses a leading Unicode character class like \p{Han}
// from the beginning of s. If one is present, it appends the characters to r
// and returns the new slice r and the remainder of the string.
-func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, err os.Error) {
+func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, err error) {
if p.flags&UnicodeGroups == 0 || len(s) < 2 || s[0] != '\\' || s[1] != 'p' && s[1] != 'P' {
return
}
// parseClass parses a character class at the beginning of s
// and pushes it onto the parse stack.
-func (p *parser) parseClass(s string) (rest string, err os.Error) {
+func (p *parser) parseClass(s string) (rest string, err error) {
t := s[1:] // chop [
re := p.newRegexp(OpCharClass)
re.Flags = p.flags
p[i], p[i+1], p[j], p[j+1] = p[j], p[j+1], p[i], p[i+1]
}
-func checkUTF8(s string) os.Error {
+func checkUTF8(s string) error {
for s != "" {
rune, size := utf8.DecodeRuneInString(s)
if rune == utf8.RuneError && size == 1 {
return nil
}
-func nextRune(s string) (c rune, t string, err os.Error) {
+func nextRune(s string) (c rune, t string, err error) {
c, size := utf8.DecodeRuneInString(s)
if c == utf8.RuneError && size == 1 {
return 0, "", &Error{Code: ErrInvalidUTF8, Expr: s}
import (
"bufio"
+ "errors"
"gob"
"http"
"io"
"log"
"net"
- "os"
"sync"
)
// the remote side of the RPC connection.
type ServerError string
-func (e ServerError) String() string {
+func (e ServerError) Error() string {
return string(e)
}
-var ErrShutdown = os.NewError("connection is shut down")
+var ErrShutdown = errors.New("connection is shut down")
// Call represents an active RPC.
type Call struct {
ServiceMethod string // The name of the service and method to call.
Args interface{} // The argument to the function (*struct).
Reply interface{} // The reply from the function (*struct).
- Error os.Error // After completion, the error status.
+ Error error // After completion, the error status.
Done chan *Call // Strobes when call is complete; value is the error status.
seq uint64
}
// argument to force the body of the response to be read and then
// discarded.
type ClientCodec interface {
- WriteRequest(*Request, interface{}) os.Error
- ReadResponseHeader(*Response) os.Error
- ReadResponseBody(interface{}) os.Error
+ WriteRequest(*Request, interface{}) error
+ ReadResponseHeader(*Response) error
+ ReadResponseBody(interface{}) error
- Close() os.Error
+ Close() error
}
func (client *Client) send(c *Call) {
}
func (client *Client) input() {
- var err os.Error
+ var err error
var response Response
for err == nil {
response = Response{}
err = client.codec.ReadResponseHeader(&response)
if err != nil {
- if err == os.EOF && !client.closing {
+ if err == io.EOF && !client.closing {
err = io.ErrUnexpectedEOF
}
break
if response.Error == "" {
err = client.codec.ReadResponseBody(c.Reply)
if err != nil {
- c.Error = os.NewError("reading body " + err.String())
+ c.Error = errors.New("reading body " + err.Error())
}
} else {
// We've got an error response. Give this to the request;
c.Error = ServerError(response.Error)
err = client.codec.ReadResponseBody(nil)
if err != nil {
- err = os.NewError("reading error body: " + err.String())
+ err = errors.New("reading error body: " + err.Error())
}
}
c.done()
call.done()
}
client.mutex.Unlock()
- if err != os.EOF || !client.closing {
+ if err != io.EOF || !client.closing {
log.Println("rpc: client protocol error:", err)
}
}
encBuf *bufio.Writer
}
-func (c *gobClientCodec) WriteRequest(r *Request, body interface{}) (err os.Error) {
+func (c *gobClientCodec) WriteRequest(r *Request, body interface{}) (err error) {
if err = c.enc.Encode(r); err != nil {
return
}
return c.encBuf.Flush()
}
-func (c *gobClientCodec) ReadResponseHeader(r *Response) os.Error {
+func (c *gobClientCodec) ReadResponseHeader(r *Response) error {
return c.dec.Decode(r)
}
-func (c *gobClientCodec) ReadResponseBody(body interface{}) os.Error {
+func (c *gobClientCodec) ReadResponseBody(body interface{}) error {
return c.dec.Decode(body)
}
-func (c *gobClientCodec) Close() os.Error {
+func (c *gobClientCodec) Close() error {
return c.rwc.Close()
}
// DialHTTP connects to an HTTP RPC server at the specified network address
// listening on the default HTTP RPC path.
-func DialHTTP(network, address string) (*Client, os.Error) {
+func DialHTTP(network, address string) (*Client, error) {
return DialHTTPPath(network, address, DefaultRPCPath)
}
// DialHTTPPath connects to an HTTP RPC server
// at the specified network address and path.
-func DialHTTPPath(network, address, path string) (*Client, os.Error) {
- var err os.Error
+func DialHTTPPath(network, address, path string) (*Client, error) {
+ var err error
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
return NewClient(conn), nil
}
if err == nil {
- err = os.NewError("unexpected HTTP response: " + resp.Status)
+ err = errors.New("unexpected HTTP response: " + resp.Status)
}
conn.Close()
return nil, &net.OpError{"dial-http", network + " " + address, nil, err}
}
// Dial connects to an RPC server at the specified network address.
-func Dial(network, address string) (*Client, os.Error) {
+func Dial(network, address string) (*Client, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
return NewClient(conn), nil
}
-func (client *Client) Close() os.Error {
+func (client *Client) Close() error {
client.mutex.Lock()
if client.shutdown || client.closing {
client.mutex.Unlock()
}
// Call invokes the named function, waits for it to complete, and returns its error status.
-func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) os.Error {
+func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error {
if client.shutdown {
return ErrShutdown
}
<th align=center>Method</th><th align=center>Calls</th>
{{range .Method}}
<tr>
- <td align=left font=fixed>{{.Name}}({{.Type.ArgType}}, {{.Type.ReplyType}}) os.Error</td>
+ <td align=left font=fixed>{{.Name}}({{.Type.ArgType}}, {{.Type.ReplyType}}) error</td>
<td align=center>{{.Type.NumCalls}}</td>
</tr>
{{end}}
sort.Sort(services)
err := debug.Execute(w, services)
if err != nil {
- fmt.Fprintln(w, "rpc: error executing template:", err.String())
+ fmt.Fprintln(w, "rpc: error executing template:", err.Error())
}
}
package jsonrpc
import (
+ "errors"
"fmt"
"io"
"json"
"net"
- "os"
"rpc"
"testing"
)
type Arith int
-func (t *Arith) Add(args *Args, reply *Reply) os.Error {
+func (t *Arith) Add(args *Args, reply *Reply) error {
reply.C = args.A + args.B
return nil
}
-func (t *Arith) Mul(args *Args, reply *Reply) os.Error {
+func (t *Arith) Mul(args *Args, reply *Reply) error {
reply.C = args.A * args.B
return nil
}
-func (t *Arith) Div(args *Args, reply *Reply) os.Error {
+func (t *Arith) Div(args *Args, reply *Reply) error {
if args.B == 0 {
- return os.NewError("divide by zero")
+ return errors.New("divide by zero")
}
reply.C = args.A / args.B
return nil
}
-func (t *Arith) Error(args *Args, reply *Reply) os.Error {
+func (t *Arith) Error(args *Args, reply *Reply) error {
panic("ERROR")
}
reply := new(Reply)
err := client.Call("Arith.Add", args, reply)
if err != nil {
- t.Errorf("Add: expected no error but got string %q", err.String())
+ t.Errorf("Add: expected no error but got string %q", err.Error())
}
if reply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
reply = new(Reply)
err = client.Call("Arith.Mul", args, reply)
if err != nil {
- t.Errorf("Mul: expected no error but got string %q", err.String())
+ t.Errorf("Mul: expected no error but got string %q", err.Error())
}
if reply.C != args.A*args.B {
t.Errorf("Mul: expected %d got %d", reply.C, args.A*args.B)
addCall = <-addCall.Done
if addCall.Error != nil {
- t.Errorf("Add: expected no error but got string %q", addCall.Error.String())
+ t.Errorf("Add: expected no error but got string %q", addCall.Error.Error())
}
if addReply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", addReply.C, args.A+args.B)
mulCall = <-mulCall.Done
if mulCall.Error != nil {
- t.Errorf("Mul: expected no error but got string %q", mulCall.Error.String())
+ t.Errorf("Mul: expected no error but got string %q", mulCall.Error.Error())
}
if mulReply.C != args.A*args.B {
t.Errorf("Mul: expected %d got %d", mulReply.C, args.A*args.B)
// expect an error: zero divide
if err == nil {
t.Error("Div: expected error")
- } else if err.String() != "divide by zero" {
+ } else if err.Error() != "divide by zero" {
t.Error("Div: expected divide by zero error; got", err)
}
}
func TestUnexpectedError(t *testing.T) {
cli, srv := myPipe()
- go cli.PipeWriter.CloseWithError(os.NewError("unexpected error!")) // reader will get this error
- ServeConn(srv) // must return, not loop
+ go cli.PipeWriter.CloseWithError(errors.New("unexpected error!")) // reader will get this error
+ ServeConn(srv) // must return, not loop
}
// Copied from package net.
return "pipe"
}
-func (p *pipe) Close() os.Error {
+func (p *pipe) Close() error {
err := p.PipeReader.Close()
err1 := p.PipeWriter.Close()
if err == nil {
return pipeAddr(0)
}
-func (p *pipe) SetTimeout(nsec int64) os.Error {
- return os.NewError("net.Pipe does not support timeouts")
+func (p *pipe) SetTimeout(nsec int64) error {
+ return errors.New("net.Pipe does not support timeouts")
}
-func (p *pipe) SetReadTimeout(nsec int64) os.Error {
- return os.NewError("net.Pipe does not support timeouts")
+func (p *pipe) SetReadTimeout(nsec int64) error {
+ return errors.New("net.Pipe does not support timeouts")
}
-func (p *pipe) SetWriteTimeout(nsec int64) os.Error {
- return os.NewError("net.Pipe does not support timeouts")
+func (p *pipe) SetWriteTimeout(nsec int64) error {
+ return errors.New("net.Pipe does not support timeouts")
}
"io"
"json"
"net"
- "os"
"rpc"
"sync"
)
Id uint64 `json:"id"`
}
-func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) os.Error {
+func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) error {
c.mutex.Lock()
c.pending[r.Seq] = r.ServiceMethod
c.mutex.Unlock()
r.Error = nil
}
-func (c *clientCodec) ReadResponseHeader(r *rpc.Response) os.Error {
+func (c *clientCodec) ReadResponseHeader(r *rpc.Response) error {
c.resp.reset()
if err := c.dec.Decode(&c.resp); err != nil {
return err
return nil
}
-func (c *clientCodec) ReadResponseBody(x interface{}) os.Error {
+func (c *clientCodec) ReadResponseBody(x interface{}) error {
if x == nil {
return nil
}
return json.Unmarshal(*c.resp.Result, x)
}
-func (c *clientCodec) Close() os.Error {
+func (c *clientCodec) Close() error {
return c.c.Close()
}
}
// Dial connects to a JSON-RPC server at the specified network address.
-func Dial(network, address string) (*rpc.Client, os.Error) {
+func Dial(network, address string) (*rpc.Client, error) {
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
package jsonrpc
import (
+ "errors"
"io"
"json"
- "os"
"rpc"
"sync"
)
Error interface{} `json:"error"`
}
-func (c *serverCodec) ReadRequestHeader(r *rpc.Request) os.Error {
+func (c *serverCodec) ReadRequestHeader(r *rpc.Request) error {
c.req.reset()
if err := c.dec.Decode(&c.req); err != nil {
return err
return nil
}
-func (c *serverCodec) ReadRequestBody(x interface{}) os.Error {
+func (c *serverCodec) ReadRequestBody(x interface{}) error {
if x == nil {
return nil
}
var null = json.RawMessage([]byte("null"))
-func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) os.Error {
+func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) error {
var resp serverResponse
c.mutex.Lock()
b, ok := c.pending[r.Seq]
if !ok {
c.mutex.Unlock()
- return os.NewError("invalid sequence number in response")
+ return errors.New("invalid sequence number in response")
}
delete(c.pending, r.Seq)
c.mutex.Unlock()
return c.enc.Encode(resp)
}
-func (c *serverCodec) Close() os.Error {
+func (c *serverCodec) Close() error {
return c.c.Close()
}
registering the service).
- the method has two arguments, both exported or local types.
- the method's second argument is a pointer.
- - the method has return type os.Error.
+ - the method has return type error.
The method's first argument represents the arguments provided by the caller; the
second argument represents the result parameters to be returned to the caller.
The method's return value, if non-nil, is passed back as a string that the client
- sees as an os.ErrorString.
+ sees as if created by errors.New.
The server may handle requests on a single connection by calling ServeConn. More
typically it will create a network listener and call Accept or, for an HTTP
type Arith int
- func (t *Arith) Multiply(args *Args, reply *int) os.Error {
+ func (t *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
}
- func (t *Arith) Divide(args *Args, quo *Quotient) os.Error {
+ func (t *Arith) Divide(args *Args, quo *Quotient) error {
if args.B == 0 {
- return os.ErrorString("divide by zero")
+ return errors.New("divide by zero")
}
quo.Quo = args.A / args.B
quo.Rem = args.A % args.B
import (
"bufio"
+ "errors"
"gob"
"http"
"io"
"log"
"net"
- "os"
"reflect"
"strings"
"sync"
DefaultDebugPath = "/debug/rpc"
)
-// Precompute the reflect type for os.Error. Can't use os.Error directly
+// Precompute the reflect type for error. Can't use error directly
// because Typeof takes an empty interface value. This is annoying.
-var unusedError *os.Error
-var typeOfOsError = reflect.TypeOf(unusedError).Elem()
+var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
type methodType struct {
sync.Mutex // protects counters
// receiver value that satisfy the following conditions:
// - exported method
// - two arguments, both pointers to exported structs
-// - one return value, of type os.Error
+// - one return value, of type error
// It returns an error if the receiver is not an exported type or has no
// suitable methods.
// The client accesses each method using a string of the form "Type.Method",
// where Type is the receiver's concrete type.
-func (server *Server) Register(rcvr interface{}) os.Error {
+func (server *Server) Register(rcvr interface{}) error {
return server.register(rcvr, "", false)
}
// RegisterName is like Register but uses the provided name for the type
// instead of the receiver's concrete type.
-func (server *Server) RegisterName(name string, rcvr interface{}) os.Error {
+func (server *Server) RegisterName(name string, rcvr interface{}) error {
return server.register(rcvr, name, true)
}
-func (server *Server) register(rcvr interface{}, name string, useName bool) os.Error {
+func (server *Server) register(rcvr interface{}, name string, useName bool) error {
server.mu.Lock()
defer server.mu.Unlock()
if server.serviceMap == nil {
if !isExported(sname) && !useName {
s := "rpc Register: type " + sname + " is not exported"
log.Print(s)
- return os.NewError(s)
+ return errors.New(s)
}
if _, present := server.serviceMap[sname]; present {
- return os.NewError("rpc: service already defined: " + sname)
+ return errors.New("rpc: service already defined: " + sname)
}
s.name = sname
s.method = make(map[string]*methodType)
log.Println("method", mname, "reply type not exported or local:", replyType)
continue
}
- // Method needs one out: os.Error.
+ // Method needs one out: error.
if mtype.NumOut() != 1 {
log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
continue
}
- if returnType := mtype.Out(0); returnType != typeOfOsError {
- log.Println("method", mname, "returns", returnType.String(), "not os.Error")
+ if returnType := mtype.Out(0); returnType != typeOfError {
+ log.Println("method", mname, "returns", returnType.String(), "not error")
continue
}
s.method[mname] = &methodType{method: method, ArgType: argType, ReplyType: replyType}
if len(s.method) == 0 {
s := "rpc Register: type " + sname + " has no exported methods of suitable type"
log.Print(s)
- return os.NewError(s)
+ return errors.New(s)
}
server.serviceMap[s.name] = s
return nil
function := mtype.method.Func
// Invoke the method, providing a new value for the reply.
returnValues := function.Call([]reflect.Value{s.rcvr, argv, replyv})
- // The return value for the method is an os.Error.
+ // The return value for the method is an error.
errInter := returnValues[0].Interface()
errmsg := ""
if errInter != nil {
- errmsg = errInter.(os.Error).String()
+ errmsg = errInter.(error).Error()
}
server.sendResponse(sending, req, replyv.Interface(), codec, errmsg)
server.freeRequest(req)
encBuf *bufio.Writer
}
-func (c *gobServerCodec) ReadRequestHeader(r *Request) os.Error {
+func (c *gobServerCodec) ReadRequestHeader(r *Request) error {
return c.dec.Decode(r)
}
-func (c *gobServerCodec) ReadRequestBody(body interface{}) os.Error {
+func (c *gobServerCodec) ReadRequestBody(body interface{}) error {
return c.dec.Decode(body)
}
-func (c *gobServerCodec) WriteResponse(r *Response, body interface{}) (err os.Error) {
+func (c *gobServerCodec) WriteResponse(r *Response, body interface{}) (err error) {
if err = c.enc.Encode(r); err != nil {
return
}
return c.encBuf.Flush()
}
-func (c *gobServerCodec) Close() os.Error {
+func (c *gobServerCodec) Close() error {
return c.rwc.Close()
}
for {
service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec)
if err != nil {
- if err != os.EOF {
+ if err != io.EOF {
log.Println("rpc:", err)
}
if !keepReading {
}
// send a response if we actually managed to read a header.
if req != nil {
- server.sendResponse(sending, req, invalidRequest, codec, err.String())
+ server.sendResponse(sending, req, invalidRequest, codec, err.Error())
server.freeRequest(req)
}
continue
// ServeRequest is like ServeCodec but synchronously serves a single request.
// It does not close the codec upon completion.
-func (server *Server) ServeRequest(codec ServerCodec) os.Error {
+func (server *Server) ServeRequest(codec ServerCodec) error {
sending := new(sync.Mutex)
service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec)
if err != nil {
}
// send a response if we actually managed to read a header.
if req != nil {
- server.sendResponse(sending, req, invalidRequest, codec, err.String())
+ server.sendResponse(sending, req, invalidRequest, codec, err.Error())
server.freeRequest(req)
}
return err
server.respLock.Unlock()
}
-func (server *Server) readRequest(codec ServerCodec) (service *service, mtype *methodType, req *Request, argv, replyv reflect.Value, keepReading bool, err os.Error) {
+func (server *Server) readRequest(codec ServerCodec) (service *service, mtype *methodType, req *Request, argv, replyv reflect.Value, keepReading bool, err error) {
service, mtype, req, keepReading, err = server.readRequestHeader(codec)
if err != nil {
if !keepReading {
return
}
-func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mtype *methodType, req *Request, keepReading bool, err os.Error) {
+func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mtype *methodType, req *Request, keepReading bool, err error) {
// Grab the request header.
req = server.getRequest()
err = codec.ReadRequestHeader(req)
if err != nil {
req = nil
- if err == os.EOF || err == io.ErrUnexpectedEOF {
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
- err = os.NewError("rpc: server cannot decode request: " + err.String())
+ err = errors.New("rpc: server cannot decode request: " + err.Error())
return
}
serviceMethod := strings.Split(req.ServiceMethod, ".")
if len(serviceMethod) != 2 {
- err = os.NewError("rpc: service/method request ill-formed: " + req.ServiceMethod)
+ err = errors.New("rpc: service/method request ill-formed: " + req.ServiceMethod)
return
}
// Look up the request.
service = server.serviceMap[serviceMethod[0]]
server.mu.Unlock()
if service == nil {
- err = os.NewError("rpc: can't find service " + req.ServiceMethod)
+ err = errors.New("rpc: can't find service " + req.ServiceMethod)
return
}
mtype = service.method[serviceMethod[1]]
if mtype == nil {
- err = os.NewError("rpc: can't find method " + req.ServiceMethod)
+ err = errors.New("rpc: can't find method " + req.ServiceMethod)
}
return
}
for {
conn, err := lis.Accept()
if err != nil {
- log.Fatal("rpc.Serve: accept:", err.String()) // TODO(r): exit?
+ log.Fatal("rpc.Serve: accept:", err.Error()) // TODO(r): exit?
}
go server.ServeConn(conn)
}
}
// Register publishes the receiver's methods in the DefaultServer.
-func Register(rcvr interface{}) os.Error { return DefaultServer.Register(rcvr) }
+func Register(rcvr interface{}) error { return DefaultServer.Register(rcvr) }
// RegisterName is like Register but uses the provided name for the type
// instead of the receiver's concrete type.
-func RegisterName(name string, rcvr interface{}) os.Error {
+func RegisterName(name string, rcvr interface{}) error {
return DefaultServer.RegisterName(name, rcvr)
}
// connection. ReadRequestBody may be called with a nil
// argument to force the body of the request to be read and discarded.
type ServerCodec interface {
- ReadRequestHeader(*Request) os.Error
- ReadRequestBody(interface{}) os.Error
- WriteResponse(*Response, interface{}) os.Error
+ ReadRequestHeader(*Request) error
+ ReadRequestBody(interface{}) error
+ WriteResponse(*Response, interface{}) error
- Close() os.Error
+ Close() error
}
// ServeConn runs the DefaultServer on a single connection.
// ServeRequest is like ServeCodec but synchronously serves a single request.
// It does not close the codec upon completion.
-func ServeRequest(codec ServerCodec) os.Error {
+func ServeRequest(codec ServerCodec) error {
return DefaultServer.ServeRequest(codec)
}
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
- log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.String())
+ log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
return
}
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
package rpc
import (
+ "errors"
"fmt"
"http/httptest"
"io"
"log"
"net"
- "os"
"runtime"
"strings"
"sync"
// Some of Arith's methods have value args, some have pointer args. That's deliberate.
-func (t *Arith) Add(args Args, reply *Reply) os.Error {
+func (t *Arith) Add(args Args, reply *Reply) error {
reply.C = args.A + args.B
return nil
}
-func (t *Arith) Mul(args *Args, reply *Reply) os.Error {
+func (t *Arith) Mul(args *Args, reply *Reply) error {
reply.C = args.A * args.B
return nil
}
-func (t *Arith) Div(args Args, reply *Reply) os.Error {
+func (t *Arith) Div(args Args, reply *Reply) error {
if args.B == 0 {
- return os.NewError("divide by zero")
+ return errors.New("divide by zero")
}
reply.C = args.A / args.B
return nil
}
-func (t *Arith) String(args *Args, reply *string) os.Error {
+func (t *Arith) String(args *Args, reply *string) error {
*reply = fmt.Sprintf("%d+%d=%d", args.A, args.B, args.A+args.B)
return nil
}
-func (t *Arith) Scan(args string, reply *Reply) (err os.Error) {
+func (t *Arith) Scan(args string, reply *Reply) (err error) {
_, err = fmt.Sscan(args, &reply.C)
return
}
-func (t *Arith) Error(args *Args, reply *Reply) os.Error {
+func (t *Arith) Error(args *Args, reply *Reply) error {
panic("ERROR")
}
reply := new(Reply)
err = client.Call("Arith.Add", args, reply)
if err != nil {
- t.Errorf("Add: expected no error but got string %q", err.String())
+ t.Errorf("Add: expected no error but got string %q", err.Error())
}
if reply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
// expect an error
if err == nil {
t.Error("BadOperation: expected error")
- } else if !strings.HasPrefix(err.String(), "rpc: can't find method ") {
+ } else if !strings.HasPrefix(err.Error(), "rpc: can't find method ") {
t.Errorf("BadOperation: expected can't find method error; got %q", err)
}
err = client.Call("Arith.Unknown", args, reply)
if err == nil {
t.Error("expected error calling unknown service")
- } else if strings.Index(err.String(), "method") < 0 {
+ } else if strings.Index(err.Error(), "method") < 0 {
t.Error("expected error about method; got", err)
}
addCall = <-addCall.Done
if addCall.Error != nil {
- t.Errorf("Add: expected no error but got string %q", addCall.Error.String())
+ t.Errorf("Add: expected no error but got string %q", addCall.Error.Error())
}
if addReply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", addReply.C, args.A+args.B)
mulCall = <-mulCall.Done
if mulCall.Error != nil {
- t.Errorf("Mul: expected no error but got string %q", mulCall.Error.String())
+ t.Errorf("Mul: expected no error but got string %q", mulCall.Error.Error())
}
if mulReply.C != args.A*args.B {
t.Errorf("Mul: expected %d got %d", mulReply.C, args.A*args.B)
// expect an error: zero divide
if err == nil {
t.Error("Div: expected error")
- } else if err.String() != "divide by zero" {
+ } else if err.Error() != "divide by zero" {
t.Error("Div: expected divide by zero error; got", err)
}
err = client.Call("Arith.Add", reply, reply) // args, reply would be the correct thing to use
if err == nil {
t.Error("expected error calling Arith.Add with wrong arg type")
- } else if strings.Index(err.String(), "type") < 0 {
+ } else if strings.Index(err.Error(), "type") < 0 {
t.Error("expected error about type; got", err)
}
reply = new(Reply)
err = client.Call("Arith.Scan", &str, reply)
if err != nil {
- t.Errorf("Scan: expected no error but got string %q", err.String())
+ t.Errorf("Scan: expected no error but got string %q", err.Error())
} else if reply.C != Val {
t.Errorf("Scan: expected %d got %d", Val, reply.C)
}
str = ""
err = client.Call("Arith.String", args, &str)
if err != nil {
- t.Errorf("String: expected no error but got string %q", err.String())
+ t.Errorf("String: expected no error but got string %q", err.Error())
}
expect := fmt.Sprintf("%d+%d=%d", args.A, args.B, args.A+args.B)
if str != expect {
reply = new(Reply)
err = client.Call("Arith.Mul", args, reply)
if err != nil {
- t.Errorf("Mul: expected no error but got string %q", err.String())
+ t.Errorf("Mul: expected no error but got string %q", err.Error())
}
if reply.C != args.A*args.B {
t.Errorf("Mul: expected %d got %d", reply.C, args.A*args.B)
func testHTTPRPC(t *testing.T, path string) {
var client *Client
- var err os.Error
+ var err error
if path == "" {
client, err = DialHTTP("tcp", httpServerAddr)
} else {
reply := new(Reply)
err = client.Call("Arith.Add", args, reply)
if err != nil {
- t.Errorf("Add: expected no error but got string %q", err.String())
+ t.Errorf("Add: expected no error but got string %q", err.Error())
}
if reply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
serviceMethod string
args *Args
reply *Reply
- err os.Error
+ err error
}
-func (codec *CodecEmulator) Call(serviceMethod string, args *Args, reply *Reply) os.Error {
+func (codec *CodecEmulator) Call(serviceMethod string, args *Args, reply *Reply) error {
codec.serviceMethod = serviceMethod
codec.args = args
codec.reply = reply
codec.err = nil
- var serverError os.Error
+ var serverError error
if codec.server == nil {
serverError = ServeRequest(codec)
} else {
return codec.err
}
-func (codec *CodecEmulator) ReadRequestHeader(req *Request) os.Error {
+func (codec *CodecEmulator) ReadRequestHeader(req *Request) error {
req.ServiceMethod = codec.serviceMethod
req.Seq = 0
return nil
}
-func (codec *CodecEmulator) ReadRequestBody(argv interface{}) os.Error {
+func (codec *CodecEmulator) ReadRequestBody(argv interface{}) error {
if codec.args == nil {
return io.ErrUnexpectedEOF
}
return nil
}
-func (codec *CodecEmulator) WriteResponse(resp *Response, reply interface{}) os.Error {
+func (codec *CodecEmulator) WriteResponse(resp *Response, reply interface{}) error {
if resp.Error != "" {
- codec.err = os.NewError(resp.Error)
+ codec.err = errors.New(resp.Error)
} else {
*codec.reply = *(reply.(*Reply))
}
return nil
}
-func (codec *CodecEmulator) Close() os.Error {
+func (codec *CodecEmulator) Close() error {
return nil
}
reply := new(Reply)
err := client.Call("Arith.Add", args, reply)
if err != nil {
- t.Errorf("Add: expected no error but got string %q", err.String())
+ t.Errorf("Add: expected no error but got string %q", err.Error())
}
if reply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
type ReplyNotPublic int
type local struct{}
-func (t *ReplyNotPointer) ReplyNotPointer(args *Args, reply Reply) os.Error {
+func (t *ReplyNotPointer) ReplyNotPointer(args *Args, reply Reply) error {
return nil
}
-func (t *ArgNotPublic) ArgNotPublic(args *local, reply *Reply) os.Error {
+func (t *ArgNotPublic) ArgNotPublic(args *local, reply *Reply) error {
return nil
}
-func (t *ReplyNotPublic) ReplyNotPublic(args *Args, reply *local) os.Error {
+func (t *ReplyNotPublic) ReplyNotPublic(args *Args, reply *local) error {
return nil
}
type WriteFailCodec int
-func (WriteFailCodec) WriteRequest(*Request, interface{}) os.Error {
+func (WriteFailCodec) WriteRequest(*Request, interface{}) error {
// the panic caused by this error used to not unlock a lock.
- return os.NewError("fail")
+ return errors.New("fail")
}
-func (WriteFailCodec) ReadResponseHeader(*Response) os.Error {
+func (WriteFailCodec) ReadResponseHeader(*Response) error {
time.Sleep(120e9)
panic("unreachable")
}
-func (WriteFailCodec) ReadResponseBody(interface{}) os.Error {
+func (WriteFailCodec) ReadResponseBody(interface{}) error {
time.Sleep(120e9)
panic("unreachable")
}
-func (WriteFailCodec) Close() os.Error {
+func (WriteFailCodec) Close() error {
return nil
}
client.Call("Arith.Add", args, reply)
}
-func dialDirect() (*Client, os.Error) {
+func dialDirect() (*Client, error) {
return Dial("tcp", serverAddr)
}
-func dialHTTP() (*Client, os.Error) {
+func dialHTTP() (*Client, error) {
return DialHTTP("tcp", httpServerAddr)
}
-func countMallocs(dial func() (*Client, os.Error), t *testing.T) uint64 {
+func countMallocs(dial func() (*Client, error), t *testing.T) uint64 {
once.Do(startServer)
client, err := dial()
if err != nil {
for i := 0; i < count; i++ {
err := client.Call("Arith.Add", args, reply)
if err != nil {
- t.Errorf("Add: expected no error but got string %q", err.String())
+ t.Errorf("Add: expected no error but got string %q", err.Error())
}
if reply.C != args.A+args.B {
t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B)
type writeCrasher struct{}
-func (writeCrasher) Close() os.Error {
+func (writeCrasher) Close() error {
return nil
}
-func (writeCrasher) Read(p []byte) (int, os.Error) {
- return 0, os.EOF
+func (writeCrasher) Read(p []byte) (int, error) {
+ return 0, io.EOF
}
-func (writeCrasher) Write(p []byte) (int, os.Error) {
- return 0, os.NewError("fake write failure")
+func (writeCrasher) Write(p []byte) (int, error) {
+ return 0, errors.New("fake write failure")
}
func TestClientWriteError(t *testing.T) {
if err == nil {
t.Fatal("expected error")
}
- if err.String() != "fake write failure" {
+ if err.Error() != "fake write failure" {
t.Error("unexpected value of error:", err)
}
}
-func benchmarkEndToEnd(dial func() (*Client, os.Error), b *testing.B) {
+func benchmarkEndToEnd(dial func() (*Client, error), b *testing.B) {
b.StopTimer()
once.Do(startServer)
client, err := dial()
for atomic.AddInt32(&N, -1) >= 0 {
err = client.Call("Arith.Add", args, reply)
if err != nil {
- fmt.Printf("Add: expected no error but got string %q", err.String())
+ fmt.Printf("Add: expected no error but got string %q", err.Error())
panic("rpc error")
}
if reply.C != args.A+args.B {
wg.Wait()
}
-func benchmarkEndToEndAsync(dial func() (*Client, os.Error), b *testing.B) {
+func benchmarkEndToEndAsync(dial func() (*Client, error), b *testing.B) {
const MaxConcurrentCalls = 100
b.StopTimer()
once.Do(startServer)
// The Error interface identifies a run time error.
type Error interface {
- String() string
+ error
// RuntimeError is a no-op function but
// serves to distinguish types that are runtime
- // errors from ordinary os.Errors: a type is a
+ // errors from ordinary errors: a type is a
// runtime error if it has a RuntimeError method.
RuntimeError()
}
func (*TypeAssertionError) RuntimeError() {}
-func (e *TypeAssertionError) String() string {
+func (e *TypeAssertionError) Error() string {
inter := e.interfaceString
if inter == "" {
inter = "interface"
func (e errorString) RuntimeError() {}
-func (e errorString) String() string {
+func (e errorString) Error() string {
return "runtime error: " + string(e)
}
print("nil")
case stringer:
print(v.String())
+ case error:
+ print(v.Error())
case int:
print(v)
case string:
"bufio"
"fmt"
"io"
- "os"
"runtime"
"sync"
)
// WriteHeapProfile writes a pprof-formatted heap profile to w.
// If a write to w returns an error, WriteHeapProfile returns that error.
// Otherwise, WriteHeapProfile returns nil.
-func WriteHeapProfile(w io.Writer) os.Error {
+func WriteHeapProfile(w io.Writer) error {
// Find out how many records there are (MemProfile(nil, false)),
// allocate that many records, and get the data.
// There's a race—more records might be added between
// StartCPUProfile enables CPU profiling for the current process.
// While profiling, the profile will be buffered and written to w.
// StartCPUProfile returns an error if profiling is already enabled.
-func StartCPUProfile(w io.Writer) os.Error {
+func StartCPUProfile(w io.Writer) error {
// The runtime routines allow a variable profiling rate,
// but in practice operating systems cannot trigger signals
// at more than about 500 Hz, and our processing of the
s.lastCharLen = 0
return EOF
}
- if err != os.EOF {
- s.error(err.String())
+ if err != io.EOF {
+ s.error(err.Error())
}
// If err == EOF, we won't be getting more
// bytes; break to avoid infinite loop. If
import (
"bytes"
"fmt"
- "os"
+ "io"
"strings"
"testing"
"utf8"
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
}
package smtp
-import (
- "os"
-)
+import "errors"
// Auth is implemented by an SMTP authentication mechanism.
type Auth interface {
// and optionally data to include in the initial AUTH message
// sent to the server. It can return proto == "" to indicate
// that the authentication should be skipped.
- // If it returns a non-nil os.Error, the SMTP client aborts
+ // If it returns a non-nil error, the SMTP client aborts
// the authentication attempt and closes the connection.
- Start(server *ServerInfo) (proto string, toServer []byte, err os.Error)
+ Start(server *ServerInfo) (proto string, toServer []byte, err error)
// Next continues the authentication. The server has just sent
// the fromServer data. If more is true, the server expects a
// response, which Next should return as toServer; otherwise
// Next should return toServer == nil.
- // If Next returns a non-nil os.Error, the SMTP client aborts
+ // If Next returns a non-nil error, the SMTP client aborts
// the authentication attempt and closes the connection.
- Next(fromServer []byte, more bool) (toServer []byte, err os.Error)
+ Next(fromServer []byte, more bool) (toServer []byte, err error)
}
// ServerInfo records information about an SMTP server.
return &plainAuth{identity, username, password, host}
}
-func (a *plainAuth) Start(server *ServerInfo) (string, []byte, os.Error) {
+func (a *plainAuth) Start(server *ServerInfo) (string, []byte, error) {
if !server.TLS {
- return "", nil, os.NewError("unencrypted connection")
+ return "", nil, errors.New("unencrypted connection")
}
if server.Name != a.host {
- return "", nil, os.NewError("wrong host name")
+ return "", nil, errors.New("wrong host name")
}
resp := []byte(a.identity + "\x00" + a.username + "\x00" + a.password)
return "PLAIN", resp, nil
}
-func (a *plainAuth) Next(fromServer []byte, more bool) ([]byte, os.Error) {
+func (a *plainAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
// We've already sent everything.
- return nil, os.NewError("unexpected server challenge")
+ return nil, errors.New("unexpected server challenge")
}
return nil, nil
}
"crypto/tls"
"encoding/base64"
"io"
- "os"
"net"
"net/textproto"
"strings"
}
// Dial returns a new Client connected to an SMTP server at addr.
-func Dial(addr string) (*Client, os.Error) {
+func Dial(addr string) (*Client, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
// NewClient returns a new Client using an existing connection and host as a
// server name to be used when authenticating.
-func NewClient(conn net.Conn, host string) (*Client, os.Error) {
+func NewClient(conn net.Conn, host string) (*Client, error) {
text := textproto.NewConn(conn)
_, msg, err := text.ReadResponse(220)
if err != nil {
}
// cmd is a convenience function that sends a command and returns the response
-func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, os.Error) {
+func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {
id, err := c.Text.Cmd(format, args...)
if err != nil {
return 0, "", err
// helo sends the HELO greeting to the server. It should be used only when the
// server does not support ehlo.
-func (c *Client) helo() os.Error {
+func (c *Client) helo() error {
c.ext = nil
_, _, err := c.cmd(250, "HELO localhost")
return err
// ehlo sends the EHLO (extended hello) greeting to the server. It
// should be the preferred greeting for servers that support it.
-func (c *Client) ehlo() os.Error {
+func (c *Client) ehlo() error {
_, msg, err := c.cmd(250, "EHLO localhost")
if err != nil {
return err
// StartTLS sends the STARTTLS command and encrypts all further communication.
// Only servers that advertise the STARTTLS extension support this function.
-func (c *Client) StartTLS(config *tls.Config) os.Error {
+func (c *Client) StartTLS(config *tls.Config) error {
_, _, err := c.cmd(220, "STARTTLS")
if err != nil {
return err
// If Verify returns nil, the address is valid. A non-nil return
// does not necessarily indicate an invalid address. Many servers
// will not verify addresses for security reasons.
-func (c *Client) Verify(addr string) os.Error {
+func (c *Client) Verify(addr string) error {
_, _, err := c.cmd(250, "VRFY %s", addr)
return err
}
// Auth authenticates a client using the provided authentication mechanism.
// A failed authentication closes the connection.
// Only servers that advertise the AUTH extension support this function.
-func (c *Client) Auth(a Auth) os.Error {
+func (c *Client) Auth(a Auth) error {
encoding := base64.StdEncoding
mech, resp, err := a.Start(&ServerInfo{c.serverName, c.tls, c.auth})
if err != nil {
// If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME
// parameter.
// This initiates a mail transaction and is followed by one or more Rcpt calls.
-func (c *Client) Mail(from string) os.Error {
+func (c *Client) Mail(from string) error {
cmdStr := "MAIL FROM:<%s>"
if c.ext != nil {
if _, ok := c.ext["8BITMIME"]; ok {
// Rcpt issues a RCPT command to the server using the provided email address.
// A call to Rcpt must be preceded by a call to Mail and may be followed by
// a Data call or another Rcpt call.
-func (c *Client) Rcpt(to string) os.Error {
+func (c *Client) Rcpt(to string) error {
_, _, err := c.cmd(25, "RCPT TO:<%s>", to)
return err
}
io.WriteCloser
}
-func (d *dataCloser) Close() os.Error {
+func (d *dataCloser) Close() error {
d.WriteCloser.Close()
_, _, err := d.c.Text.ReadResponse(250)
return err
// can be used to write the data. The caller should close the writer
// before calling any more methods on c.
// A call to Data must be preceded by one or more calls to Rcpt.
-func (c *Client) Data() (io.WriteCloser, os.Error) {
+func (c *Client) Data() (io.WriteCloser, error) {
_, _, err := c.cmd(354, "DATA")
if err != nil {
return nil, err
// SendMail connects to the server at addr, switches to TLS if possible,
// authenticates with mechanism a if possible, and then sends an email from
// address from, to addresses to, with message msg.
-func SendMail(addr string, a Auth, from string, to []string, msg []byte) os.Error {
+func SendMail(addr string, a Auth, from string, to []string, msg []byte) error {
c, err := Dial(addr)
if err != nil {
return err
// Reset sends the RSET command to the server, aborting the current mail
// transaction.
-func (c *Client) Reset() os.Error {
+func (c *Client) Reset() error {
_, _, err := c.cmd(250, "RSET")
return err
}
// Quit sends the QUIT command and closes the connection to the server.
-func (c *Client) Quit() os.Error {
+func (c *Client) Quit() error {
_, _, err := c.cmd(221, "QUIT")
if err != nil {
return err
"bytes"
"io"
"net/textproto"
- "os"
"strings"
"testing"
)
io.ReadWriter
}
-func (f faker) Close() os.Error {
+func (f faker) Close() error {
return nil
}
package strconv
-import "os"
-
// Atob returns the boolean value represented by the string.
// It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
// Any other value returns an error.
-func Atob(str string) (value bool, err os.Error) {
+func Atob(str string) (value bool, err error) {
switch str {
case "1", "t", "T", "true", "TRUE", "True":
return true, nil
package strconv_test
import (
- "os"
. "strconv"
"testing"
)
type atobTest struct {
in string
out bool
- err os.Error
+ err error
}
var atobtests = []atobTest{
t.Errorf("%s: expected %s but got nil", test.in, test.err)
} else {
// NumError assertion must succeed; it's the only thing we return.
- if test.err != e.(*NumError).Error {
+ if test.err != e.(*NumError).Err {
t.Errorf("%s: expected %s but got %s", test.in, test.err, e)
}
}
// 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
// 3) Multiply by 2^precision and round to get mantissa.
-import (
- "math"
- "os"
-)
+import "math"
var optimize = true // can change for testing
// If s is syntactically well-formed but is more than 1/2 ULP
// away from the largest floating point number of the given size,
// Atof32 returns f = ±Inf, err.Error = ErrRange.
-func Atof32(s string) (f float32, err os.Error) {
+func Atof32(s string) (f float32, err error) {
if val, ok := special(s); ok {
return float32(val), nil
}
// Atof64 converts the string s to a 64-bit floating-point number.
// Except for the type of its result, its definition is the same as that
// of Atof32.
-func Atof64(s string) (f float64, err os.Error) {
+func Atof64(s string) (f float64, err error) {
if val, ok := special(s); ok {
return val, nil
}
// AtofN converts the string s to a 64-bit floating-point number,
// but it rounds the result assuming that it will be stored in a value
// of n bits (32 or 64).
-func AtofN(s string, n int) (f float64, err os.Error) {
+func AtofN(s string, n int) (f float64, err error) {
if n == 32 {
f1, err1 := Atof32(s)
return float64(f1), err1
package strconv_test
import (
- "os"
"reflect"
. "strconv"
"testing"
type atofTest struct {
in string
out string
- err os.Error
+ err error
}
var atoftests = []atofTest{
package strconv
-import "os"
+import "errors"
// ErrRange indicates that a value is out of range for the target type.
-var ErrRange = os.NewError("value out of range")
+var ErrRange = errors.New("value out of range")
// ErrSyntax indicates that a value does not have the right syntax for the target type.
-var ErrSyntax = os.NewError("invalid syntax")
+var ErrSyntax = errors.New("invalid syntax")
// A NumError records a failed conversion.
type NumError struct {
- Num string // the input
- Error os.Error // the reason the conversion failed (ErrRange, ErrSyntax)
+ Num string // the input
+ Err error // the reason the conversion failed (ErrRange, ErrSyntax)
}
-func (e *NumError) String() string { return `parsing "` + e.Num + `": ` + e.Error.String() }
+func (e *NumError) Error() string { return `parsing "` + e.Num + `": ` + e.Err.Error() }
func computeIntsize() uint {
siz := uint(8)
// and include err.Num = s. If s is empty or contains invalid
// digits, err.Error = ErrSyntax; if the value corresponding
// to s cannot be represented by a uint64, err.Error = ErrRange.
-func Btoui64(s string, b int) (n uint64, err os.Error) {
+func Btoui64(s string, b int) (n uint64, err error) {
var cutoff uint64
s0 := s
}
default:
- err = os.NewError("invalid base " + Itoa(b))
+ err = errors.New("invalid base " + Itoa(b))
goto Error
}
//
// Atoui64 returns err.Error = ErrSyntax if s is empty or contains invalid digits.
// It returns err.Error = ErrRange if s cannot be represented by a uint64.
-func Atoui64(s string) (n uint64, err os.Error) {
+func Atoui64(s string) (n uint64, err error) {
return Btoui64(s, 10)
}
// Btoi64 is like Btoui64 but allows signed numbers and
// returns its result in an int64.
-func Btoi64(s string, base int) (i int64, err os.Error) {
+func Btoi64(s string, base int) (i int64, err error) {
// Empty string bad.
if len(s) == 0 {
return 0, &NumError{s, ErrSyntax}
// Convert unsigned and check range.
var un uint64
un, err = Btoui64(s, base)
- if err != nil && err.(*NumError).Error != ErrRange {
+ if err != nil && err.(*NumError).Err != ErrRange {
err.(*NumError).Num = s0
return 0, err
}
// Atoi64 is like Atoui64 but allows signed numbers and
// returns its result in an int64.
-func Atoi64(s string) (i int64, err os.Error) { return Btoi64(s, 10) }
+func Atoi64(s string) (i int64, err error) { return Btoi64(s, 10) }
// Atoui is like Atoui64 but returns its result as a uint.
-func Atoui(s string) (i uint, err os.Error) {
+func Atoui(s string) (i uint, err error) {
i1, e1 := Atoui64(s)
- if e1 != nil && e1.(*NumError).Error != ErrRange {
+ if e1 != nil && e1.(*NumError).Err != ErrRange {
return 0, e1
}
i = uint(i1)
}
// Atoi is like Atoi64 but returns its result as an int.
-func Atoi(s string) (i int, err os.Error) {
+func Atoi(s string) (i int, err error) {
i1, e1 := Atoi64(s)
- if e1 != nil && e1.(*NumError).Error != ErrRange {
+ if e1 != nil && e1.(*NumError).Err != ErrRange {
return 0, e1
}
i = int(i1)
package strconv_test
import (
- "os"
"reflect"
. "strconv"
"testing"
type atoui64Test struct {
in string
out uint64
- err os.Error
+ err error
}
var atoui64tests = []atoui64Test{
type atoi64Test struct {
in string
out int64
- err os.Error
+ err error
}
var atoi64tests = []atoi64Test{
type atoui32Test struct {
in string
out uint32
- err os.Error
+ err error
}
var atoui32tests = []atoui32Test{
type atoi32Test struct {
in string
out int32
- err os.Error
+ err error
}
var atoi32tests = []atoi32Test{
import (
"bufio"
"fmt"
+ "io"
"os"
"strconv"
"strings"
lineno := 0
for {
line, err2 := b.ReadString('\n')
- if err2 == os.EOF {
+ if err2 == io.EOF {
break
}
if err2 != nil {
- t.Fatal("testfp: read testfp.txt: " + err2.String())
+ t.Fatal("testfp: read testfp.txt: " + err2.Error())
}
line = line[0 : len(line)-1]
lineno++
import (
"bytes"
- "os"
"strings"
"unicode"
"utf8"
// If set to a single quote, it permits the sequence \' and disallows unescaped '.
// If set to a double quote, it permits \" and disallows unescaped ".
// If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.
-func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err os.Error) {
+func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) {
// easy cases
switch c := s[0]; {
case c == quote && (quote == '\'' || quote == '"'):
// that s quotes. (If s is single-quoted, it would be a Go
// character literal; Unquote returns the corresponding
// one-character string.)
-func Unquote(s string) (t string, err os.Error) {
+func Unquote(s string) (t string, err error) {
n := len(s)
if n < 2 {
return "", ErrSyntax
package strings
import (
- "os"
+ "errors"
+ "io"
"utf8"
)
return len(r.s) - r.i
}
-func (r *Reader) Read(b []byte) (n int, err os.Error) {
+func (r *Reader) Read(b []byte) (n int, err error) {
if r.i >= len(r.s) {
- return 0, os.EOF
+ return 0, io.EOF
}
n = copy(b, r.s[r.i:])
r.i += n
return
}
-func (r *Reader) ReadByte() (b byte, err os.Error) {
+func (r *Reader) ReadByte() (b byte, err error) {
if r.i >= len(r.s) {
- return 0, os.EOF
+ return 0, io.EOF
}
b = r.s[r.i]
r.i++
// UnreadByte moves the reading position back by one byte.
// It is an error to call UnreadByte if nothing has been
// read yet.
-func (r *Reader) UnreadByte() os.Error {
+func (r *Reader) UnreadByte() error {
if r.i <= 0 {
- return os.NewError("strings.Reader: at beginning of string")
+ return errors.New("strings.Reader: at beginning of string")
}
r.i--
r.prevRune = -1
// 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 (r *Reader) ReadRune() (ch rune, size int, err os.Error) {
+func (r *Reader) ReadRune() (ch rune, size int, err error) {
if r.i >= len(r.s) {
- return 0, 0, os.EOF
+ return 0, 0, io.EOF
}
r.prevRune = r.i
if c := r.s[r.i]; c < utf8.RuneSelf {
// UnreadRune causes the next call to ReadRune to return the same rune
// as the previous call to ReadRune.
// The last method called on r must have been ReadRune.
-func (r *Reader) UnreadRune() os.Error {
+func (r *Reader) UnreadRune() error {
if r.prevRune < 0 {
- return os.NewError("strings.Reader: previous operation was not ReadRune")
+ return errors.New("strings.Reader: previous operation was not ReadRune")
}
r.i = r.prevRune
r.prevRune = -1
package strings
-import (
- "io"
- "os"
-)
+import "io"
// A Replacer replaces a list of strings with replacements.
type Replacer struct {
// replacer is the interface that a replacement algorithm needs to implement.
type replacer interface {
Replace(s string) string
- WriteString(w io.Writer, s string) (n int, err os.Error)
+ WriteString(w io.Writer, s string) (n int, err error)
}
// byteBitmap represents bytes which are sought for replacement.
}
// WriteString writes s to w with all replacements performed.
-func (r *Replacer) WriteString(w io.Writer, s string) (n int, err os.Error) {
+func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error) {
return r.r.WriteString(w, s)
}
b []byte
}
-func (w *appendSliceWriter) Write(p []byte) (int, os.Error) {
+func (w *appendSliceWriter) Write(p []byte) (int, error) {
w.b = append(w.b, p...)
return len(p), nil
}
return string(w.b)
}
-func (r *genericReplacer) WriteString(w io.Writer, s string) (n int, err os.Error) {
+func (r *genericReplacer) WriteString(w io.Writer, s string) (n int, err error) {
lastEmpty := false // the last replacement was of the empty string
Input:
// TODO(bradfitz): optimized version
return string(buf)
}
-func (r *byteReplacer) WriteString(w io.Writer, s string) (n int, err os.Error) {
+func (r *byteReplacer) WriteString(w io.Writer, s string) (n int, err error) {
// TODO(bradfitz): use io.WriteString with slices of s, avoiding allocation.
bufsize := 32 << 10
if len(s) < bufsize {
// WriteString maintains one buffer that's at most 32KB. The bytes in
// s are enumerated and the buffer is filled. If it reaches its
// capacity or a byte has a replacement, the buffer is flushed to w.
-func (r *byteStringReplacer) WriteString(w io.Writer, s string) (n int, err os.Error) {
+func (r *byteStringReplacer) WriteString(w io.Writer, s string) (n int, err error) {
// TODO(bradfitz): use io.WriteString with slices of s instead.
bufsize := 32 << 10
if len(s) < bufsize {
type devNull int
-func (devNull) Write(p []byte) (int, os.Error) {
+func (devNull) Write(p []byte) (int, error) {
return len(p), nil
}
import (
"bytes"
- "os"
+ "io"
"reflect"
"strconv"
. "strings"
var res bytes.Buffer
for {
b, e := reader.ReadByte()
- if e == os.EOF {
+ if e == io.EOF {
break
}
if e != nil {
res := ""
for {
r, z, e := reader.ReadRune()
- if e == os.EOF {
+ if e == io.EOF {
break
}
if e != nil {
}
type serverConn interface {
- writeBytes(p Priority, prefix string, b []byte) (int, os.Error)
- writeString(p Priority, prefix string, s string) (int, os.Error)
- close() os.Error
+ writeBytes(p Priority, prefix string, b []byte) (int, error)
+ writeString(p Priority, prefix string, s string) (int, error)
+ close() error
}
type netConn struct {
// New establishes a new connection to the system log daemon.
// Each write to the returned writer sends a log message with
// the given priority and prefix.
-func New(priority Priority, prefix string) (w *Writer, err os.Error) {
+func New(priority Priority, prefix string) (w *Writer, err error) {
return Dial("", "", priority, prefix)
}
// to address raddr on the network net.
// Each write to the returned writer sends a log message with
// the given priority and prefix.
-func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, err os.Error) {
+func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, err error) {
if prefix == "" {
prefix = os.Args[0]
}
}
// Write sends a log message to the syslog daemon.
-func (w *Writer) Write(b []byte) (int, os.Error) {
+func (w *Writer) Write(b []byte) (int, error) {
if w.priority > LOG_DEBUG || w.priority < LOG_EMERG {
return 0, os.EINVAL
}
return w.conn.writeBytes(w.priority, w.prefix, b)
}
-func (w *Writer) writeString(p Priority, s string) (int, os.Error) {
+func (w *Writer) writeString(p Priority, s string) (int, error) {
return w.conn.writeString(p, w.prefix, s)
}
-func (w *Writer) Close() os.Error { return w.conn.close() }
+func (w *Writer) Close() error { return w.conn.close() }
// Emerg logs a message using the LOG_EMERG priority.
-func (w *Writer) Emerg(m string) (err os.Error) {
+func (w *Writer) Emerg(m string) (err error) {
_, err = w.writeString(LOG_EMERG, m)
return err
}
// Crit logs a message using the LOG_CRIT priority.
-func (w *Writer) Crit(m string) (err os.Error) {
+func (w *Writer) Crit(m string) (err error) {
_, err = w.writeString(LOG_CRIT, m)
return err
}
// ERR logs a message using the LOG_ERR priority.
-func (w *Writer) Err(m string) (err os.Error) {
+func (w *Writer) Err(m string) (err error) {
_, err = w.writeString(LOG_ERR, m)
return err
}
// Warning logs a message using the LOG_WARNING priority.
-func (w *Writer) Warning(m string) (err os.Error) {
+func (w *Writer) Warning(m string) (err error) {
_, err = w.writeString(LOG_WARNING, m)
return err
}
// Notice logs a message using the LOG_NOTICE priority.
-func (w *Writer) Notice(m string) (err os.Error) {
+func (w *Writer) Notice(m string) (err error) {
_, err = w.writeString(LOG_NOTICE, m)
return err
}
// Info logs a message using the LOG_INFO priority.
-func (w *Writer) Info(m string) (err os.Error) {
+func (w *Writer) Info(m string) (err error) {
_, err = w.writeString(LOG_INFO, m)
return err
}
// Debug logs a message using the LOG_DEBUG priority.
-func (w *Writer) Debug(m string) (err os.Error) {
+func (w *Writer) Debug(m string) (err error) {
_, err = w.writeString(LOG_DEBUG, m)
return err
}
-func (n netConn) writeBytes(p Priority, prefix string, b []byte) (int, os.Error) {
+func (n netConn) writeBytes(p Priority, prefix string, b []byte) (int, error) {
return fmt.Fprintf(n.conn, "<%d>%s: %s\n", p, prefix, b)
}
-func (n netConn) writeString(p Priority, prefix string, s string) (int, os.Error) {
+func (n netConn) writeString(p Priority, prefix string, s string) (int, error) {
return fmt.Fprintf(n.conn, "<%d>%s: %s\n", p, prefix, s)
}
-func (n netConn) close() os.Error {
+func (n netConn) close() error {
return n.conn.Close()
}
package syslog
import (
+ "errors"
"net"
- "os"
)
// unixSyslog opens a connection to the syslog daemon running on the
// local machine using a Unix domain socket.
-func unixSyslog() (conn serverConn, err os.Error) {
+func unixSyslog() (conn serverConn, err error) {
logTypes := []string{"unixgram", "unix"}
logPaths := []string{"/dev/log", "/var/run/syslog"}
var raddr string
}
}
}
- return nil, os.NewError("Unix syslog delivery error")
+ return nil, errors.New("Unix syslog delivery error")
}
print("\n")
}
-// local error wrapper so we can distinguish os.Errors we want to return
+// local error wrapper so we can distinguish errors we want to return
// as errors from genuine panics (which we don't want to return as errors)
type osError struct {
- err os.Error
+ err error
}
func (b *Writer) write0(buf []byte) {
return len(*line)
}
-func handlePanic(err *os.Error) {
+func handlePanic(err *error) {
if e := recover(); e != nil {
*err = e.(osError).err // re-panics if it's not a local osError
}
// incomplete escape sequence at the end is simply considered
// complete for formatting purposes.
//
-func (b *Writer) Flush() (err os.Error) {
+func (b *Writer) Flush() (err error) {
defer b.reset() // even in the presence of errors
defer handlePanic(&err)
// The only errors returned are ones encountered
// while writing to the underlying output stream.
//
-func (b *Writer) Write(buf []byte) (n int, err os.Error) {
+func (b *Writer) Write(buf []byte) (n int, err error) {
defer handlePanic(&err)
// split text into cells
import (
"io"
- "os"
"testing"
)
func (b *buffer) clear() { b.a = b.a[0:0] }
-func (b *buffer) Write(buf []byte) (written int, err os.Error) {
+func (b *buffer) Write(buf []byte) (written int, err error) {
n := len(b.a)
m := len(buf)
if n+m <= cap(b.a) {
.Method
The result is the value of invoking the method with dot as the
receiver, dot.Method(). Such a method must have one return value (of
- any type) or two return values, the second of which is an os.Error.
+ any type) or two return values, the second of which is an error.
If it has two and the returned error is non-nil, execution terminates
and an error is returned to the caller as the value of Execute.
Method invocations may be chained and combined with fields and keys
command in the pipeline is the value of the pipeline.
The output of a command will be either one value or two values, the second of
-which has type os.Error. If that second value is present and evaluates to
+which has type error. If that second value is present and evaluates to
non-nil, execution terminates and the error is returned to the caller of
Execute.
import (
"fmt"
"io"
- "os"
"reflect"
"runtime"
"strings"
}
// error terminates processing.
-func (s *state) error(err os.Error) {
+func (s *state) error(err error) {
s.errorf("%s", err)
}
// errRecover is the handler that turns panics into returns from the top
// level of Parse.
-func errRecover(errp *os.Error) {
+func errRecover(errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
panic(e)
}
- *errp = e.(os.Error)
+ *errp = e.(error)
}
}
// Execute applies a parsed template to the specified data object,
// writing the output to wr.
-func (t *Template) Execute(wr io.Writer, data interface{}) (err os.Error) {
+func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
defer errRecover(&err)
value := reflect.ValueOf(data)
state := &state{
}
var (
- osErrorType = reflect.TypeOf((*os.Error)(nil)).Elem()
+ osErrorType = reflect.TypeOf((*error)(nil)).Elem()
fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
)
argv[i] = final
}
result := fun.Call(argv)
- // If we have an os.Error that is not nil, stop execution and return that error to the caller.
+ // If we have an error that is not nil, stop execution and return that error to the caller.
if len(result) == 2 && !result[1].IsNil() {
- s.errorf("error calling %s: %s", name, result[1].Interface().(os.Error))
+ s.errorf("error calling %s: %s", name, result[1].Interface().(error))
}
return result[0]
}
return keys
}
-// EPERM returns a value and an os.Error according to its argument.
-func (t *T) EPERM(error bool) (bool, os.Error) {
+// EPERM returns a value and an error according to its argument.
+func (t *T) EPERM(error bool) (bool, error) {
if error {
return true, os.EPERM
}
err = tmpl.Execute(b, tVal)
if err == nil {
t.Errorf("expected error; got none")
- } else if !strings.Contains(err.String(), os.EPERM.String()) {
+ } else if !strings.Contains(err.Error(), os.EPERM.Error()) {
if *debug {
fmt.Printf("test execute error: %s\n", err)
}
"bytes"
"fmt"
"io"
- "os"
"reflect"
"strings"
"unicode"
// FuncMap is the type of the map defining the mapping from names to functions.
// Each function must have either a single return value, or two return values of
-// which the second has type os.Error. If the second argument evaluates to non-nil
+// which the second has type error. If the second argument evaluates to non-nil
// during execution, execution terminates and Execute returns an error.
type FuncMap map[string]interface{}
// goodFunc checks that the function or method has the right result signature.
func goodFunc(typ reflect.Type) bool {
- // We allow functions with 1 result or 2 results where the second is an os.Error.
+ // We allow functions with 1 result or 2 results where the second is an error.
switch {
case typ.NumOut() == 1:
return true
// index returns the result of indexing its first argument by the following
// arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each
// indexed item must be a map, slice, or array.
-func index(item interface{}, indices ...interface{}) (interface{}, os.Error) {
+func index(item interface{}, indices ...interface{}) (interface{}, error) {
v := reflect.ValueOf(item)
for _, i := range indices {
index := reflect.ValueOf(i)
// Length
// length returns the length of the item, with an error if it has no defined length.
-func length(item interface{}) (int, os.Error) {
+func length(item interface{}) (int, error) {
v, isNil := indirect(reflect.ValueOf(item))
if isNil {
return 0, fmt.Errorf("len of nil pointer")
import (
"fmt"
"io/ioutil"
- "os"
"path/filepath"
)
// Functions and methods to parse a single template.
-// Must is a helper that wraps a call to a function returning (*Template, os.Error)
+// Must is a helper that wraps a call to a function returning (*Template, error)
// and panics if the error is non-nil. It is intended for use in variable initializations
// such as
// var t = template.Must(template.New("name").Parse("text"))
-func Must(t *Template, err os.Error) *Template {
+func Must(t *Template, err error) *Template {
if err != nil {
panic(err)
}
// ParseFile creates a new Template and parses the template definition from
// the named file. The template name is the base name of the file.
-func ParseFile(filename string) (*Template, os.Error) {
+func ParseFile(filename string) (*Template, error) {
t := New(filepath.Base(filename))
return t.ParseFile(filename)
}
// definition from the named file. The template name is the base name
// of the file. It also adds the template to the set. Function bindings are
// checked against those in the set.
-func parseFileInSet(filename string, set *Set) (*Template, os.Error) {
+func parseFileInSet(filename string, set *Set) (*Template, error) {
t := New(filepath.Base(filename))
return t.parseFileInSet(filename, set)
}
// ParseFile reads the template definition from a file and parses it to
// construct an internal representation of the template for execution.
// The returned template will be nil if an error occurs.
-func (t *Template) ParseFile(filename string) (*Template, os.Error) {
+func (t *Template) ParseFile(filename string) (*Template, error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
// are checked against those in the set and the template is added
// to the set.
// The returned template will be nil if an error occurs.
-func (t *Template) parseFileInSet(filename string, set *Set) (*Template, os.Error) {
+func (t *Template) parseFileInSet(filename string, set *Set) (*Template, error) {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
// Functions and methods to parse a set.
-// SetMust is a helper that wraps a call to a function returning (*Set, os.Error)
+// SetMust is a helper that wraps a call to a function returning (*Set, error)
// and panics if the error is non-nil. It is intended for use in variable initializations
// such as
// var s = template.SetMust(template.ParseSetFiles("file"))
-func SetMust(s *Set, err os.Error) *Set {
+func SetMust(s *Set, err error) *Set {
if err != nil {
panic(err)
}
// ParseFiles parses the named files into a set of named templates.
// Each file must be parseable by itself.
// If an error occurs, parsing stops and the returned set is nil.
-func (s *Set) ParseFiles(filenames ...string) (*Set, os.Error) {
+func (s *Set) ParseFiles(filenames ...string) (*Set, error) {
for _, filename := range filenames {
b, err := ioutil.ReadFile(filename)
if err != nil {
// ParseSetFiles creates a new Set and parses the set definition from the
// named files. Each file must be individually parseable.
-func ParseSetFiles(filenames ...string) (*Set, os.Error) {
+func ParseSetFiles(filenames ...string) (*Set, error) {
s := new(Set)
for _, filename := range filenames {
b, err := ioutil.ReadFile(filename)
// pattern. The pattern is processed by filepath.Glob and must match at
// least one file.
// If an error occurs, parsing stops and the returned set is nil.
-func (s *Set) ParseGlob(pattern string) (*Set, os.Error) {
+func (s *Set) ParseGlob(pattern string) (*Set, error) {
filenames, err := filepath.Glob(pattern)
if err != nil {
return nil, err
// ParseSetGlob creates a new Set and parses the set definition from the
// files identified by the pattern. The pattern is processed by filepath.Glob
// and must match at least one file.
-func ParseSetGlob(pattern string) (*Set, os.Error) {
+func ParseSetGlob(pattern string) (*Set, error) {
set, err := new(Set).ParseGlob(pattern)
if err != nil {
return nil, err
// individual templates, which are then added to the set.
// Each file must be parseable by itself.
// If an error occurs, parsing stops and the returned set is nil.
-func (s *Set) ParseTemplateFiles(filenames ...string) (*Set, os.Error) {
+func (s *Set) ParseTemplateFiles(filenames ...string) (*Set, error) {
for _, filename := range filenames {
_, err := parseFileInSet(filename, s)
if err != nil {
// individual templates, which are then added to the set.
// Each file must be parseable by itself.
// If an error occurs, parsing stops and the returned set is nil.
-func (s *Set) ParseTemplateGlob(pattern string) (*Set, os.Error) {
+func (s *Set) ParseTemplateGlob(pattern string) (*Set, error) {
filenames, err := filepath.Glob(pattern)
if err != nil {
return nil, err
// individual templates, which are then added to the set.
// Each file must be parseable by itself. Parsing stops if an error is
// encountered.
-func ParseTemplateFiles(filenames ...string) (*Set, os.Error) {
+func ParseTemplateFiles(filenames ...string) (*Set, error) {
set := new(Set)
set.init()
for _, filename := range filenames {
// individual templates, which are then added to the set.
// Each file must be parseable by itself. Parsing stops if an error is
// encountered.
-func ParseTemplateGlob(pattern string) (*Set, os.Error) {
+func ParseTemplateGlob(pattern string) (*Set, error) {
set := new(Set)
filenames, err := filepath.Glob(pattern)
if err != nil {
package template
import (
- "os"
"reflect"
"template/parse"
)
// Parse parses the template definition string to construct an internal
// representation of the template for execution.
-func (t *Template) Parse(s string) (tmpl *Template, err os.Error) {
+func (t *Template) Parse(s string) (tmpl *Template, err error) {
t.Tree, err = parse.New(t.name).Parse(s, t.leftDelim, t.rightDelim, t.parseFuncs, builtins)
if err != nil {
return nil, err
// representation of the template for execution. It also adds the template
// to the set.
// Function bindings are checked against those in the set.
-func (t *Template) ParseInSet(s string, set *Set) (tmpl *Template, err os.Error) {
+func (t *Template) ParseInSet(s string, set *Set) (tmpl *Template, err error) {
var setFuncs FuncMap
if set != nil {
setFuncs = set.parseFuncs
import (
"bytes"
"fmt"
- "os"
"strconv"
"strings"
)
Text string // The original textual representation from the input.
}
-func newNumber(text string, typ itemType) (*NumberNode, os.Error) {
+func newNumber(text string, typ itemType) (*NumberNode, error) {
n := &NumberNode{NodeType: NodeNumber, Text: text}
switch typ {
case itemCharConstant:
import (
"fmt"
- "os"
"runtime"
"strconv"
"unicode"
}
// error terminates processing.
-func (t *Tree) error(err os.Error) {
+func (t *Tree) error(err error) {
t.errorf("%s", err)
}
}
// recover is the handler that turns panics into returns from the top level of Parse.
-func (t *Tree) recover(errp *os.Error) {
+func (t *Tree) recover(errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
if t != nil {
t.stopParse()
}
- *errp = e.(os.Error)
+ *errp = e.(error)
}
return
}
// Parse parses the template definition string to construct an internal
// representation of the template for execution. If either action delimiter
// string is empty, the default ("{{" or "}}") is used.
-func (t *Tree) Parse(s, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree *Tree, err os.Error) {
+func (t *Tree) Parse(s, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree *Tree, err error) {
defer t.recover(&err)
t.startParse(funcs, lex(t.Name, s, leftDelim, rightDelim))
t.parse(true)
import (
"fmt"
- "os"
"strconv"
)
// Set returns a slice of Trees created by parsing the template set
// definition in the argument string. If an error is encountered,
// parsing stops and an empty slice is returned with the error.
-func Set(text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree map[string]*Tree, err os.Error) {
+func Set(text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree map[string]*Tree, err error) {
tree = make(map[string]*Tree)
defer (*Tree)(nil).recover(&err)
lex := lex("set", text, leftDelim, rightDelim)
import (
"fmt"
"io"
- "os"
"reflect"
"template/parse"
)
}
// add adds the argument template to the set.
-func (s *Set) add(t *Template) os.Error {
+func (s *Set) add(t *Template) error {
s.init()
if t.set != nil {
return fmt.Errorf("template: %q already in a set", t.name)
// Execute applies the named template to the specified data object, writing
// the output to wr.
-func (s *Set) Execute(wr io.Writer, name string, data interface{}) os.Error {
+func (s *Set) Execute(wr io.Writer, name string, data interface{}) error {
tmpl := s.tmpl[name]
if tmpl == nil {
return fmt.Errorf("template: no template %q in set", name)
// multiple times for a given set, adding the templates defined in the string
// to the set. If a template is redefined, the element in the set is
// overwritten with the new definition.
-func (s *Set) Parse(text string) (*Set, os.Error) {
+func (s *Set) Parse(text string) (*Set, error) {
trees, err := parse.Set(text, s.leftDelim, s.rightDelim, s.parseFuncs, builtins)
if err != nil {
return nil, err
// An internal function but exported because it is cross-package; part of the implementation
// of gotest.
-func RunBenchmarks(matchString func(pat, str string) (bool, os.Error), benchmarks []InternalBenchmark) {
+func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) {
// If no flag was specified, don't run benchmarks.
if len(*matchBenchmarks) == 0 {
return
for _, Benchmark := range benchmarks {
matched, err := matchString(*matchBenchmarks, Benchmark.Name)
if err != nil {
- println("invalid regexp for -test.bench:", err.String())
+ println("invalid regexp for -test.bench:", err.Error())
os.Exit(1)
}
if !matched {
defer func() {
os.Stdout, os.Stderr = stdout, stderr
if e := recover(); e != nil {
- if err, ok := e.(os.Error); ok {
+ if err, ok := e.(error); ok {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
import (
"io"
"log"
- "os"
)
type writeLogger struct {
w io.Writer
}
-func (l *writeLogger) Write(p []byte) (n int, err os.Error) {
+func (l *writeLogger) Write(p []byte) (n int, err error) {
n, err = l.w.Write(p)
if err != nil {
log.Printf("%s %x: %v", l.prefix, p[0:n], err)
r io.Reader
}
-func (l *readLogger) Read(p []byte) (n int, err os.Error) {
+func (l *readLogger) Read(p []byte) (n int, err error) {
n, err = l.r.Read(p)
if err != nil {
log.Printf("%s %x: %v", l.prefix, p[0:n], err)
package iotest
import (
+ "errors"
"io"
- "os"
)
// OneByteReader returns a Reader that implements
r io.Reader
}
-func (r *oneByteReader) Read(p []byte) (int, os.Error) {
+func (r *oneByteReader) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
r io.Reader
}
-func (r *halfReader) Read(p []byte) (int, os.Error) {
+func (r *halfReader) Read(p []byte) (int, error) {
return r.r.Read(p[0 : (len(p)+1)/2])
}
data []byte
}
-func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
+func (r *dataErrReader) Read(p []byte) (n int, err error) {
// loop because first call needs two reads:
// one to get data and a second to look for an error.
for {
return
}
-var ErrTimeout = os.NewError("timeout")
+var ErrTimeout = errors.New("timeout")
// TimeoutReader returns ErrTimeout on the second read
// with no data. Subsequent calls to read succeed.
count int
}
-func (r *timeoutReader) Read(p []byte) (int, os.Error) {
+func (r *timeoutReader) Read(p []byte) (int, error) {
r.count++
if r.count == 2 {
return 0, ErrTimeout
package iotest
-import (
- "io"
- "os"
-)
+import "io"
// TruncateWriter returns a Writer that writes to w
// but stops silently after n bytes.
n int64
}
-func (t *truncateWriter) Write(p []byte) (n int, err os.Error) {
+func (t *truncateWriter) Write(p []byte) (n int, err error) {
if t.n <= 0 {
return len(p), nil
}
"flag"
"fmt"
"math"
- "os"
"rand"
"reflect"
"strings"
// used, independent of the functions being tested.
type SetupError string
-func (s SetupError) String() string { return string(s) }
+func (s SetupError) Error() string { return string(s) }
// A CheckError is the result of Check finding an error.
type CheckError struct {
In []interface{}
}
-func (s *CheckError) String() string {
+func (s *CheckError) Error() string {
return fmt.Sprintf("#%d: failed on input %s", s.Count, toString(s.In))
}
Out2 []interface{}
}
-func (s *CheckEqualError) String() string {
+func (s *CheckEqualError) Error() string {
return fmt.Sprintf("#%d: failed on input %s. Output 1: %s. Output 2: %s", s.Count, toString(s.In), toString(s.Out1), toString(s.Out2))
}
// t.Error(err)
// }
// }
-func Check(function interface{}, config *Config) (err os.Error) {
+func Check(function interface{}, config *Config) (err error) {
if config == nil {
config = &defaultConfig
}
// It calls f and g repeatedly with arbitrary values for each argument.
// If f and g return different answers, CheckEqual returns a *CheckEqualError
// describing the input and the outputs.
-func CheckEqual(f, g interface{}, config *Config) (err os.Error) {
+func CheckEqual(f, g interface{}, config *Config) (err error) {
if config == nil {
config = &defaultConfig
}
// arbitraryValues writes Values to args such that args contains Values
// suitable for calling f.
-func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err os.Error) {
+func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) {
if config.Values != nil {
config.Values(args, rand)
return
"rand"
"reflect"
"testing"
- "os"
)
func fBool(a bool) bool { return a }
return &b
}
-func reportError(property string, err os.Error, t *testing.T) {
+func reportError(property string, err error, t *testing.T) {
if err != nil {
t.Errorf("%s: %s", property, err)
}
import (
"fmt"
- "os"
"rand"
"reflect"
"strings"
ready []*Event
}
-func (r ReceivedUnexpected) String() string {
+func (r ReceivedUnexpected) Error() string {
names := make([]string, len(r.ready))
for i, v := range r.ready {
names[i] = v.name
// Events.
type SetupError string
-func (s SetupError) String() string { return string(s) }
+func (s SetupError) Error() string { return string(s) }
func NewEvent(name string, predecessors []*Event, action action) *Event {
e := &Event{name, false, predecessors, action}
// the other. At each receive step, all the receive channels are considered,
// thus Perform may see a value from a channel that is not in the current ready
// set and fail.
-func Perform(seed int64, events []*Event) (err os.Error) {
+func Perform(seed int64, events []*Event) (err error) {
r := rand.New(rand.NewSource(seed))
channels, err := getChannels(events)
}
// getChannels returns all the channels listed in any receive events.
-func getChannels(events []*Event) ([]interface{}, os.Error) {
+func getChannels(events []*Event) ([]interface{}, error) {
channels := make([]interface{}, len(events))
j := 0
}
// readyEvents returns the subset of events that are ready.
-func readyEvents(events []*Event) ([]*Event, os.Error) {
+func readyEvents(events []*Event) ([]*Event, error) {
ready := make([]*Event, len(events))
j := 0
// An internal function but exported because it is cross-package; part of the implementation
// of gotest.
-func Main(matchString func(pat, str string) (bool, os.Error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
+func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) {
flag.Parse()
parseCpuList()
}
}
-func RunTests(matchString func(pat, str string) (bool, os.Error), tests []InternalTest) (ok bool) {
+func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) {
ok = true
if len(tests) == 0 {
fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
for i := 0; i < len(tests); i++ {
matched, err := matchString(*match, tests[i].Name)
if err != nil {
- println("invalid regexp for -test.run:", err.String())
+ println("invalid regexp for -test.run:", err.Error())
os.Exit(1)
}
if !matched {
import (
"bytes"
- "os"
+ "errors"
"strconv"
)
return true
}
-func lookup(tab []string, val string) (int, string, os.Error) {
+func lookup(tab []string, val string) (int, string, error) {
for i, v := range tab {
if len(val) >= len(v) && match(val[0:len(v)], v) {
return i, val[len(v):], nil
return t.Format(UnixDate)
}
-var errBad = os.NewError("bad value for field") // placeholder not passed to user
+var errBad = errors.New("bad value for field") // placeholder not passed to user
// ParseError describes a problem parsing a time string.
type ParseError struct {
}
// String is the string representation of a ParseError.
-func (e *ParseError) String() string {
+func (e *ParseError) Error() string {
if e.Message == "" {
return "parsing time " +
strconv.Quote(e.Value) + " as " +
// getnum parses s[0:1] or s[0:2] (fixed forces the latter)
// as a decimal integer and returns the integer and the
// remainder of the string.
-func getnum(s string, fixed bool) (int, string, os.Error) {
+func getnum(s string, fixed bool) (int, string, error) {
if !isDigit(s, 0) {
return 0, s, errBad
}
// skip removes the given prefix from value,
// treating runs of space characters as equivalent.
-func skip(value, prefix string) (string, os.Error) {
+func skip(value, prefix string) (string, error) {
for len(prefix) > 0 {
if prefix[0] == ' ' {
if len(value) > 0 && value[0] != ' ' {
// sane: hours in 0..23, minutes in 0..59, day of month in 1..31, etc.
// Years must be in the range 0000..9999. The day of the week is checked
// for syntax but it is otherwise ignored.
-func Parse(alayout, avalue string) (*Time, os.Error) {
+func Parse(alayout, avalue string) (*Time, error) {
var t Time
rangeErrString := "" // set if a value is out of range
amSet := false // do we need to subtract 12 from the hour for midnight?
layout, value := alayout, avalue
// Each iteration processes one std value.
for {
- var err os.Error
+ var err error
prefix, std, suffix := nextStdChunk(layout)
value, err = skip(value, prefix)
if err != nil {
return &t, nil
}
-func (t *Time) parseNanoseconds(value string, nbytes int) (rangErrString string, err os.Error) {
+func (t *Time) parseNanoseconds(value string, nbytes int) (rangErrString string, err error) {
if value[0] != '.' {
return "", errBad
}
package time_test
import (
+ "errors"
"fmt"
- "os"
"testing"
"sort"
. "time"
// This test flakes out on some systems,
// so we'll try it a few times before declaring it a failure.
const attempts = 3
- err := os.NewError("!=nil")
+ err := errors.New("!=nil")
for i := 0; i < attempts && err != nil; i++ {
if err = testAfterQueuing(t); err != nil {
t.Logf("attempt %v failed: %v", i, err)
result <- afterResult{slot, <-ac}
}
-func testAfterQueuing(t *testing.T) os.Error {
+func testAfterQueuing(t *testing.T) error {
const (
Delta = 100 * 1e6
)
// Sleep pauses the current goroutine for at least ns nanoseconds.
// Higher resolution sleeping may be provided by syscall.Nanosleep
// on some operating systems.
-func Sleep(ns int64) os.Error {
+func Sleep(ns int64) error {
_, err := sleep(Nanoseconds(), ns)
return err
}
// sleep takes the current time and a duration,
// pauses for at least ns nanoseconds, and
// returns the current time and an error.
-func sleep(t, ns int64) (int64, os.Error) {
+func sleep(t, ns int64) (int64, error) {
// TODO(cw): use monotonic-time once it's available
end := t + ns
for t < end {
"syscall"
)
-func sysSleep(t int64) os.Error {
+func sysSleep(t int64) error {
err := syscall.Sleep(t)
if err != nil {
return os.NewSyscallError("sleep", err)
"syscall"
)
-func sysSleep(t int64) os.Error {
+func sysSleep(t int64) error {
errno := syscall.Sleep(t)
if errno != 0 && errno != syscall.EINTR {
return os.NewSyscallError("sleep", errno)
"syscall"
)
-func sysSleep(t int64) os.Error {
+func sysSleep(t int64) error {
errno := syscall.Sleep(t)
if errno != 0 && errno != syscall.EINTR {
return os.NewSyscallError("sleep", errno)
package time
import (
- "os"
+ "errors"
"sync"
)
// ns must be greater than zero; if not, NewTicker will panic.
func NewTicker(ns int64) *Ticker {
if ns <= 0 {
- panic(os.NewError("non-positive interval for NewTicker"))
+ panic(errors.New("non-positive interval for NewTicker"))
}
c := make(chan int64, 1) // See comment on send in tickerLoop
t := &Ticker{
_, err := Parse(test.format, test.value)
if err == nil {
t.Errorf("expected error for %q %q", test.format, test.value)
- } else if strings.Index(err.String(), test.expect) < 0 {
+ } else if strings.Index(err.Error(), test.expect) < 0 {
t.Errorf("expected error with %q for %q %q; got %s", test.expect, test.format, test.value, err)
}
}
}
var tz zoneinfo
-var initError os.Error
+var initError error
var onceSetupZone sync.Once
func setupZone() {
package url
import (
- "os"
+ "errors"
"strconv"
"strings"
)
// Error reports an error and the operation and URL that caused it.
type Error struct {
- Op string
- URL string
- Error os.Error
+ Op string
+ URL string
+ Err error
}
-func (e *Error) String() string { return e.Op + " " + e.URL + ": " + e.Error.String() }
+func (e *Error) Error() string { return e.Op + " " + e.URL + ": " + e.Err.Error() }
func ishex(c byte) bool {
switch {
type EscapeError string
-func (e EscapeError) String() string {
+func (e EscapeError) Error() string {
return "invalid URL escape " + strconv.Quote(string(e))
}
// QueryUnescape does the inverse transformation of QueryEscape, converting
// %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if
// any % is not followed by two hexadecimal digits.
-func QueryUnescape(s string) (string, os.Error) {
+func QueryUnescape(s string) (string, error) {
return unescape(s, encodeQueryComponent)
}
// unescape unescapes a string; the mode specifies
// which section of the URL string is being unescaped.
-func unescape(s string, mode encoding) (string, os.Error) {
+func unescape(s string, mode encoding) (string, error) {
// Count %, check that they're well-formed.
n := 0
hasPlus := false
// ``is NOT RECOMMENDED, because the passing of authentication
// information in clear text (such as URI) has proven to be a
// security risk in almost every case where it has been used.''
-func UnescapeUserinfo(rawUserinfo string) (user, password string, err os.Error) {
+func UnescapeUserinfo(rawUserinfo string) (user, password string, err error) {
u, p := split(rawUserinfo, ':', true)
if user, err = unescape(u, encodeUserPassword); err != nil {
return "", "", err
// Maybe rawurl is of the form scheme:path.
// (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*)
// If so, return scheme, path; else return "", rawurl.
-func getscheme(rawurl string) (scheme, path string, err os.Error) {
+func getscheme(rawurl string) (scheme, path string, err error) {
for i := 0; i < len(rawurl); i++ {
c := rawurl[i]
switch {
}
case c == ':':
if i == 0 {
- return "", "", os.NewError("missing protocol scheme")
+ return "", "", errors.New("missing protocol scheme")
}
return rawurl[0:i], rawurl[i+1:], nil
default:
// The string rawurl is assumed not to have a #fragment suffix.
// (Web browsers strip #fragment before sending the URL to a web server.)
// The rawurl may be relative or absolute.
-func Parse(rawurl string) (url *URL, err os.Error) {
+func Parse(rawurl string) (url *URL, err error) {
return parse(rawurl, false)
}
// only as an absolute URI or an absolute path.
// The string rawurl is assumed not to have a #fragment suffix.
// (Web browsers strip #fragment before sending the URL to a web server.)
-func ParseRequest(rawurl string) (url *URL, err os.Error) {
+func ParseRequest(rawurl string) (url *URL, err error) {
return parse(rawurl, true)
}
// viaRequest is true, the URL is assumed to have arrived via an HTTP request,
// in which case only absolute URLs or path-absolute relative URLs are allowed.
// If viaRequest is false, all forms of relative URLs are allowed.
-func parse(rawurl string, viaRequest bool) (url *URL, err os.Error) {
+func parse(rawurl string, viaRequest bool) (url *URL, err error) {
var (
leadingSlash bool
path string
)
if rawurl == "" {
- err = os.NewError("empty url")
+ err = errors.New("empty url")
goto Error
}
url = new(URL)
url.OpaquePath = true
} else {
if viaRequest && !leadingSlash {
- err = os.NewError("invalid URI for request")
+ err = errors.New("invalid URI for request")
goto Error
}
if strings.Contains(rawHost, "%") {
// Host cannot contain escaped characters.
- err = os.NewError("hexadecimal escape in host")
+ err = errors.New("hexadecimal escape in host")
goto Error
}
url.Host = rawHost
}
// ParseWithReference is like Parse but allows a trailing #fragment.
-func ParseWithReference(rawurlref string) (url *URL, err os.Error) {
+func ParseWithReference(rawurlref string) (url *URL, err error) {
// Cut off #frag.
rawurl, frag := split(rawurlref, '#', false)
if url, err = Parse(rawurl); err != nil {
// ParseQuery always returns a non-nil map containing all the
// valid query parameters found; err describes the first decoding error
// encountered, if any.
-func ParseQuery(query string) (m Values, err os.Error) {
+func ParseQuery(query string) (m Values, err error) {
m = make(Values)
err = parseQuery(m, query)
return
}
-func parseQuery(m Values, query string) (err os.Error) {
+func parseQuery(m Values, query string) (err error) {
for query != "" {
key := query
if i := strings.IndexAny(key, "&;"); i >= 0 {
// Parse parses a URL in the context of a base URL. The URL in ref
// may be relative or absolute. Parse returns nil, err on parse
// failure, otherwise its return value is the same as ResolveReference.
-func (base *URL) Parse(ref string) (*URL, os.Error) {
+func (base *URL) Parse(ref string) (*URL, error) {
refurl, err := Parse(ref)
if err != nil {
return nil, err
import (
"fmt"
- "os"
"reflect"
"testing"
)
u.Host, u.Path, u.RawQuery, u.Fragment)
}
-func DoTest(t *testing.T, parse func(string) (*URL, os.Error), name string, tests []URLTest) {
+func DoTest(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) {
for _, tt := range tests {
u, err := parse(tt.in)
if err != nil {
}
}
-func DoTestString(t *testing.T, parse func(string) (*URL, os.Error), name string, tests []URLTest) {
+func DoTestString(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) {
for _, tt := range tests {
u, err := parse(tt.in)
if err != nil {
type EscapeTest struct {
in string
out string
- err os.Error
+ err error
}
var unescapeTests = []EscapeTest{
package utf8
+import "errors"
+
// String wraps a regular string with a small structure that provides more
// efficient indexing by code point index, as opposed to byte index.
// Scanning incrementally forwards or backwards is O(1) per index operation
return r
}
-// We want the panic in At(i) to satisfy os.Error, because that's what
-// runtime panics satisfy, but we can't import os. This is our solution.
-
-// error is the type of the error returned if a user calls String.At(i) with i out of range.
-// It satisfies os.Error and runtime.Error.
-type error string
-
-func (err error) String() string {
- return string(err)
-}
-
-func (err error) RunTimeError() {
-}
-
-var outOfRange = error("utf8.String: index out of range")
-var sliceOutOfRange = error("utf8.String: slice index out of range")
+var outOfRange = errors.New("utf8.String: index out of range")
+var sliceOutOfRange = errors.New("utf8.String: slice index out of range")
"crypto/tls"
"io"
"net"
- "os"
"url"
)
// DialError is an error that occurs while dialling a websocket server.
type DialError struct {
*Config
- Error os.Error
+ Err error
}
-func (e *DialError) String() string {
- return "websocket.Dial " + e.Config.Location.String() + ": " + e.Error.String()
+func (e *DialError) Error() string {
+ return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error()
}
// NewConfig creates a new WebSocket config for client connection.
-func NewConfig(server, origin string) (config *Config, err os.Error) {
+func NewConfig(server, origin string) (config *Config, err error) {
config = new(Config)
config.Version = ProtocolVersionHybi13
config.Location, err = url.ParseRequest(server)
}
// NewClient creates a new WebSocket client connection over rwc.
-func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err os.Error) {
+func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) {
br := bufio.NewReader(rwc)
bw := bufio.NewWriter(rwc)
switch config.Version {
// use msg[0:n]
}
*/
-func Dial(url_, protocol, origin string) (ws *Conn, err os.Error) {
+func Dial(url_, protocol, origin string) (ws *Conn, err error) {
config, err := NewConfig(url_, origin)
if err != nil {
return nil, err
}
// DialConfig opens a new client connection to a WebSocket with a config.
-func DialConfig(config *Config) (ws *Conn, err os.Error) {
+func DialConfig(config *Config) (ws *Conn, err error) {
var client net.Conn
if config.Location == nil {
return nil, &DialError{config, ErrBadWebSocketLocation}
"http"
"io"
"io/ioutil"
- "os"
"rand"
"strconv"
"strings"
}
type byteReader interface {
- ReadByte() (byte, os.Error)
+ ReadByte() (byte, error)
}
// readHixieLength reads frame length for frame type 0x80-0xFF
// as defined in Hixie draft.
// See section 4.2 Data framing.
// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-4.2
-func readHixieLength(r byteReader) (length int64, lengthFields []byte, err os.Error) {
+func readHixieLength(r byteReader) (length int64, lengthFields []byte, err error) {
for {
c, err := r.ReadByte()
if err != nil {
length int
}
-func (frame *hixieLengthFrameReader) Read(msg []byte) (n int, err os.Error) {
+func (frame *hixieLengthFrameReader) Read(msg []byte) (n int, err error) {
return frame.reader.Read(msg)
}
trailer *bytes.Buffer
}
-func (frame *hixieSentinelFrameReader) Read(msg []byte) (n int, err os.Error) {
+func (frame *hixieSentinelFrameReader) Read(msg []byte) (n int, err error) {
if len(frame.data) == 0 {
if frame.seenTrailer {
- return 0, os.EOF
+ return 0, io.EOF
}
frame.data, err = frame.reader.ReadSlice('\xff')
if err == nil {
*bufio.Reader
}
-func (buf hixieFrameReaderFactory) NewFrameReader() (r frameReader, err os.Error) {
+func (buf hixieFrameReaderFactory) NewFrameReader() (r frameReader, err error) {
var header []byte
var b byte
b, err = buf.ReadByte()
return nil, err
}
if length == 0 {
- return nil, os.EOF
+ return nil, io.EOF
}
header = append(header, lengthFields...)
return &hixieLengthFrameReader{
writer *bufio.Writer
}
-func (frame *hixiFrameWriter) Write(msg []byte) (n int, err os.Error) {
+func (frame *hixiFrameWriter) Write(msg []byte) (n int, err error) {
frame.writer.WriteByte(0)
frame.writer.Write(msg)
frame.writer.WriteByte(0xff)
return len(msg), err
}
-func (frame *hixiFrameWriter) Close() os.Error { return nil }
+func (frame *hixiFrameWriter) Close() error { return nil }
type hixiFrameWriterFactory struct {
*bufio.Writer
}
-func (buf hixiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err os.Error) {
+func (buf hixiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) {
if payloadType != TextFrame {
return nil, ErrNotSupported
}
conn *Conn
}
-func (handler *hixiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err os.Error) {
+func (handler *hixiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err error) {
if header := frame.HeaderReader(); header != nil {
io.Copy(ioutil.Discard, header)
}
return frame, nil
}
-func (handler *hixiFrameHandler) WriteClose(_ int) (err os.Error) {
+func (handler *hixiFrameHandler) WriteClose(_ int) (err error) {
handler.conn.wio.Lock()
defer handler.conn.wio.Unlock()
closingFrame := []byte{'\xff', '\x00'}
// getChallengeResponse computes the expected response from the
// challenge as described in section 5.1 Opening Handshake steps 42 to
// 43 of http://www.whatwg.org/specs/web-socket-protocol/
-func getChallengeResponse(number1, number2 uint32, key3 []byte) (expected []byte, err os.Error) {
+func getChallengeResponse(number1, number2 uint32, key3 []byte) (expected []byte, err error) {
// 41. Let /challenge/ be the concatenation of /number_1/, expressed
// a big-endian 32 bit integer, /number_2/, expressed in a big-
// endian 32 bit integer, and the eight bytes of /key_3/ in the
// Cilent handhake described in (soon obsolete)
// draft-ietf-hybi-thewebsocket-protocol-00
// (draft-hixie-thewebsocket-protocol-76)
-func hixie76ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err os.Error) {
+func hixie76ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) {
switch config.Version {
case ProtocolVersionHixie76, ProtocolVersionHybi00:
default:
// Client Handshake described in (soon obsolete)
// draft-hixie-thewebsocket-protocol-75.
-func hixie75ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err os.Error) {
+func hixie75ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) {
if config.Version != ProtocolVersionHixie75 {
panic("wrong protocol version.")
}
challengeResponse []byte
}
-func (c *hixie76ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) {
+func (c *hixie76ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
c.Version = ProtocolVersionHybi00
if req.Method != "GET" {
return http.StatusMethodNotAllowed, ErrBadRequestMethod
return http.StatusSwitchingProtocols, nil
}
-func (c *hixie76ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err os.Error) {
+func (c *hixie76ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) {
if len(c.Protocol) > 0 {
if len(c.Protocol) != 1 {
return ErrBadWebSocketProtocol
*Config
}
-func (c *hixie75ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) {
+func (c *hixie75ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
c.Version = ProtocolVersionHixie75
if req.Method != "GET" || req.Proto != "HTTP/1.1" {
return http.StatusMethodNotAllowed, ErrBadRequestMethod
return http.StatusSwitchingProtocols, nil
}
-func (c *hixie75ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err os.Error) {
+func (c *hixie75ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) {
if len(c.Protocol) > 0 {
if len(c.Protocol) != 1 {
return ErrBadWebSocketProtocol
"bytes"
"fmt"
"http"
- "os"
+ "io"
"strings"
"testing"
"url"
8jKS'y:G*Co,Wxa-`))
- var err os.Error
+ var err error
config := new(Config)
config.Location, err = url.ParseRequest("ws://example.com/demo")
if err != nil {
t.Errorf("Read: expected %q got %q", b[1:6], msg[0:n])
}
n, err = ws.Read(msg)
- if err != os.EOF {
+ if err != io.EOF {
t.Errorf("read: %v", err)
}
}
"http"
"io"
"io/ioutil"
- "os"
"strings"
"url"
)
length int
}
-func (frame *hybiFrameReader) Read(msg []byte) (n int, err os.Error) {
+func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) {
n, err = frame.reader.Read(msg)
if err != nil {
return 0, err
// NewFrameReader reads a frame header from the connection, and creates new reader for the frame.
// See Section 5.2 Base Frameing protocol for detail.
// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2
-func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err os.Error) {
+func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) {
hybiFrame := new(hybiFrameReader)
frame = hybiFrame
var header []byte
header *hybiFrameHeader
}
-func (frame *hybiFrameWriter) Write(msg []byte) (n int, err os.Error) {
+func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) {
var header []byte
var b byte
if frame.header.Fin {
return length, err
}
-func (frame *hybiFrameWriter) Close() os.Error { return nil }
+func (frame *hybiFrameWriter) Close() error { return nil }
type hybiFrameWriterFactory struct {
*bufio.Writer
needMaskingKey bool
}
-func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err os.Error) {
+func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) {
frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType}
if buf.needMaskingKey {
frameHeader.MaskingKey, err = generateMaskingKey()
payloadType byte
}
-func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err os.Error) {
+func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err error) {
if handler.conn.IsServerConn() {
// The client MUST mask all frames sent to the server.
if frame.(*hybiFrameReader).header.MaskingKey == nil {
handler.WriteClose(closeStatusProtocolError)
- return nil, os.EOF
+ return nil, io.EOF
}
} else {
// The server MUST NOT mask all frames.
if frame.(*hybiFrameReader).header.MaskingKey != nil {
handler.WriteClose(closeStatusProtocolError)
- return nil, os.EOF
+ return nil, io.EOF
}
}
if header := frame.HeaderReader(); header != nil {
case TextFrame, BinaryFrame:
handler.payloadType = frame.PayloadType()
case CloseFrame:
- return nil, os.EOF
+ return nil, io.EOF
case PingFrame:
pingMsg := make([]byte, maxControlFramePayloadLength)
n, err := io.ReadFull(frame, pingMsg)
return frame, nil
}
-func (handler *hybiFrameHandler) WriteClose(status int) (err os.Error) {
+func (handler *hybiFrameHandler) WriteClose(status int) (err error) {
handler.conn.wio.Lock()
defer handler.conn.wio.Unlock()
w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame)
return err
}
-func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err os.Error) {
+func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) {
handler.conn.wio.Lock()
defer handler.conn.wio.Unlock()
w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame)
}
// generateMaskingKey generates a masking key for a frame.
-func generateMaskingKey() (maskingKey []byte, err os.Error) {
+func generateMaskingKey() (maskingKey []byte, err error) {
maskingKey = make([]byte, 4)
if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil {
return
// getNonceAccept computes the base64-encoded SHA-1 of the concatenation of
// the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string.
-func getNonceAccept(nonce []byte) (expected []byte, err os.Error) {
+func getNonceAccept(nonce []byte) (expected []byte, err error) {
h := sha1.New()
if _, err = h.Write(nonce); err != nil {
return
}
// Client handhake described in draft-ietf-hybi-thewebsocket-protocol-17
-func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err os.Error) {
+func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) {
if !isHybiVersion(config.Version) {
panic("wrong protocol version.")
}
accept []byte
}
-func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) {
+func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
c.Version = ProtocolVersionHybi13
if req.Method != "GET" {
return http.StatusMethodNotAllowed, ErrBadRequestMethod
return http.StatusSwitchingProtocols, nil
}
-func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err os.Error) {
+func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) {
if len(c.Protocol) > 0 {
if len(c.Protocol) != 1 {
return ErrBadWebSocketProtocol
"bytes"
"fmt"
"http"
- "os"
+ "io"
"strings"
"testing"
"url"
Sec-WebSocket-Protocol: chat
`))
- var err os.Error
+ var err error
config := new(Config)
config.Location, err = url.ParseRequest("ws://server.example.com/chat")
if err != nil {
Sec-WebSocket-Protocol: chat
`))
- var err os.Error
+ var err error
config := new(Config)
config.Location, err = url.ParseRequest("ws://server.example.com/chat")
if err != nil {
// server MUST close the connection upon receiving a non-masked frame.
msg := make([]byte, 512)
_, err := conn.Read(msg)
- if err != os.EOF {
- t.Errorf("read 1st frame, expect %q, but got %q", os.EOF, err)
+ if err != io.EOF {
+ t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err)
}
}
// client MUST close the connection upon receiving a masked frame.
msg := make([]byte, 512)
_, err := conn.Read(msg)
- if err != os.EOF {
- t.Errorf("read 1st frame, expect %q, but got %q", os.EOF, err)
+ if err != io.EOF {
+ t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err)
}
}
"fmt"
"http"
"io"
- "os"
)
-func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err os.Error) {
+func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err error) {
config := new(Config)
var hs serverHandshaker = &hybiServerHandshaker{Config: config}
code, err := hs.ReadHandshake(buf.Reader, req)
fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
buf.WriteString("\r\n")
- buf.WriteString(err.String())
+ buf.WriteString(err.Error())
return
}
if err != nil {
if err != nil {
fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
buf.WriteString("\r\n")
- buf.WriteString(err.String())
+ buf.WriteString(err.Error())
return
}
config.Protocol = nil
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
rwc, buf, err := w.(http.Hijacker).Hijack()
if err != nil {
- panic("Hijack failed: " + err.String())
+ panic("Hijack failed: " + err.Error())
return
}
// The server should abort the WebSocket connection if it finds
ErrorString string
}
-func (err *ProtocolError) String() string { return err.ErrorString }
+func (err *ProtocolError) Error() string { return err.ErrorString }
var (
ErrBadProtocolVersion = &ProtocolError{"bad protocol version"}
type serverHandshaker interface {
// ReadHandshake reads handshake request message from client.
// Returns http response code and error if any.
- ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error)
+ ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error)
// AcceptHandshake accepts the client handshake request and sends
// handshake response back to client.
- AcceptHandshake(buf *bufio.Writer) (err os.Error)
+ AcceptHandshake(buf *bufio.Writer) (err error)
// NewServerConn creates a new WebSocket connection.
NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn)
// frameReaderFactory is an interface to creates new frame reader.
type frameReaderFactory interface {
- NewFrameReader() (r frameReader, err os.Error)
+ NewFrameReader() (r frameReader, err error)
}
// frameWriter is an interface to write a WebSocket frame.
// frameWriterFactory is an interface to create new frame writer.
type frameWriterFactory interface {
- NewFrameWriter(payloadType byte) (w frameWriter, err os.Error)
+ NewFrameWriter(payloadType byte) (w frameWriter, err error)
}
type frameHandler interface {
- HandleFrame(frame frameReader) (r frameReader, err os.Error)
- WriteClose(status int) (err os.Error)
+ HandleFrame(frame frameReader) (r frameReader, err error)
+ WriteClose(status int) (err error)
}
// Conn represents a WebSocket connection.
// if msg is not large enough for the frame data, it fills the msg and next Read
// will read the rest of the frame data.
// it reads Text frame or Binary frame.
-func (ws *Conn) Read(msg []byte) (n int, err os.Error) {
+func (ws *Conn) Read(msg []byte) (n int, err error) {
ws.rio.Lock()
defer ws.rio.Unlock()
again:
}
}
n, err = ws.frameReader.Read(msg)
- if err == os.EOF {
+ if err == io.EOF {
if trailer := ws.frameReader.TrailerReader(); trailer != nil {
io.Copy(ioutil.Discard, trailer)
}
// Write implements the io.Writer interface:
// it writes data as a frame to the WebSocket connection.
-func (ws *Conn) Write(msg []byte) (n int, err os.Error) {
+func (ws *Conn) Write(msg []byte) (n int, err error) {
ws.wio.Lock()
defer ws.wio.Unlock()
w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType)
}
// Close implements the io.Closer interface.
-func (ws *Conn) Close() os.Error {
+func (ws *Conn) Close() error {
err := ws.frameHandler.WriteClose(ws.defaultCloseStatus)
if err != nil {
return err
}
// SetTimeout sets the connection's network timeout in nanoseconds.
-func (ws *Conn) SetTimeout(nsec int64) os.Error {
+func (ws *Conn) SetTimeout(nsec int64) error {
if conn, ok := ws.rwc.(net.Conn); ok {
return conn.SetTimeout(nsec)
}
}
// SetReadTimeout sets the connection's network read timeout in nanoseconds.
-func (ws *Conn) SetReadTimeout(nsec int64) os.Error {
+func (ws *Conn) SetReadTimeout(nsec int64) error {
if conn, ok := ws.rwc.(net.Conn); ok {
return conn.SetReadTimeout(nsec)
}
}
// SetWriteTimeout sets the connection's network write timeout in nanoseconds.
-func (ws *Conn) SetWriteTimeout(nsec int64) os.Error {
+func (ws *Conn) SetWriteTimeout(nsec int64) error {
if conn, ok := ws.rwc.(net.Conn); ok {
return conn.SetWriteTimeout(nsec)
}
// Codec represents a symmetric pair of functions that implement a codec.
type Codec struct {
- Marshal func(v interface{}) (data []byte, payloadType byte, err os.Error)
- Unmarshal func(data []byte, payloadType byte, v interface{}) (err os.Error)
+ Marshal func(v interface{}) (data []byte, payloadType byte, err error)
+ Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
}
// Send sends v marshaled by cd.Marshal as single frame to ws.
-func (cd Codec) Send(ws *Conn, v interface{}) (err os.Error) {
+func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
if err != nil {
return err
}
}
// Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores in v.
-func (cd Codec) Receive(ws *Conn, v interface{}) (err os.Error) {
+func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
ws.rio.Lock()
defer ws.rio.Unlock()
if ws.frameReader != nil {
return cd.Unmarshal(data, payloadType, v)
}
-func marshal(v interface{}) (msg []byte, payloadType byte, err os.Error) {
+func marshal(v interface{}) (msg []byte, payloadType byte, err error) {
switch data := v.(type) {
case string:
return []byte(data), TextFrame, nil
return nil, UnknownFrame, ErrNotSupported
}
-func unmarshal(msg []byte, payloadType byte, v interface{}) (err os.Error) {
+func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
switch data := v.(type) {
case *string:
*data = string(msg)
*/
var Message = Codec{marshal, unmarshal}
-func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err os.Error) {
+func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
msg, err = json.Marshal(v)
return msg, TextFrame, err
}
-func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err os.Error) {
+func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {
return json.Unmarshal(msg, v)
}
t.Errorf("Get: not url.Error %#v", err)
return
}
- if urlerr.Error != io.ErrUnexpectedEOF {
+ if urlerr.Err != io.ErrUnexpectedEOF {
t.Errorf("Get: error %#v", err)
return
}
import (
"bufio"
"io"
- "os"
"reflect"
"strconv"
"strings"
// A Marshaler can produce well-formatted XML representing its internal state.
// It is used by both Marshal and MarshalIndent.
type Marshaler interface {
- MarshalXML() ([]byte, os.Error)
+ MarshalXML() ([]byte, error)
}
type printer struct {
// </result>
//
// Marshal will return an error if asked to marshal a channel, function, or map.
-func Marshal(w io.Writer, v interface{}) (err os.Error) {
+func Marshal(w io.Writer, v interface{}) (err error) {
p := &printer{bufio.NewWriter(w)}
err = p.marshalValue(reflect.ValueOf(v), "???")
p.Flush()
return err
}
-func (p *printer) marshalValue(val reflect.Value, name string) os.Error {
+func (p *printer) marshalValue(val reflect.Value, name string) error {
if !val.IsValid() {
return nil
}
Type reflect.Type
}
-func (e *UnsupportedTypeError) String() string {
+func (e *UnsupportedTypeError) Error() string {
return "xml: unsupported type: " + e.Type.String()
}
import (
"reflect"
"testing"
-
"bytes"
- "os"
- "strconv"
"strings"
+ "strconv"
)
type DriveType int
type RawXML string
-func (rx RawXML) MarshalXML() ([]byte, os.Error) {
+func (rx RawXML) MarshalXML() ([]byte, error) {
return []byte(rx), nil
}
for idx, test := range marshalErrorTests {
buf := bytes.NewBuffer(nil)
err := Marshal(buf, test.Value)
- if err == nil || err.String() != test.Err {
+ if err == nil || err.Error() != test.Err {
t.Errorf("#%d: marshal(%#v) = [error] %q, want %q", idx, test.Value, err, test.Err)
}
if kind := err.(*UnsupportedTypeError).Type.Kind(); kind != test.Kind {
import (
"bytes"
+ "errors"
"fmt"
"io"
- "os"
"reflect"
"strconv"
"strings"
// Unmarshal maps an XML element to a pointer by setting the pointer
// to a freshly allocated value and then mapping the element to that value.
//
-func Unmarshal(r io.Reader, val interface{}) os.Error {
+func Unmarshal(r io.Reader, val interface{}) error {
v := reflect.ValueOf(val)
if v.Kind() != reflect.Ptr {
- return os.NewError("non-pointer passed to Unmarshal")
+ return errors.New("non-pointer passed to Unmarshal")
}
p := NewParser(r)
elem := v.Elem()
// An UnmarshalError represents an error in the unmarshalling process.
type UnmarshalError string
-func (e UnmarshalError) String() string { return string(e) }
+func (e UnmarshalError) Error() string { return string(e) }
// A TagPathError represents an error in the unmarshalling process
// caused by the use of field tags with conflicting paths.
Field2, Tag2 string
}
-func (e *TagPathError) String() string {
+func (e *TagPathError) Error() string {
return fmt.Sprintf("%s field %q with tag %q conflicts with field %q with tag %q", e.Struct, e.Field1, e.Tag1, e.Field2, e.Tag2)
}
// but also defers to Unmarshal for some elements.
// Passing a nil start element indicates that Unmarshal should
// read the token stream to find the start element.
-func (p *Parser) Unmarshal(val interface{}, start *StartElement) os.Error {
+func (p *Parser) Unmarshal(val interface{}, start *StartElement) error {
v := reflect.ValueOf(val)
if v.Kind() != reflect.Ptr {
- return os.NewError("non-pointer passed to Unmarshal")
+ return errors.New("non-pointer passed to Unmarshal")
}
return p.unmarshal(v.Elem(), start)
}
}
// Unmarshal a single XML element into val.
-func (p *Parser) unmarshal(val reflect.Value, start *StartElement) os.Error {
+func (p *Parser) unmarshal(val reflect.Value, start *StartElement) error {
// Find start element if we need it.
if start == nil {
for {
switch v := val; v.Kind() {
default:
- return os.NewError("unknown type " + v.Type().String())
+ return errors.New("unknown type " + v.Type().String())
case reflect.Slice:
typ := v.Type()
return nil
}
-func copyValue(dst reflect.Value, src []byte) (err os.Error) {
+func copyValue(dst reflect.Value, src []byte) (err error) {
// Helper functions for integer and unsigned integer conversions
var itmp int64
getInt64 := func() bool {
case reflect.Invalid:
// Probably a comment, handled below
default:
- return os.NewError("cannot happen: unknown type " + t.Type().String())
+ return errors.New("cannot happen: unknown type " + t.Type().String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if !getInt64() {
return err
// paths map with all paths leading to it ("a", "a>b", and "a>b>c").
// It is okay for paths to share a common, shorter prefix but not ok
// for one path to itself be a prefix of another.
-func addFieldPath(sv reflect.Value, paths map[string]pathInfo, path string, fieldIdx []int) os.Error {
+func addFieldPath(sv reflect.Value, paths map[string]pathInfo, path string, fieldIdx []int) error {
if info, found := paths[path]; found {
return tagError(sv, info.fieldIdx, fieldIdx)
}
}
-func tagError(sv reflect.Value, idx1 []int, idx2 []int) os.Error {
+func tagError(sv reflect.Value, idx1 []int, idx2 []int) error {
t := sv.Type()
f1 := t.FieldByIndex(idx1)
f2 := t.FieldByIndex(idx2)
// unmarshalPaths walks down an XML structure looking for
// wanted paths, and calls unmarshal on them.
-func (p *Parser) unmarshalPaths(sv reflect.Value, paths map[string]pathInfo, path string, start *StartElement) os.Error {
+func (p *Parser) unmarshalPaths(sv reflect.Value, paths map[string]pathInfo, path string, start *StartElement) error {
if info, _ := paths[path]; info.complete {
return p.unmarshal(sv.FieldByIndex(info.fieldIdx), start)
}
// Read tokens until we find the end element.
// Token is taking care of making sure the
// end element matches the start element we saw.
-func (p *Parser) Skip() os.Error {
+func (p *Parser) Skip() error {
for {
tok, err := p.Token()
if err != nil {
"bytes"
"fmt"
"io"
- "os"
"strconv"
"strings"
"unicode"
Line int
}
-func (e *SyntaxError) String() string {
+func (e *SyntaxError) Error() string {
return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg
}
// non-UTF-8 charset into UTF-8. If CharsetReader is nil or
// returns an error, parsing stops with an error. One of the
// the CharsetReader's result values must be non-nil.
- CharsetReader func(charset string, input io.Reader) (io.Reader, os.Error)
+ CharsetReader func(charset string, input io.Reader) (io.Reader, error)
r io.ByteReader
buf bytes.Buffer
nextToken Token
nextByte int
ns map[string]string
- err os.Error
+ err error
line int
tmp [32]byte
}
// set to the URL identifying its name space when known.
// If Token encounters an unrecognized name space prefix,
// it uses the prefix as the Space rather than report an error.
-func (p *Parser) Token() (t Token, err os.Error) {
+func (p *Parser) Token() (t Token, err error) {
if p.nextToken != nil {
t = p.nextToken
p.nextToken = nil
}
// Creates a SyntaxError with the current line number.
-func (p *Parser) syntaxError(msg string) os.Error {
+func (p *Parser) syntaxError(msg string) error {
return &SyntaxError{Msg: msg, Line: p.line}
}
// RawToken is like Token but does not verify that
// start and end elements match and does not translate
// name space prefixes to their corresponding URLs.
-func (p *Parser) RawToken() (Token, os.Error) {
+func (p *Parser) RawToken() (Token, error) {
if p.err != nil {
return nil, p.err
}
// and return ok==false
func (p *Parser) mustgetc() (b byte, ok bool) {
if b, ok = p.getc(); !ok {
- if p.err == os.EOF {
+ if p.err == io.EOF {
p.err = p.syntaxError("unexpected EOF")
}
}
b, ok := p.getc()
if !ok {
if cdata {
- if p.err == os.EOF {
+ if p.err == io.EOF {
p.err = p.syntaxError("unexpected EOF in CDATA section")
}
return nil
var ok bool
p.tmp[i], ok = p.getc()
if !ok {
- if p.err == os.EOF {
+ if p.err == io.EOF {
p.err = p.syntaxError("unexpected EOF")
}
return nil
var text string
if i >= 2 && s[0] == '#' {
var n uint64
- var err os.Error
+ var err error
if i >= 3 && s[1] == 'x' {
n, err = strconv.Btoui64(s[2:], 16)
} else {
off int
}
-func (r *stringReader) Read(b []byte) (n int, err os.Error) {
+func (r *stringReader) Read(b []byte) (n int, err error) {
if r.off >= len(r.s) {
- return 0, os.EOF
+ return 0, io.EOF
}
for r.off < len(r.s) && n < len(b) {
b[n] = r.s[r.off]
return
}
-func (r *stringReader) ReadByte() (b byte, err os.Error) {
+func (r *stringReader) ReadByte() (b byte, err error) {
if r.off >= len(r.s) {
- return 0, os.EOF
+ return 0, io.EOF
}
b = r.s[r.off]
r.off++
r io.ByteReader
}
-func (d *downCaser) ReadByte() (c byte, err os.Error) {
+func (d *downCaser) ReadByte() (c byte, err error) {
c, err = d.r.ReadByte()
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
return
}
-func (d *downCaser) Read(p []byte) (int, os.Error) {
+func (d *downCaser) Read(p []byte) (int, error) {
d.t.Fatalf("unexpected Read call on downCaser reader")
return 0, os.EINVAL
}
func TestRawTokenAltEncoding(t *testing.T) {
sawEncoding := ""
p := NewParser(StringReader(testInputAltEncoding))
- p.CharsetReader = func(charset string, input io.Reader) (io.Reader, os.Error) {
+ p.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
sawEncoding = charset
if charset != "x-testing-uppercase" {
t.Fatalf("unexpected charset %q", charset)
t.Fatalf("expected an error on second RawToken call")
}
const encoding = "x-testing-uppercase"
- if !strings.Contains(err.String(), encoding) {
+ if !strings.Contains(err.Error(), encoding) {
t.Errorf("expected error to contain %q; got error: %v",
encoding, err)
}
func TestSyntax(t *testing.T) {
for i := range xmlInput {
p := NewParser(StringReader(xmlInput[i]))
- var err os.Error
+ var err error
for _, err = p.Token(); err == nil; _, err = p.Token() {
}
if _, ok := err.(*SyntaxError); !ok {
func TestSyntaxErrorLineNum(t *testing.T) {
testInput := "<P>Foo<P>\n\n<P>Bar</>\n"
p := NewParser(StringReader(testInput))
- var err os.Error
+ var err error
for _, err = p.Token(); err == nil; _, err = p.Token() {
}
synerr, ok := err.(*SyntaxError)
func TestTrailingRawToken(t *testing.T) {
input := `<FOO></FOO> `
p := NewParser(StringReader(input))
- var err os.Error
+ var err error
for _, err = p.RawToken(); err == nil; _, err = p.RawToken() {
}
- if err != os.EOF {
+ if err != io.EOF {
t.Fatalf("p.RawToken() = _, %v, want _, os.EOF", err)
}
}
func TestTrailingToken(t *testing.T) {
input := `<FOO></FOO> `
p := NewParser(StringReader(input))
- var err os.Error
+ var err error
for _, err = p.Token(); err == nil; _, err = p.Token() {
}
- if err != os.EOF {
+ if err != io.EOF {
t.Fatalf("p.Token() = _, %v, want _, os.EOF", err)
}
}
func TestEntityInsideCDATA(t *testing.T) {
input := `<test><![CDATA[ &val=foo ]]></test>`
p := NewParser(StringReader(input))
- var err os.Error
+ var err error
for _, err = p.Token(); err == nil; _, err = p.Token() {
}
- if err != os.EOF {
+ if err != io.EOF {
t.Fatalf("p.Token() = _, %v, want _, os.EOF", err)
}
}
for i, tt := range characterTests {
p := NewParser(StringReader(tt.in))
- var err os.Error
+ var err error
for err == nil {
_, err = p.Token()
fi
}
+merge_c() {
+ from=$1
+ to=$2
+ oldfile=${OLDDIR}/src/pkg/runtime/$from
+ if test -f ${oldfile}; then
+ sed -e 's/·/_/g' < ${oldfile} > ${oldfile}.tmp
+ oldfile=${oldfile}.tmp
+ newfile=${NEWDIR}/src/pkg/runtime/$from
+ sed -e 's/·/_/g' < ${newfile} > ${newfile}.tmp
+ newfile=${newfile}.tmp
+ libgofile=runtime/$to
+ merge $from ${oldfile} ${newfile} ${libgofile}
+ fi
+}
+
(cd ${NEWDIR}/src/pkg && find . -name '*.go' -print) | while read f; do
if test `dirname $f` = "./syscall"; then
continue
runtime="chan.c cpuprof.c goc2c.c lock_futex.c lock_sema.c mcache.c mcentral.c mfinal.c mfixalloc.c mgc0.c mheap.c msize.c proc.c runtime.c runtime.h malloc.h malloc.goc mprof.goc runtime1.goc sema.goc sigqueue.goc string.goc"
for f in $runtime; do
- oldfile=${OLDDIR}/src/pkg/runtime/$f
- if test -f ${oldfile}; then
- sed -e 's/·/_/g' < ${oldfile} > ${oldfile}.tmp
- oldfile=${oldfile}.tmp
- newfile=${NEWDIR}/src/pkg/runtime/$f
- sed -e 's/·/_/g' < ${newfile} > ${newfile}.tmp
- newfile=${newfile}.tmp
- libgofile=runtime/$f
- merge $f ${oldfile} ${newfile} ${libgofile}
- fi
+ merge_c $f $f
done
-runtime2="linux/thread.c thread-linux.c linux/mem.c mem.c"
-echo $runtime2 | while read from; do
- read to
- oldfile=${OLDDIR}/src/pkg/runtime/$from
- if test -f ${oldfile}; then
- sed -e 's/·/_/g' < ${oldfile} > ${oldfile}.tmp
- oldfile=${oldfile}.tmp
- newfile=${NEWDIR}/src/pkg/runtime/$from
- sed -e 's/·/_/g' < ${newfile} > ${newfile}.tmp
- newfile=${newfile}.tmp
- libgofile=runtime/$to
- merge $f ${oldfile} ${newfile} ${libgofile}
- fi
-done
+merge_c linux/thread.c thread-linux.c
+merge_c linux/mem.c mem.c
(cd ${OLDDIR}/src/pkg && find . -name '*.go' -print) | while read f; do
oldfile=${OLDDIR}/src/pkg/$f
echo 'import "./_xtest_"'
fi
echo 'import "testing"'
- echo 'import __os__ "os"' # rename in case tested package is called os
echo 'import __regexp__ "regexp"' # rename in case tested package is called regexp
# test array
echo
var matchPat string
var matchRe *__regexp__.Regexp
-func matchString(pat, str string) (result bool, err __os__.Error) {
+func matchString(pat, str string) (result bool, err error) {
if matchRe == nil || matchPat != pat {
matchPat = pat
matchRe, err = __regexp__.Compile(matchPat)