1
0
mirror of https://github.com/golang/go synced 2024-11-25 08:57:58 -07:00

os.Error API: don't export os.ErrorString, use os.NewError consistently

This is a core API change.

1) gofix misc src
2) Manual adjustments to the following files under src/pkg:
   gob/decode.go
   rpc/client.go
   os/error.go
   io/io.go
   bufio/bufio.go
   http/request.go
   websocket/client.go
as well as:
   src/cmd/gofix/testdata/*.go.in (reverted)
   test/fixedbugs/bug243.go
3) Implemented gofix patch (oserrorstring.go) and test case (oserrorstring_test.go)

Compiles and runs all tests.

R=r, rsc, gri
CC=golang-dev
https://golang.org/cl/4607052
This commit is contained in:
Robert Griesemer 2011-06-22 10:52:47 -07:00
parent 55b0662465
commit 712fb6dcd3
80 changed files with 367 additions and 230 deletions

View File

@ -230,9 +230,9 @@ func splitQuoted(s string) (r []string, err os.Error) {
args = append(args, string(arg[:i])) args = append(args, string(arg[:i]))
} }
if quote != 0 { if quote != 0 {
err = os.ErrorString("unclosed quote") err = os.NewError("unclosed quote")
} else if escaped { } else if escaped {
err = os.ErrorString("unfinished escaping") err = os.NewError("unfinished escaping")
} }
return args, err return args, err
} }

View File

@ -9,6 +9,7 @@ GOFILES=\
fix.go\ fix.go\
netdial.go\ netdial.go\
main.go\ main.go\
oserrorstring.go\
osopen.go\ osopen.go\
httpfinalurl.go\ httpfinalurl.go\
httpheaders.go\ httpheaders.go\

View File

@ -0,0 +1,75 @@
// 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 main
import (
"go/ast"
)
var oserrorstringFix = fix{
"oserrorstring",
oserrorstring,
`Replace os.ErrorString() conversions with calls to os.NewError().
http://codereview.appspot.com/4607052
`,
}
func init() {
register(oserrorstringFix)
}
func oserrorstring(f *ast.File) bool {
if !imports(f, "os") {
return false
}
fixed := false
walk(f, func(n interface{}) {
// The conversion os.ErrorString(x) looks like a call
// of os.ErrorString with one argument.
if call := callExpr(n, "os", "ErrorString"); call != nil {
// os.ErrorString(args) -> os.NewError(args)
call.Fun.(*ast.SelectorExpr).Sel.Name = "NewError"
// os.ErrorString(args) -> os.NewError(args)
call.Fun.(*ast.SelectorExpr).Sel.Name = "NewError"
fixed = true
return
}
// Remove os.Error type from variable declarations initialized
// with an os.NewError.
// (An *ast.ValueSpec may also be used in a const declaration
// but those won't be initialized with a call to os.NewError.)
if spec, ok := n.(*ast.ValueSpec); ok &&
len(spec.Names) == 1 &&
isPkgDot(spec.Type, "os", "Error") &&
len(spec.Values) == 1 &&
callExpr(spec.Values[0], "os", "NewError") != nil {
// var name os.Error = os.NewError(x) ->
// var name = os.NewError(x)
spec.Type = nil
fixed = true
return
}
// Other occurrences of os.ErrorString are not fixed
// but they are rare.
})
return fixed
}
// callExpr returns the call expression if x is a call to pkg.name with one argument;
// otherwise it returns nil.
func callExpr(x interface{}, pkg, name string) *ast.CallExpr {
if call, ok := x.(*ast.CallExpr); ok &&
len(call.Args) == 1 &&
isPkgDot(call.Fun, pkg, name) {
return call
}
return nil
}

View File

@ -0,0 +1,57 @@
// 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 main
func init() {
addTestCases(oserrorstringTests)
}
var oserrorstringTests = []testCase{
{
Name: "oserrorstring.0",
In: `package main
import "os"
var _ = os.ErrorString("foo")
var _ os.Error = os.ErrorString("bar1")
var _ os.Error = os.NewError("bar2")
var _ os.Error = MyError("bal") // don't rewrite this one
var (
_ = os.ErrorString("foo")
_ os.Error = os.ErrorString("bar1")
_ os.Error = os.NewError("bar2")
_ os.Error = MyError("bal") // don't rewrite this one
)
func _() (err os.Error) {
err = os.ErrorString("foo")
return os.ErrorString("foo")
}
`,
Out: `package main
import "os"
var _ = os.NewError("foo")
var _ = os.NewError("bar1")
var _ = os.NewError("bar2")
var _ os.Error = MyError("bal") // don't rewrite this one
var (
_ = os.NewError("foo")
_ = os.NewError("bar1")
_ = os.NewError("bar2")
_ os.Error = MyError("bal") // don't rewrite this one
)
func _() (err os.Error) {
err = os.NewError("foo")
return os.NewError("foo")
}
`,
},
}

View File

@ -44,7 +44,7 @@ func NewDecoder(r io.Reader) *Decoder {
func (dec *Decoder) recvType(id typeId) { func (dec *Decoder) recvType(id typeId) {
// Have we already seen this type? That's an error // Have we already seen this type? That's an error
if id < firstUserId || dec.wireType[id] != nil { if id < firstUserId || dec.wireType[id] != nil {
dec.err = os.ErrorString("gob: duplicate type received") dec.err = os.NewError("gob: duplicate type received")
return return
} }
@ -143,7 +143,7 @@ func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId {
// will be absorbed by recvMessage.) // will be absorbed by recvMessage.)
if dec.buf.Len() > 0 { if dec.buf.Len() > 0 {
if !isInterface { if !isInterface {
dec.err = os.ErrorString("extra data in buffer") dec.err = os.NewError("extra data in buffer")
break break
} }
dec.nextUint() dec.nextUint()
@ -165,7 +165,7 @@ func (dec *Decoder) Decode(e interface{}) os.Error {
// If e represents a value as opposed to a pointer, the answer won't // 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. // get back to the caller. Make sure it's a pointer.
if value.Type().Kind() != reflect.Ptr { if value.Type().Kind() != reflect.Ptr {
dec.err = os.ErrorString("gob: attempt to decode into a non-pointer") dec.err = os.NewError("gob: attempt to decode into a non-pointer")
return dec.err return dec.err
} }
return dec.DecodeValue(value) return dec.DecodeValue(value)

View File

@ -50,7 +50,7 @@ func (enc *Encoder) popWriter() {
} }
func (enc *Encoder) badType(rt reflect.Type) { func (enc *Encoder) badType(rt reflect.Type) {
enc.setError(os.ErrorString("gob: can't encode type " + rt.String())) enc.setError(os.NewError("gob: can't encode type " + rt.String()))
} }
func (enc *Encoder) setError(err os.Error) { func (enc *Encoder) setError(err os.Error) {

View File

@ -343,20 +343,20 @@ func (exp *Exporter) Sync(timeout int64) os.Error {
func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) { func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) {
chanType := reflect.TypeOf(chT) chanType := reflect.TypeOf(chT)
if chanType.Kind() != reflect.Chan { if chanType.Kind() != reflect.Chan {
return reflect.Value{}, os.ErrorString("not a channel") return reflect.Value{}, os.NewError("not a channel")
} }
if dir != Send && dir != Recv { if dir != Send && dir != Recv {
return reflect.Value{}, os.ErrorString("unknown channel direction") return reflect.Value{}, os.NewError("unknown channel direction")
} }
switch chanType.ChanDir() { switch chanType.ChanDir() {
case reflect.BothDir: case reflect.BothDir:
case reflect.SendDir: case reflect.SendDir:
if dir != Recv { if dir != Recv {
return reflect.Value{}, os.ErrorString("to import/export with Send, must provide <-chan") return reflect.Value{}, os.NewError("to import/export with Send, must provide <-chan")
} }
case reflect.RecvDir: case reflect.RecvDir:
if dir != Send { if dir != Send {
return reflect.Value{}, os.ErrorString("to import/export with Recv, must provide chan<-") return reflect.Value{}, os.NewError("to import/export with Recv, must provide chan<-")
} }
} }
return reflect.ValueOf(chT), nil return reflect.ValueOf(chT), nil
@ -376,7 +376,7 @@ func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error {
defer exp.mu.Unlock() defer exp.mu.Unlock()
_, present := exp.names[name] _, present := exp.names[name]
if present { if present {
return os.ErrorString("channel name already being exported:" + name) return os.NewError("channel name already being exported:" + name)
} }
exp.names[name] = &chanDir{ch, dir} exp.names[name] = &chanDir{ch, dir}
return nil return nil
@ -393,7 +393,7 @@ func (exp *Exporter) Hangup(name string) os.Error {
// TODO drop all instances of channel from client sets // TODO drop all instances of channel from client sets
exp.mu.Unlock() exp.mu.Unlock()
if !ok { if !ok {
return os.ErrorString("netchan export: hangup: no such channel: " + name) return os.NewError("netchan export: hangup: no such channel: " + name)
} }
chDir.ch.Close() chDir.ch.Close()
return nil return nil

View File

@ -185,7 +185,7 @@ func Sprintf(format string, a ...interface{}) string {
// Errorf formats according to a format specifier and returns the string // Errorf formats according to a format specifier and returns the string
// converted to an os.ErrorString, which satisfies the os.Error interface. // converted to an os.ErrorString, which satisfies the os.Error interface.
func Errorf(format string, a ...interface{}) os.Error { func Errorf(format string, a ...interface{}) os.Error {
return os.ErrorString(Sprintf(format, a...)) return os.NewError(Sprintf(format, a...))
} }
// These routines do not take a format string // These routines do not take a format string

View File

@ -244,7 +244,7 @@ func (p *Parser) unmarshal(val reflect.Value, start *StartElement) os.Error {
switch v := val; v.Kind() { switch v := val; v.Kind() {
default: default:
return os.ErrorString("unknown type " + v.Type().String()) return os.NewError("unknown type " + v.Type().String())
case reflect.Slice: case reflect.Slice:
typ := v.Type() typ := v.Type()
@ -483,7 +483,7 @@ Loop:
case reflect.Invalid: case reflect.Invalid:
// Probably a comment, handled below // Probably a comment, handled below
default: default:
return os.ErrorString("cannot happen: unknown type " + t.Type().String()) return os.NewError("cannot happen: unknown type " + t.Type().String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if !getInt64() { if !getInt64() {
return err return err

View File

@ -167,7 +167,7 @@ type ssave struct {
// satisfies io.Reader. It will never be called when used as // satisfies io.Reader. It will never be called when used as
// intended, so there is no need to make it actually work. // intended, so there is no need to make it actually work.
func (s *ss) Read(buf []byte) (n int, err os.Error) { func (s *ss) Read(buf []byte) (n int, err os.Error) {
return 0, os.ErrorString("ScanState's Read should not be called. Use ReadRune") return 0, os.NewError("ScanState's Read should not be called. Use ReadRune")
} }
func (s *ss) ReadRune() (rune int, size int, err os.Error) { func (s *ss) ReadRune() (rune int, size int, err os.Error) {
@ -240,7 +240,7 @@ func (s *ss) error(err os.Error) {
} }
func (s *ss) errorString(err string) { func (s *ss) errorString(err string) {
panic(scanError{os.ErrorString(err)}) panic(scanError{os.NewError(err)})
} }
func (s *ss) Token(skipSpace bool, f func(int) bool) (tok []byte, err os.Error) { func (s *ss) Token(skipSpace bool, f func(int) bool) (tok []byte, err os.Error) {
@ -426,8 +426,8 @@ func (s *ss) typeError(field interface{}, expected string) {
s.errorString("expected field of type pointer to " + expected + "; found " + reflect.TypeOf(field).String()) s.errorString("expected field of type pointer to " + expected + "; found " + reflect.TypeOf(field).String())
} }
var complexError = os.ErrorString("syntax error scanning complex number") var complexError = os.NewError("syntax error scanning complex number")
var boolError = os.ErrorString("syntax error scanning boolean") var boolError = os.NewError("syntax error scanning boolean")
// consume reads the next rune in the input and reports whether it is in the ok string. // 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. // If accept is true, it puts the character into the input token.

View File

@ -67,7 +67,7 @@ func validUserType(rt reflect.Type) (ut *userTypeInfo, err os.Error) {
ut.base = pt.Elem() ut.base = pt.Elem()
if ut.base == slowpoke { // ut.base lapped slowpoke if ut.base == slowpoke { // ut.base lapped slowpoke
// recursive pointer type. // recursive pointer type.
return nil, os.ErrorString("can't represent recursive pointer type " + ut.base.String()) return nil, os.NewError("can't represent recursive pointer type " + ut.base.String())
} }
if ut.indir%2 == 0 { if ut.indir%2 == 0 {
slowpoke = slowpoke.Elem() slowpoke = slowpoke.Elem()
@ -524,7 +524,7 @@ func newTypeObject(name string, ut *userTypeInfo, rt reflect.Type) (gobType, os.
return st, nil return st, nil
default: default:
return nil, os.ErrorString("gob NewTypeObject can't handle type: " + rt.String()) return nil, os.NewError("gob NewTypeObject can't handle type: " + rt.String())
} }
return nil, nil return nil, nil
} }

View File

@ -160,14 +160,14 @@ func isRemote(pkg string) bool {
// download checks out or updates pkg from the remote server. // download checks out or updates pkg from the remote server.
func download(pkg, srcDir string) os.Error { func download(pkg, srcDir string) os.Error {
if strings.Contains(pkg, "..") { if strings.Contains(pkg, "..") {
return os.ErrorString("invalid path (contains ..)") return os.NewError("invalid path (contains ..)")
} }
var m *vcsMatch var m *vcsMatch
for _, v := range vcsList { for _, v := range vcsList {
for _, host := range v.defaultHosts { for _, host := range v.defaultHosts {
if hm := host.pattern.FindStringSubmatch(pkg); hm != nil { if hm := host.pattern.FindStringSubmatch(pkg); hm != nil {
if v.suffix != "" && strings.HasSuffix(hm[1], v.suffix) { if v.suffix != "" && strings.HasSuffix(hm[1], v.suffix) {
return os.ErrorString("repository " + pkg + " should not have " + v.suffix + " suffix") return os.NewError("repository " + pkg + " should not have " + v.suffix + " suffix")
} }
repo := host.protocol + "://" + hm[1] + v.suffix repo := host.protocol + "://" + hm[1] + v.suffix
m = &vcsMatch{v, hm[1], repo} m = &vcsMatch{v, hm[1], repo}
@ -175,7 +175,7 @@ func download(pkg, srcDir string) os.Error {
} }
} }
if m == nil { if m == nil {
return os.ErrorString("cannot download: " + pkg) return os.NewError("cannot download: " + pkg)
} }
return vcsCheckout(m.vcs, srcDir, m.prefix, m.repo, pkg) return vcsCheckout(m.vcs, srcDir, m.prefix, m.repo, pkg)
} }
@ -205,7 +205,7 @@ func vcsCheckout(vcs *vcs, srcDir, pkgprefix, repo, dashpath string) os.Error {
dst := filepath.Join(srcDir, filepath.FromSlash(pkgprefix)) dst := filepath.Join(srcDir, filepath.FromSlash(pkgprefix))
dir, err := os.Stat(filepath.Join(dst, vcs.metadir)) dir, err := os.Stat(filepath.Join(dst, vcs.metadir))
if err == nil && !dir.IsDirectory() { if err == nil && !dir.IsDirectory() {
return os.ErrorString("not a directory: " + dst) return os.NewError("not a directory: " + dst)
} }
if err != nil { if err != nil {
parent, _ := filepath.Split(dst) parent, _ := filepath.Split(dst)

View File

@ -279,7 +279,7 @@ func genRun(dir string, stdin []byte, arg []string, quiet bool) os.Error {
os.Stderr.Write(out) os.Stderr.Write(out)
fmt.Fprintf(os.Stderr, "--- %s\n", err) fmt.Fprintf(os.Stderr, "--- %s\n", err)
} }
return os.ErrorString("running " + arg[0] + ": " + err.String()) return os.NewError("running " + arg[0] + ": " + err.String())
} }
return nil return nil
} }

View File

@ -114,7 +114,7 @@ func parseFiles(fset *token.FileSet, filenames []string) (files map[string]*ast.
} }
if file := parse(fset, filename, src); file != nil { if file := parse(fset, filename, src); file != nil {
if files[filename] != nil { if files[filename] != nil {
report(os.ErrorString(fmt.Sprintf("%q: duplicate file", filename))) report(os.NewError(fmt.Sprintf("%q: duplicate file", filename)))
continue continue
} }
files[filename] = file files[filename] = file

View File

@ -16,7 +16,7 @@ import (
) )
var ( var (
HeaderError os.Error = os.ErrorString("invalid tar header") HeaderError = os.NewError("invalid tar header")
) )
// A Reader provides sequential access to the contents of a tar archive. // A Reader provides sequential access to the contents of a tar archive.

View File

@ -430,7 +430,7 @@ func (z *Int) Scan(s fmt.ScanState, ch int) os.Error {
case 's', 'v': case 's', 'v':
// let scan determine the base // let scan determine the base
default: default:
return os.ErrorString("Int.Scan: invalid verb") return os.NewError("Int.Scan: invalid verb")
} }
_, _, err := z.scan(s, base) _, _, err := z.scan(s, base)
return err return err
@ -834,11 +834,11 @@ func (z *Int) GobEncode() ([]byte, os.Error) {
// GobDecode implements the gob.GobDecoder interface. // GobDecode implements the gob.GobDecoder interface.
func (z *Int) GobDecode(buf []byte) os.Error { func (z *Int) GobDecode(buf []byte) os.Error {
if len(buf) == 0 { if len(buf) == 0 {
return os.ErrorString("Int.GobDecode: no data") return os.NewError("Int.GobDecode: no data")
} }
b := buf[0] b := buf[0]
if b>>1 != intGobVersion { if b>>1 != intGobVersion {
return os.ErrorString(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1)) return os.NewError(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1))
} }
z.neg = b&1 != 0 z.neg = b&1 != 0
z.abs = z.abs.setBytes(buf[1:]) z.abs = z.abs.setBytes(buf[1:])

View File

@ -644,7 +644,7 @@ func hexValue(ch int) Word {
func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) { func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
// reject illegal bases // reject illegal bases
if base < 0 || base == 1 || MaxBase < base { if base < 0 || base == 1 || MaxBase < base {
return z, 0, os.ErrorString("illegal number base") return z, 0, os.NewError("illegal number base")
} }
// one char look-ahead // one char look-ahead
@ -721,7 +721,7 @@ func (z nat) scan(r io.RuneScanner, base int) (nat, int, os.Error) {
return z, 10, nil return z, 10, nil
case base != 0 || b != 8: case base != 0 || b != 8:
// there was neither a mantissa digit nor the octal prefix 0 // there was neither a mantissa digit nor the octal prefix 0
return z, int(b), os.ErrorString("syntax error scanning number") return z, int(b), os.NewError("syntax error scanning number")
} }
return z.norm(), int(b), nil return z.norm(), int(b), nil

View File

@ -227,10 +227,10 @@ func (z *Rat) Scan(s fmt.ScanState, ch int) os.Error {
return err return err
} }
if strings.IndexRune("efgEFGv", ch) < 0 { if strings.IndexRune("efgEFGv", ch) < 0 {
return os.ErrorString("Rat.Scan: invalid verb") return os.NewError("Rat.Scan: invalid verb")
} }
if _, ok := z.SetString(string(tok)); !ok { if _, ok := z.SetString(string(tok)); !ok {
return os.ErrorString("Rat.Scan: invalid syntax") return os.NewError("Rat.Scan: invalid syntax")
} }
return nil return nil
} }
@ -368,7 +368,7 @@ func (z *Rat) GobEncode() ([]byte, os.Error) {
n := i - j n := i - j
if int(uint32(n)) != n { if int(uint32(n)) != n {
// this should never happen // this should never happen
return nil, os.ErrorString("Rat.GobEncode: numerator too large") return nil, os.NewError("Rat.GobEncode: numerator too large")
} }
binary.BigEndian.PutUint32(buf[j-4:j], uint32(n)) binary.BigEndian.PutUint32(buf[j-4:j], uint32(n))
j -= 1 + 4 j -= 1 + 4
@ -384,11 +384,11 @@ func (z *Rat) GobEncode() ([]byte, os.Error) {
// GobDecode implements the gob.GobDecoder interface. // GobDecode implements the gob.GobDecoder interface.
func (z *Rat) GobDecode(buf []byte) os.Error { func (z *Rat) GobDecode(buf []byte) os.Error {
if len(buf) == 0 { if len(buf) == 0 {
return os.ErrorString("Rat.GobDecode: no data") return os.NewError("Rat.GobDecode: no data")
} }
b := buf[0] b := buf[0]
if b>>1 != ratGobVersion { if b>>1 != ratGobVersion {
return os.ErrorString(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1)) return os.NewError(fmt.Sprintf("Rat.GobDecode: encoding version %d not supported", b>>1))
} }
const j = 1 + 4 const j = 1 + 4
i := j + binary.BigEndian.Uint32(buf[j-4:j]) i := j + binary.BigEndian.Uint32(buf[j-4:j])

View File

@ -22,9 +22,11 @@ const (
// Errors introduced by this package. // Errors introduced by this package.
type Error struct { type Error struct {
os.ErrorString ErrorString string
} }
func (err *Error) String() string { return err.ErrorString }
var ( var (
ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"} ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"}
ErrInvalidUnreadRune os.Error = &Error{"bufio: invalid use of UnreadRune"} ErrInvalidUnreadRune os.Error = &Error{"bufio: invalid use of UnreadRune"}

View File

@ -280,7 +280,7 @@ func (b *Buffer) ReadRune() (r int, size int, err os.Error) {
// from any read operation.) // from any read operation.)
func (b *Buffer) UnreadRune() os.Error { func (b *Buffer) UnreadRune() os.Error {
if b.lastRead != opReadRune { if b.lastRead != opReadRune {
return os.ErrorString("bytes.Buffer: UnreadRune: previous operation was not ReadRune") return os.NewError("bytes.Buffer: UnreadRune: previous operation was not ReadRune")
} }
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off > 0 { if b.off > 0 {
@ -295,7 +295,7 @@ func (b *Buffer) UnreadRune() os.Error {
// returns an error. // returns an error.
func (b *Buffer) UnreadByte() os.Error { func (b *Buffer) UnreadByte() os.Error {
if b.lastRead != opReadRune && b.lastRead != opRead { if b.lastRead != opReadRune && b.lastRead != opRead {
return os.ErrorString("bytes.Buffer: UnreadByte: previous operation was not a read") return os.NewError("bytes.Buffer: UnreadByte: previous operation was not a read")
} }
b.lastRead = opInvalid b.lastRead = opInvalid
if b.off > 0 { if b.off > 0 {

View File

@ -36,8 +36,8 @@ func makeReader(r io.Reader) flate.Reader {
return bufio.NewReader(r) return bufio.NewReader(r)
} }
var HeaderError os.Error = os.ErrorString("invalid gzip header") var HeaderError = os.NewError("invalid gzip header")
var ChecksumError os.Error = os.ErrorString("gzip checksum error") var ChecksumError = os.NewError("gzip checksum error")
// The gzip file stores a header giving metadata about the compressed file. // The gzip file stores a header giving metadata about the compressed file.
// That header is exposed as the fields of the Compressor and Decompressor structs. // That header is exposed as the fields of the Compressor and Decompressor structs.

View File

@ -34,9 +34,9 @@ import (
const zlibDeflate = 8 const zlibDeflate = 8
var ChecksumError os.Error = os.ErrorString("zlib checksum error") var ChecksumError = os.NewError("zlib checksum error")
var HeaderError os.Error = os.ErrorString("invalid zlib header") var HeaderError = os.NewError("invalid zlib header")
var DictionaryError os.Error = os.ErrorString("invalid zlib dictionary") var DictionaryError = os.NewError("invalid zlib dictionary")
type reader struct { type reader struct {
r flate.Reader r flate.Reader

View File

@ -20,7 +20,7 @@ type Cipher struct {
func NewCipher(key []byte) (c *Cipher, err os.Error) { func NewCipher(key []byte) (c *Cipher, err os.Error) {
if len(key) != KeySize { if len(key) != KeySize {
return nil, os.ErrorString("CAST5: keys must be 16 bytes") return nil, os.NewError("CAST5: keys must be 16 bytes")
} }
c = new(Cipher) c = new(Cipher)

View File

@ -79,7 +79,7 @@ func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes
L = 3072 L = 3072
N = 256 N = 256
default: default:
return os.ErrorString("crypto/dsa: invalid ParameterSizes") return os.NewError("crypto/dsa: invalid ParameterSizes")
} }
qBytes := make([]byte, N/8) qBytes := make([]byte, N/8)
@ -158,7 +158,7 @@ GeneratePrimes:
// PrivateKey must already be valid (see GenerateParameters). // PrivateKey must already be valid (see GenerateParameters).
func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error { func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error {
if priv.P == nil || priv.Q == nil || priv.G == nil { if priv.P == nil || priv.Q == nil || priv.G == nil {
return os.ErrorString("crypto/dsa: parameters not set up before generating key") return os.NewError("crypto/dsa: parameters not set up before generating key")
} }
x := new(big.Int) x := new(big.Int)

View File

@ -37,7 +37,7 @@ type PrivateKey struct {
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 os.Error) {
pLen := (pub.P.BitLen() + 7) / 8 pLen := (pub.P.BitLen() + 7) / 8
if len(msg) > pLen-11 { if len(msg) > pLen-11 {
err = os.ErrorString("elgamal: message too long") err = os.NewError("elgamal: message too long")
return return
} }
@ -97,7 +97,7 @@ func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err os.Error) {
} }
if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 {
return nil, os.ErrorString("elgamal: decryption error") return nil, os.NewError("elgamal: decryption error")
} }
return em[index+1:], nil return em[index+1:], nil
} }

View File

@ -232,11 +232,11 @@ func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte)
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 os.Error) {
hashLen = hash.Size() hashLen = hash.Size()
if inLen != hashLen { if inLen != hashLen {
return 0, nil, os.ErrorString("input must be hashed message") return 0, nil, os.NewError("input must be hashed message")
} }
prefix, ok := hashPrefixes[hash] prefix, ok := hashPrefixes[hash]
if !ok { if !ok {
return 0, nil, os.ErrorString("unsupported hash function") return 0, nil, os.NewError("unsupported hash function")
} }
return return
} }

View File

@ -64,7 +64,7 @@ func (priv *PrivateKey) Validate() os.Error {
// easy for an attack to generate composites that pass this test. // easy for an attack to generate composites that pass this test.
for _, prime := range priv.Primes { for _, prime := range priv.Primes {
if !big.ProbablyPrime(prime, 20) { if !big.ProbablyPrime(prime, 20) {
return os.ErrorString("prime factor is composite") return os.NewError("prime factor is composite")
} }
} }
@ -74,7 +74,7 @@ func (priv *PrivateKey) Validate() os.Error {
modulus.Mul(modulus, prime) modulus.Mul(modulus, prime)
} }
if modulus.Cmp(priv.N) != 0 { if modulus.Cmp(priv.N) != 0 {
return os.ErrorString("invalid modulus") return os.NewError("invalid modulus")
} }
// Check that e and totient(Πprimes) are coprime. // Check that e and totient(Πprimes) are coprime.
totient := new(big.Int).Set(bigOne) totient := new(big.Int).Set(bigOne)
@ -88,13 +88,13 @@ func (priv *PrivateKey) Validate() os.Error {
y := new(big.Int) y := new(big.Int)
big.GcdInt(gcd, x, y, totient, e) big.GcdInt(gcd, x, y, totient, e)
if gcd.Cmp(bigOne) != 0 { if gcd.Cmp(bigOne) != 0 {
return os.ErrorString("invalid public exponent E") return os.NewError("invalid public exponent E")
} }
// Check that de ≡ 1 (mod totient(Πprimes)) // Check that de ≡ 1 (mod totient(Πprimes))
de := new(big.Int).Mul(priv.D, e) de := new(big.Int).Mul(priv.D, e)
de.Mod(de, totient) de.Mod(de, totient)
if de.Cmp(bigOne) != 0 { if de.Cmp(bigOne) != 0 {
return os.ErrorString("invalid private exponent D") return os.NewError("invalid private exponent D")
} }
return nil return nil
} }
@ -127,7 +127,7 @@ func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *Priva
priv.E = 3 priv.E = 3
if nprimes < 2 { if nprimes < 2 {
return nil, os.ErrorString("rsa.GenerateMultiPrimeKey: nprimes must be >= 2") return nil, os.NewError("rsa.GenerateMultiPrimeKey: nprimes must be >= 2")
} }
primes := make([]*big.Int, nprimes) primes := make([]*big.Int, nprimes)

View File

@ -790,10 +790,10 @@ func (c *Conn) VerifyHostname(host string) os.Error {
c.handshakeMutex.Lock() c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock() defer c.handshakeMutex.Unlock()
if !c.isClient { if !c.isClient {
return os.ErrorString("VerifyHostname called on TLS server connection") return os.NewError("VerifyHostname called on TLS server connection")
} }
if !c.handshakeComplete { if !c.handshakeComplete {
return os.ErrorString("TLS handshake has not yet been performed") return os.NewError("TLS handshake has not yet been performed")
} }
return c.peerCertificates[0].VerifyHostname(host) return c.peerCertificates[0].VerifyHostname(host)
} }

View File

@ -40,7 +40,7 @@ func (c *Conn) clientHandshake() os.Error {
_, err := io.ReadFull(c.config.rand(), hello.random[4:]) _, err := io.ReadFull(c.config.rand(), hello.random[4:])
if err != nil { if err != nil {
c.sendAlert(alertInternalError) c.sendAlert(alertInternalError)
return os.ErrorString("short read from Rand") return os.NewError("short read from Rand")
} }
finishedHash.Write(hello.marshal()) finishedHash.Write(hello.marshal())
@ -69,7 +69,7 @@ func (c *Conn) clientHandshake() os.Error {
if !hello.nextProtoNeg && serverHello.nextProtoNeg { if !hello.nextProtoNeg && serverHello.nextProtoNeg {
c.sendAlert(alertHandshakeFailure) c.sendAlert(alertHandshakeFailure)
return os.ErrorString("server advertised unrequested NPN") return os.NewError("server advertised unrequested NPN")
} }
suite, suiteId := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite) suite, suiteId := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
@ -92,7 +92,7 @@ func (c *Conn) clientHandshake() os.Error {
cert, err := x509.ParseCertificate(asn1Data) cert, err := x509.ParseCertificate(asn1Data)
if err != nil { if err != nil {
c.sendAlert(alertBadCertificate) c.sendAlert(alertBadCertificate)
return os.ErrorString("failed to parse certificate from server: " + err.String()) return os.NewError("failed to parse certificate from server: " + err.String())
} }
certs[i] = cert certs[i] = cert
} }

View File

@ -173,7 +173,7 @@ FindCipherSuite:
cert, err := x509.ParseCertificate(asn1Data) cert, err := x509.ParseCertificate(asn1Data)
if err != nil { if err != nil {
c.sendAlert(alertBadCertificate) c.sendAlert(alertBadCertificate)
return os.ErrorString("could not parse client's certificate: " + err.String()) return os.NewError("could not parse client's certificate: " + err.String())
} }
certs[i] = cert certs[i] = cert
} }
@ -182,7 +182,7 @@ FindCipherSuite:
for i := 1; i < len(certs); i++ { for i := 1; i < len(certs); i++ {
if err := certs[i-1].CheckSignatureFrom(certs[i]); err != nil { if err := certs[i-1].CheckSignatureFrom(certs[i]); err != nil {
c.sendAlert(alertBadCertificate) c.sendAlert(alertBadCertificate)
return os.ErrorString("could not validate certificate signature: " + err.String()) return os.NewError("could not validate certificate signature: " + err.String())
} }
} }
@ -229,7 +229,7 @@ FindCipherSuite:
err = rsa.VerifyPKCS1v15(pub, crypto.MD5SHA1, digest, certVerify.signature) err = rsa.VerifyPKCS1v15(pub, crypto.MD5SHA1, digest, certVerify.signature)
if err != nil { if err != nil {
c.sendAlert(alertBadCertificate) c.sendAlert(alertBadCertificate)
return os.ErrorString("could not validate signature of connection nonces: " + err.String()) return os.NewError("could not validate signature of connection nonces: " + err.String())
} }
finishedHash.Write(certVerify.marshal()) finishedHash.Write(certVerify.marshal())

View File

@ -32,11 +32,11 @@ func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKe
} }
if len(ckx.ciphertext) < 2 { if len(ckx.ciphertext) < 2 {
return nil, os.ErrorString("bad ClientKeyExchange") return nil, os.NewError("bad ClientKeyExchange")
} }
ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1]) ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
if ciphertextLen != len(ckx.ciphertext)-2 { if ciphertextLen != len(ckx.ciphertext)-2 {
return nil, os.ErrorString("bad ClientKeyExchange") return nil, os.NewError("bad ClientKeyExchange")
} }
ciphertext := ckx.ciphertext[2:] ciphertext := ckx.ciphertext[2:]
@ -54,7 +54,7 @@ func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKe
} }
func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) os.Error { func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) os.Error {
return os.ErrorString("unexpected ServerKeyExchange") return os.NewError("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, os.Error) {
@ -146,7 +146,7 @@ Curve:
md5sha1 := md5SHA1Hash(clientHello.random, hello.random, serverECDHParams) md5sha1 := md5SHA1Hash(clientHello.random, hello.random, serverECDHParams)
sig, err := rsa.SignPKCS1v15(config.rand(), config.Certificates[0].PrivateKey, crypto.MD5SHA1, md5sha1) sig, err := rsa.SignPKCS1v15(config.rand(), config.Certificates[0].PrivateKey, crypto.MD5SHA1, md5sha1)
if err != nil { if err != nil {
return nil, os.ErrorString("failed to sign ECDHE parameters: " + err.String()) return nil, os.NewError("failed to sign ECDHE parameters: " + err.String())
} }
skx := new(serverKeyExchangeMsg) skx := new(serverKeyExchangeMsg)
@ -162,11 +162,11 @@ Curve:
func (ka *ecdheRSAKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg) ([]byte, os.Error) { func (ka *ecdheRSAKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg) ([]byte, os.Error) {
if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 { if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
return nil, os.ErrorString("bad ClientKeyExchange") return nil, os.NewError("bad ClientKeyExchange")
} }
x, y := ka.curve.Unmarshal(ckx.ciphertext[1:]) x, y := ka.curve.Unmarshal(ckx.ciphertext[1:])
if x == nil { if x == nil {
return nil, os.ErrorString("bad ClientKeyExchange") return nil, os.NewError("bad ClientKeyExchange")
} }
x, _ = ka.curve.ScalarMult(x, y, ka.privateKey) x, _ = ka.curve.ScalarMult(x, y, ka.privateKey)
preMasterSecret := make([]byte, (ka.curve.BitSize+7)>>3) preMasterSecret := make([]byte, (ka.curve.BitSize+7)>>3)
@ -176,14 +176,14 @@ func (ka *ecdheRSAKeyAgreement) processClientKeyExchange(config *Config, ckx *cl
return preMasterSecret, nil return preMasterSecret, nil
} }
var errServerKeyExchange = os.ErrorString("invalid ServerKeyExchange") var errServerKeyExchange = os.NewError("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) os.Error {
if len(skx.key) < 4 { if len(skx.key) < 4 {
return errServerKeyExchange return errServerKeyExchange
} }
if skx.key[0] != 3 { // named curve if skx.key[0] != 3 { // named curve
return os.ErrorString("server selected unsupported curve") return os.NewError("server selected unsupported curve")
} }
curveid := uint16(skx.key[1])<<8 | uint16(skx.key[2]) curveid := uint16(skx.key[1])<<8 | uint16(skx.key[2])
@ -195,7 +195,7 @@ func (ka *ecdheRSAKeyAgreement) processServerKeyExchange(config *Config, clientH
case curveP521: case curveP521:
ka.curve = elliptic.P521() ka.curve = elliptic.P521()
default: default:
return os.ErrorString("server selected unsupported curve") return os.NewError("server selected unsupported curve")
} }
publicLen := int(skx.key[3]) publicLen := int(skx.key[3])
@ -224,7 +224,7 @@ func (ka *ecdheRSAKeyAgreement) processServerKeyExchange(config *Config, clientH
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, os.Error) {
if ka.curve == nil { if ka.curve == nil {
return nil, nil, os.ErrorString("missing ServerKeyExchange message") return nil, nil, os.NewError("missing ServerKeyExchange message")
} }
priv, mx, my, err := ka.curve.GenerateKey(config.rand()) priv, mx, my, err := ka.curve.GenerateKey(config.rand())
if err != nil { if err != nil {

View File

@ -147,19 +147,19 @@ func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err os.Err
} }
if len(cert.Certificate) == 0 { if len(cert.Certificate) == 0 {
err = os.ErrorString("crypto/tls: failed to parse certificate PEM data") err = os.NewError("crypto/tls: failed to parse certificate PEM data")
return return
} }
keyDERBlock, _ := pem.Decode(keyPEMBlock) keyDERBlock, _ := pem.Decode(keyPEMBlock)
if keyDERBlock == nil { if keyDERBlock == nil {
err = os.ErrorString("crypto/tls: failed to parse key PEM data") err = os.NewError("crypto/tls: failed to parse key PEM data")
return return
} }
key, err := x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes) key, err := x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes)
if err != nil { if err != nil {
err = os.ErrorString("crypto/tls: failed to parse key: " + err.String()) err = os.NewError("crypto/tls: failed to parse key: " + err.String())
return return
} }
@ -173,7 +173,7 @@ func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err os.Err
} }
if x509Cert.PublicKeyAlgorithm != x509.RSA || x509Cert.PublicKey.(*rsa.PublicKey).N.Cmp(key.PublicKey.N) != 0 { if x509Cert.PublicKeyAlgorithm != x509.RSA || x509Cert.PublicKey.(*rsa.PublicKey).N.Cmp(key.PublicKey.N) != 0 {
err = os.ErrorString("crypto/tls: private key does not match public key") err = os.NewError("crypto/tls: private key does not match public key")
return return
} }

View File

@ -120,7 +120,7 @@ func expectAuthorityUnknown(t *testing.T, i int, err os.Error) (ok bool) {
func certificateFromPEM(pemBytes string) (*Certificate, os.Error) { func certificateFromPEM(pemBytes string) (*Certificate, os.Error) {
block, _ := pem.Decode([]byte(pemBytes)) block, _ := pem.Decode([]byte(pemBytes))
if block == nil { if block == nil {
return nil, os.ErrorString("failed to decode PEM") return nil, os.NewError("failed to decode PEM")
} }
return ParseCertificate(block.Bytes) return ParseCertificate(block.Bytes)
} }

View File

@ -58,11 +58,11 @@ func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
} }
if priv.Version > 1 { if priv.Version > 1 {
return nil, os.ErrorString("x509: unsupported private key version") return nil, os.NewError("x509: unsupported private key version")
} }
if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 { if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 {
return nil, os.ErrorString("private key contains zero or negative value") return nil, os.NewError("private key contains zero or negative value")
} }
key = new(rsa.PrivateKey) key = new(rsa.PrivateKey)
@ -77,7 +77,7 @@ func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
key.Primes[1] = priv.Q key.Primes[1] = priv.Q
for i, a := range priv.AdditionalPrimes { for i, a := range priv.AdditionalPrimes {
if a.Prime.Sign() <= 0 { if a.Prime.Sign() <= 0 {
return nil, os.ErrorString("private key contains zero or negative prime") return nil, os.NewError("private key contains zero or negative prime")
} }
key.Primes[i+2] = a.Prime key.Primes[i+2] = a.Prime
// We ignore the other two values because rsa will calculate // We ignore the other two values because rsa will calculate
@ -457,10 +457,10 @@ func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature
return err return err
} }
if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
return os.ErrorString("DSA signature contained zero or negative values") return os.NewError("DSA signature contained zero or negative values")
} }
if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) { if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
return os.ErrorString("DSA verification failure") return os.NewError("DSA verification failure")
} }
return return
} }
@ -535,7 +535,7 @@ func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{
return nil, err return nil, err
} }
if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
return nil, os.ErrorString("zero or negative DSA parameter") return nil, os.NewError("zero or negative DSA parameter")
} }
pub := &dsa.PublicKey{ pub := &dsa.PublicKey{
Parameters: dsa.Parameters{ Parameters: dsa.Parameters{
@ -571,7 +571,7 @@ func parseCertificate(in *certificate) (*Certificate, os.Error) {
} }
if in.TBSCertificate.SerialNumber.Sign() < 0 { if in.TBSCertificate.SerialNumber.Sign() < 0 {
return nil, os.ErrorString("negative serial number") return nil, os.NewError("negative serial number")
} }
out.Version = in.TBSCertificate.Version + 1 out.Version = in.TBSCertificate.Version + 1

View File

@ -81,7 +81,7 @@ func (s *Section) Data() ([]byte, os.Error) {
// specified link value. // specified link value.
func (f *File) stringTable(link uint32) ([]byte, os.Error) { func (f *File) stringTable(link uint32) ([]byte, os.Error) {
if link <= 0 || link >= uint32(len(f.Sections)) { if link <= 0 || link >= uint32(len(f.Sections)) {
return nil, os.ErrorString("section has invalid string table link") return nil, os.NewError("section has invalid string table link")
} }
return f.Sections[link].Data() return f.Sections[link].Data()
} }
@ -341,27 +341,27 @@ func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, os.Error) {
return f.getSymbols32(typ) return f.getSymbols32(typ)
} }
return nil, nil, os.ErrorString("not implemented") return nil, nil, os.NewError("not implemented")
} }
func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, os.Error) { func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, os.Error) {
symtabSection := f.SectionByType(typ) symtabSection := f.SectionByType(typ)
if symtabSection == nil { if symtabSection == nil {
return nil, nil, os.ErrorString("no symbol section") return nil, nil, os.NewError("no symbol section")
} }
data, err := symtabSection.Data() data, err := symtabSection.Data()
if err != nil { if err != nil {
return nil, nil, os.ErrorString("cannot load symbol section") return nil, nil, os.NewError("cannot load symbol section")
} }
symtab := bytes.NewBuffer(data) symtab := bytes.NewBuffer(data)
if symtab.Len()%Sym32Size != 0 { if symtab.Len()%Sym32Size != 0 {
return nil, nil, os.ErrorString("length of symbol section is not a multiple of SymSize") return nil, nil, os.NewError("length of symbol section is not a multiple of SymSize")
} }
strdata, err := f.stringTable(symtabSection.Link) strdata, err := f.stringTable(symtabSection.Link)
if err != nil { if err != nil {
return nil, nil, os.ErrorString("cannot load string table section") return nil, nil, os.NewError("cannot load string table section")
} }
// The first entry is all zeros. // The first entry is all zeros.
@ -390,21 +390,21 @@ func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, os.Error) {
func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, os.Error) { func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, os.Error) {
symtabSection := f.SectionByType(typ) symtabSection := f.SectionByType(typ)
if symtabSection == nil { if symtabSection == nil {
return nil, nil, os.ErrorString("no symbol section") return nil, nil, os.NewError("no symbol section")
} }
data, err := symtabSection.Data() data, err := symtabSection.Data()
if err != nil { if err != nil {
return nil, nil, os.ErrorString("cannot load symbol section") return nil, nil, os.NewError("cannot load symbol section")
} }
symtab := bytes.NewBuffer(data) symtab := bytes.NewBuffer(data)
if symtab.Len()%Sym64Size != 0 { if symtab.Len()%Sym64Size != 0 {
return nil, nil, os.ErrorString("length of symbol section is not a multiple of Sym64Size") return nil, nil, os.NewError("length of symbol section is not a multiple of Sym64Size")
} }
strdata, err := f.stringTable(symtabSection.Link) strdata, err := f.stringTable(symtabSection.Link)
if err != nil { if err != nil {
return nil, nil, os.ErrorString("cannot load string table section") return nil, nil, os.NewError("cannot load string table section")
} }
// The first entry is all zeros. // The first entry is all zeros.
@ -462,12 +462,12 @@ func (f *File) applyRelocations(dst []byte, rels []byte) os.Error {
return f.applyRelocationsAMD64(dst, rels) return f.applyRelocationsAMD64(dst, rels)
} }
return os.ErrorString("not implemented") return os.NewError("not implemented")
} }
func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) os.Error { func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) os.Error {
if len(rels)%Sym64Size != 0 { if len(rels)%Sym64Size != 0 {
return os.ErrorString("length of relocation section is not a multiple of Sym64Size") return os.NewError("length of relocation section is not a multiple of Sym64Size")
} }
symbols, _, err := f.getSymbols(SHT_SYMTAB) symbols, _, err := f.getSymbols(SHT_SYMTAB)

View File

@ -10,7 +10,7 @@ import (
) )
// ErrNotFound is the error resulting if a path search failed to find an executable file. // ErrNotFound is the error resulting if a path search failed to find an executable file.
var ErrNotFound = os.ErrorString("executable file not found in $path") var ErrNotFound = os.NewError("executable file not found in $path")
func findExecutable(file string) os.Error { func findExecutable(file string) os.Error {
d, err := os.Stat(file) d, err := os.Stat(file)

View File

@ -10,7 +10,7 @@ import (
) )
// ErrNotFound is the error resulting if a path search failed to find an executable file. // ErrNotFound is the error resulting if a path search failed to find an executable file.
var ErrNotFound = os.ErrorString("executable file not found in $PATH") var ErrNotFound = os.NewError("executable file not found in $PATH")
func findExecutable(file string) os.Error { func findExecutable(file string) os.Error {
d, err := os.Stat(file) d, err := os.Stat(file)

View File

@ -10,7 +10,7 @@ import (
) )
// ErrNotFound is the error resulting if a path search failed to find an executable file. // ErrNotFound is the error resulting if a path search failed to find an executable file.
var ErrNotFound = os.ErrorString("executable file not found in %PATH%") var ErrNotFound = os.NewError("executable file not found in %PATH%")
func chkStat(file string) os.Error { func chkStat(file string) os.Error {
d, err := os.Stat(file) d, err := os.Stat(file)

View File

@ -189,7 +189,7 @@ func Sprintf(format string, a ...interface{}) string {
// Errorf formats according to a format specifier and returns the string // Errorf formats according to a format specifier and returns the string
// converted to an os.ErrorString, which satisfies the os.Error interface. // converted to an os.ErrorString, which satisfies the os.Error interface.
func Errorf(format string, a ...interface{}) os.Error { func Errorf(format string, a ...interface{}) os.Error {
return os.ErrorString(Sprintf(format, a...)) return os.NewError(Sprintf(format, a...))
} }
// These routines do not take a format string // These routines do not take a format string

View File

@ -167,7 +167,7 @@ type ssave struct {
// satisfies io.Reader. It will never be called when used as // satisfies io.Reader. It will never be called when used as
// intended, so there is no need to make it actually work. // intended, so there is no need to make it actually work.
func (s *ss) Read(buf []byte) (n int, err os.Error) { func (s *ss) Read(buf []byte) (n int, err os.Error) {
return 0, os.ErrorString("ScanState's Read should not be called. Use ReadRune") return 0, os.NewError("ScanState's Read should not be called. Use ReadRune")
} }
func (s *ss) ReadRune() (rune int, size int, err os.Error) { func (s *ss) ReadRune() (rune int, size int, err os.Error) {
@ -241,7 +241,7 @@ func (s *ss) error(err os.Error) {
} }
func (s *ss) errorString(err string) { func (s *ss) errorString(err string) {
panic(scanError{os.ErrorString(err)}) panic(scanError{os.NewError(err)})
} }
func (s *ss) Token(skipSpace bool, f func(int) bool) (tok []byte, err os.Error) { func (s *ss) Token(skipSpace bool, f func(int) bool) (tok []byte, err os.Error) {
@ -427,8 +427,8 @@ func (s *ss) typeError(field interface{}, expected string) {
s.errorString("expected field of type pointer to " + expected + "; found " + reflect.TypeOf(field).String()) s.errorString("expected field of type pointer to " + expected + "; found " + reflect.TypeOf(field).String())
} }
var complexError = os.ErrorString("syntax error scanning complex number") var complexError = os.NewError("syntax error scanning complex number")
var boolError = os.ErrorString("syntax error scanning boolean") var boolError = os.NewError("syntax error scanning boolean")
// consume reads the next rune in the input and reports whether it is in the ok string. // 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. // If accept is true, it puts the character into the input token.

View File

@ -94,7 +94,7 @@ func (x *Xs) Scan(state ScanState, verb int) os.Error {
} }
s := string(tok) s := string(tok)
if !regexp.MustCompile("^" + string(verb) + "+$").MatchString(s) { if !regexp.MustCompile("^" + string(verb) + "+$").MatchString(s) {
return os.ErrorString("syntax error for xs") return os.NewError("syntax error for xs")
} }
*x = Xs(s) *x = Xs(s)
return nil return nil
@ -818,7 +818,7 @@ func (r *RecursiveInt) Scan(state ScanState, verb int) (err os.Error) {
next := new(RecursiveInt) next := new(RecursiveInt)
_, err = Fscanf(state, ".%v", next) _, err = Fscanf(state, ".%v", next)
if err != nil { if err != nil {
if err == os.ErrorString("input does not match format") || err == io.ErrUnexpectedEOF { if err == os.NewError("input does not match format") || err == io.ErrUnexpectedEOF {
err = nil err = nil
} }
return return

View File

@ -98,7 +98,7 @@ func ScanDir(dir string, allowMain bool) (info *DirInfo, err os.Error) {
if s == "main" || di.PkgName == "main" { if s == "main" || di.PkgName == "main" {
return ScanDir(dir, false) return ScanDir(dir, false)
} }
return nil, os.ErrorString("multiple package names in " + dir) return nil, os.NewError("multiple package names in " + dir)
} }
isCgo := false isCgo := false
for _, spec := range pf.Imports { for _, spec := range pf.Imports {

View File

@ -42,7 +42,7 @@ func readSource(filename string, src interface{}) ([]byte, os.Error) {
} }
return buf.Bytes(), nil return buf.Bytes(), nil
default: default:
return nil, os.ErrorString("invalid source") return nil, os.NewError("invalid source")
} }
} }

View File

@ -29,7 +29,7 @@ func readGopackHeader(buf *bufio.Reader) (name string, size int, err os.Error) {
s := strings.TrimSpace(string(hdr[64+12+6+6+8:][:10])) s := strings.TrimSpace(string(hdr[64+12+6+6+8:][:10]))
size, err = strconv.Atoi(s) size, err = strconv.Atoi(s)
if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' {
err = os.ErrorString("invalid archive header") err = os.NewError("invalid archive header")
return return
} }
name = strings.TrimSpace(string(hdr[:64])) name = strings.TrimSpace(string(hdr[:64]))
@ -80,7 +80,7 @@ func ExportData(filename string) (rc io.ReadCloser, err os.Error) {
return return
} }
if name != "__.SYMDEF" { if name != "__.SYMDEF" {
err = os.ErrorString("go archive does not begin with __.SYMDEF") err = os.NewError("go archive does not begin with __.SYMDEF")
return return
} }
const block = 4096 const block = 4096
@ -102,7 +102,7 @@ func ExportData(filename string) (rc io.ReadCloser, err os.Error) {
return return
} }
if name != "__.PKGDEF" { if name != "__.PKGDEF" {
err = os.ErrorString("go archive is missing __.PKGDEF") err = os.NewError("go archive is missing __.PKGDEF")
return return
} }
@ -117,7 +117,7 @@ func ExportData(filename string) (rc io.ReadCloser, err os.Error) {
// Now at __.PKGDEF in archive or still at beginning of file. // Now at __.PKGDEF in archive or still at beginning of file.
// Either way, line should begin with "go object ". // Either way, line should begin with "go object ".
if !strings.HasPrefix(string(line), "go object ") { if !strings.HasPrefix(string(line), "go object ") {
err = os.ErrorString("not a go object file") err = os.NewError("not a go object file")
return return
} }

View File

@ -124,7 +124,7 @@ func GcImporter(imports map[string]*ast.Object, path string) (pkg *ast.Object, e
filename, id := findPkg(path) filename, id := findPkg(path)
if filename == "" { if filename == "" {
err = os.ErrorString("can't find import: " + id) err = os.NewError("can't find import: " + id)
return return
} }
@ -166,7 +166,7 @@ func (e importError) String() string {
func (p *gcParser) error(err interface{}) { func (p *gcParser) error(err interface{}) {
if s, ok := err.(string); ok { if s, ok := err.(string); ok {
err = os.ErrorString(s) err = os.NewError(s)
} }
// panic with a runtime.Error if err is not an os.Error // panic with a runtime.Error if err is not an os.Error
panic(importError{p.scanner.Pos(), err.(os.Error)}) panic(importError{p.scanner.Pos(), err.(os.Error)})

View File

@ -330,7 +330,7 @@ func newDecodeStateFromData(data []byte) *decoderState {
// Test instruction execution for decoding. // Test instruction execution for decoding.
// Do not run the machine yet; instead do individual instructions crafted by hand. // Do not run the machine yet; instead do individual instructions crafted by hand.
func TestScalarDecInstructions(t *testing.T) { func TestScalarDecInstructions(t *testing.T) {
ovfl := os.ErrorString("overflow") ovfl := os.NewError("overflow")
// bool // bool
{ {

View File

@ -17,9 +17,9 @@ import (
) )
var ( var (
errBadUint = os.ErrorString("gob: encoded unsigned integer out of range") errBadUint = os.NewError("gob: encoded unsigned integer out of range")
errBadType = os.ErrorString("gob: unknown type id or corrupted data") errBadType = os.NewError("gob: unknown type id or corrupted data")
errRange = os.ErrorString("gob: bad data: field numbers out of bounds") errRange = os.NewError("gob: bad data: field numbers out of bounds")
) )
// decoderState is the execution state of an instance of the decoder. A new state // decoderState is the execution state of an instance of the decoder. A new state
@ -54,8 +54,8 @@ func (dec *Decoder) freeDecoderState(d *decoderState) {
dec.freeList = d dec.freeList = d
} }
func overflow(name string) os.ErrorString { func overflow(name string) os.Error {
return os.ErrorString(`value for "` + name + `" out of range`) return os.NewError(`value for "` + name + `" out of range`)
} }
// decodeUintReader reads an encoded unsigned integer from an io.Reader. // decodeUintReader reads an encoded unsigned integer from an io.Reader.
@ -135,10 +135,10 @@ type decOp func(i *decInstr, state *decoderState, p unsafe.Pointer)
// The 'instructions' of the decoding machine // The 'instructions' of the decoding machine
type decInstr struct { type decInstr struct {
op decOp op decOp
field int // field number of the wire type field int // field number of the wire type
indir int // how many pointer indirections to reach the value in the struct indir int // how many pointer indirections to reach the value in the struct
offset uintptr // offset in the structure of the field to encode offset uintptr // offset in the structure of the field to encode
ovfl os.ErrorString // error message for overflow/underflow (for arrays, of the elements) ovfl os.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 // Since the encoder writes no zeros, if we arrive at a decoder we have
@ -552,7 +552,7 @@ func (dec *Decoder) ignoreSingle(engine *decEngine) {
} }
// decodeArrayHelper does the work for decoding arrays and slices. // 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.ErrorString) { func (dec *Decoder) decodeArrayHelper(state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, elemIndir int, ovfl os.Error) {
instr := &decInstr{elemOp, 0, elemIndir, 0, ovfl} instr := &decInstr{elemOp, 0, elemIndir, 0, ovfl}
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
up := unsafe.Pointer(p) up := unsafe.Pointer(p)
@ -567,7 +567,7 @@ func (dec *Decoder) decodeArrayHelper(state *decoderState, p uintptr, elemOp dec
// decodeArray decodes an array and stores it through p, that is, p points to the zeroth element. // 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 // 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. // (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.ErrorString) { func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, indir, elemIndir int, ovfl os.Error) {
if indir > 0 { if indir > 0 {
p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect
} }
@ -579,7 +579,7 @@ func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, p uintpt
// decodeIntoValue is a helper for map decoding. Since maps are decoded using reflection, // decodeIntoValue is a helper for map decoding. Since maps are decoded using reflection,
// unlike the other items we can't use a pointer directly. // unlike the other items we can't use a pointer directly.
func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value, ovfl os.ErrorString) reflect.Value { func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value, ovfl os.Error) reflect.Value {
instr := &decInstr{op, 0, indir, 0, ovfl} instr := &decInstr{op, 0, indir, 0, ovfl}
up := unsafe.Pointer(unsafeAddr(v)) up := unsafe.Pointer(unsafeAddr(v))
if indir > 1 { if indir > 1 {
@ -593,7 +593,7 @@ func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value,
// Maps are encoded as a length followed by key:value pairs. // Maps are encoded as a length followed by key:value pairs.
// Because the internals of maps are not visible to us, we must // Because the internals of maps are not visible to us, we must
// use reflection rather than pointer magic. // 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.ErrorString) { func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, p uintptr, keyOp, elemOp decOp, indir, keyIndir, elemIndir int, ovfl os.Error) {
if indir > 0 { if indir > 0 {
p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect
} }
@ -616,7 +616,7 @@ func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, p uintptr,
// ignoreArrayHelper does the work for discarding arrays and slices. // ignoreArrayHelper does the work for discarding arrays and slices.
func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) { func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) {
instr := &decInstr{elemOp, 0, 0, 0, os.ErrorString("no error")} instr := &decInstr{elemOp, 0, 0, 0, os.NewError("no error")}
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
elemOp(instr, state, nil) elemOp(instr, state, nil)
} }
@ -633,8 +633,8 @@ func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) {
// ignoreMap discards the data for a map value with no destination. // ignoreMap discards the data for a map value with no destination.
func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) { func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
n := int(state.decodeUint()) n := int(state.decodeUint())
keyInstr := &decInstr{keyOp, 0, 0, 0, os.ErrorString("no error")} keyInstr := &decInstr{keyOp, 0, 0, 0, os.NewError("no error")}
elemInstr := &decInstr{elemOp, 0, 0, 0, os.ErrorString("no error")} elemInstr := &decInstr{elemOp, 0, 0, 0, os.NewError("no error")}
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
keyOp(keyInstr, state, nil) keyOp(keyInstr, state, nil)
elemOp(elemInstr, state, nil) elemOp(elemInstr, state, nil)
@ -643,7 +643,7 @@ func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
// decodeSlice decodes a slice and stores the slice header through p. // decodeSlice decodes a slice and stores the slice header through p.
// Slices are encoded as an unsigned length followed by the elements. // 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.ErrorString) { func (dec *Decoder) decodeSlice(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl os.Error) {
n := int(uintptr(state.decodeUint())) n := int(uintptr(state.decodeUint()))
if indir > 0 { if indir > 0 {
up := unsafe.Pointer(p) up := unsafe.Pointer(p)
@ -1064,10 +1064,10 @@ func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *de
engine.instr = make([]decInstr, 1) // one item engine.instr = make([]decInstr, 1) // one item
name := rt.String() // best we can do name := rt.String() // best we can do
if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) { if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
return nil, os.ErrorString("gob: wrong type received for local value " + name + ": " + dec.typeString(remoteId)) return nil, os.NewError("gob: wrong type received for local value " + name + ": " + dec.typeString(remoteId))
} }
op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp)) op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
ovfl := os.ErrorString(`value for "` + name + `" out of range`) ovfl := os.NewError(`value for "` + name + `" out of range`)
engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl} engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl}
engine.numInstr = 1 engine.numInstr = 1
return return

View File

@ -44,7 +44,7 @@ func NewDecoder(r io.Reader) *Decoder {
func (dec *Decoder) recvType(id typeId) { func (dec *Decoder) recvType(id typeId) {
// Have we already seen this type? That's an error // Have we already seen this type? That's an error
if id < firstUserId || dec.wireType[id] != nil { if id < firstUserId || dec.wireType[id] != nil {
dec.err = os.ErrorString("gob: duplicate type received") dec.err = os.NewError("gob: duplicate type received")
return return
} }
@ -143,7 +143,7 @@ func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId {
// will be absorbed by recvMessage.) // will be absorbed by recvMessage.)
if dec.buf.Len() > 0 { if dec.buf.Len() > 0 {
if !isInterface { if !isInterface {
dec.err = os.ErrorString("extra data in buffer") dec.err = os.NewError("extra data in buffer")
break break
} }
dec.nextUint() dec.nextUint()
@ -165,7 +165,7 @@ func (dec *Decoder) Decode(e interface{}) os.Error {
// If e represents a value as opposed to a pointer, the answer won't // 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. // get back to the caller. Make sure it's a pointer.
if value.Type().Kind() != reflect.Ptr { if value.Type().Kind() != reflect.Ptr {
dec.err = os.ErrorString("gob: attempt to decode into a non-pointer") dec.err = os.NewError("gob: attempt to decode into a non-pointer")
return dec.err return dec.err
} }
return dec.DecodeValue(value) return dec.DecodeValue(value)
@ -180,7 +180,7 @@ func (dec *Decoder) DecodeValue(v reflect.Value) os.Error {
if v.Kind() == reflect.Ptr && !v.IsNil() { if v.Kind() == reflect.Ptr && !v.IsNil() {
// That's okay, we'll store through the pointer. // That's okay, we'll store through the pointer.
} else if !v.CanSet() { } else if !v.CanSet() {
return os.ErrorString("gob: DecodeValue of unassignable value") return os.NewError("gob: DecodeValue of unassignable value")
} }
} }
// Make sure we're single-threaded through here. // Make sure we're single-threaded through here.

View File

@ -50,7 +50,7 @@ func (enc *Encoder) popWriter() {
} }
func (enc *Encoder) badType(rt reflect.Type) { func (enc *Encoder) badType(rt reflect.Type) {
enc.setError(os.ErrorString("gob: can't encode type " + rt.String())) enc.setError(os.NewError("gob: can't encode type " + rt.String()))
} }
func (enc *Encoder) setError(err os.Error) { func (enc *Encoder) setError(err os.Error) {

View File

@ -44,7 +44,7 @@ func (g *ByteStruct) GobEncode() ([]byte, os.Error) {
func (g *ByteStruct) GobDecode(data []byte) os.Error { func (g *ByteStruct) GobDecode(data []byte) os.Error {
if g == nil { if g == nil {
return os.ErrorString("NIL RECEIVER") return os.NewError("NIL RECEIVER")
} }
// Expect N sequential-valued bytes. // Expect N sequential-valued bytes.
if len(data) == 0 { if len(data) == 0 {
@ -53,7 +53,7 @@ func (g *ByteStruct) GobDecode(data []byte) os.Error {
g.a = data[0] g.a = data[0]
for i, c := range data { for i, c := range data {
if c != g.a+byte(i) { if c != g.a+byte(i) {
return os.ErrorString("invalid data sequence") return os.NewError("invalid data sequence")
} }
} }
return nil return nil
@ -71,7 +71,7 @@ func (g *StringStruct) GobDecode(data []byte) os.Error {
a := data[0] a := data[0]
for i, c := range data { for i, c := range data {
if c != a+byte(i) { if c != a+byte(i) {
return os.ErrorString("invalid data sequence") return os.NewError("invalid data sequence")
} }
} }
g.s = string(data) g.s = string(data)
@ -84,7 +84,7 @@ func (a *ArrayStruct) GobEncode() ([]byte, os.Error) {
func (a *ArrayStruct) GobDecode(data []byte) os.Error { func (a *ArrayStruct) GobDecode(data []byte) os.Error {
if len(data) != len(a.a) { if len(data) != len(a.a) {
return os.ErrorString("wrong length in array decode") return os.NewError("wrong length in array decode")
} }
copy(a.a[:], data) copy(a.a[:], data)
return nil return nil

View File

@ -67,7 +67,7 @@ func validUserType(rt reflect.Type) (ut *userTypeInfo, err os.Error) {
ut.base = pt.Elem() ut.base = pt.Elem()
if ut.base == slowpoke { // ut.base lapped slowpoke if ut.base == slowpoke { // ut.base lapped slowpoke
// recursive pointer type. // recursive pointer type.
return nil, os.ErrorString("can't represent recursive pointer type " + ut.base.String()) return nil, os.NewError("can't represent recursive pointer type " + ut.base.String())
} }
if ut.indir%2 == 0 { if ut.indir%2 == 0 {
slowpoke = slowpoke.Elem() slowpoke = slowpoke.Elem()
@ -508,7 +508,7 @@ func newTypeObject(name string, ut *userTypeInfo, rt reflect.Type) (gobType, os.
return st, nil return st, nil
default: default:
return nil, os.ErrorString("gob NewTypeObject can't handle type: " + rt.String()) return nil, os.NewError("gob NewTypeObject can't handle type: " + rt.String())
} }
return nil, nil return nil, nil
} }

View File

@ -198,7 +198,7 @@ func (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err os.Error)
if shouldRedirect(r.StatusCode) { if shouldRedirect(r.StatusCode) {
r.Body.Close() r.Body.Close()
if url = r.Header.Get("Location"); url == "" { if url = r.Header.Get("Location"); url == "" {
err = os.ErrorString(fmt.Sprintf("%d response missing Location header", r.StatusCode)) err = os.NewError(fmt.Sprintf("%d response missing Location header", r.StatusCode))
break break
} }
base = req.URL base = req.URL
@ -215,7 +215,7 @@ func (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err os.Error)
func defaultCheckRedirect(req *Request, via []*Request) os.Error { func defaultCheckRedirect(req *Request, via []*Request) os.Error {
if len(via) >= 10 { if len(via) >= 10 {
return os.ErrorString("stopped after 10 redirects") return os.NewError("stopped after 10 redirects")
} }
return nil return nil
} }

View File

@ -157,7 +157,7 @@ func serveFile(w ResponseWriter, r *Request, name string, redirect bool) {
// TODO(adg): handle multiple ranges // TODO(adg): handle multiple ranges
ranges, err := parseRange(r.Header.Get("Range"), size) ranges, err := parseRange(r.Header.Get("Range"), size)
if err == nil && len(ranges) > 1 { if err == nil && len(ranges) > 1 {
err = os.ErrorString("multiple ranges not supported") err = os.NewError("multiple ranges not supported")
} }
if err != nil { if err != nil {
Error(w, err.String(), StatusRequestedRangeNotSatisfiable) Error(w, err.String(), StatusRequestedRangeNotSatisfiable)

View File

@ -35,13 +35,15 @@ const (
// ErrMissingFile is returned by FormFile when the provided file field name // ErrMissingFile is returned by FormFile when the provided file field name
// is either not present in the request or not a file field. // is either not present in the request or not a file field.
var ErrMissingFile = os.ErrorString("http: no such file") var ErrMissingFile = os.NewError("http: no such file")
// HTTP request parsing errors. // HTTP request parsing errors.
type ProtocolError struct { type ProtocolError struct {
os.ErrorString ErrorString string
} }
func (err *ProtocolError) String() string { return err.ErrorString }
var ( var (
ErrLineTooLong = &ProtocolError{"header line too long"} ErrLineTooLong = &ProtocolError{"header line too long"}
ErrHeaderTooLong = &ProtocolError{"header too long"} ErrHeaderTooLong = &ProtocolError{"header too long"}
@ -704,7 +706,7 @@ func (r *Request) ParseForm() (err os.Error) {
} }
if r.Method == "POST" { if r.Method == "POST" {
if r.Body == nil { if r.Body == nil {
return os.ErrorString("missing form body") return os.NewError("missing form body")
} }
ct := r.Header.Get("Content-Type") ct := r.Header.Get("Content-Type")
switch strings.Split(ct, ";", 2)[0] { switch strings.Split(ct, ";", 2)[0] {

View File

@ -76,12 +76,12 @@ func ProxyFromEnvironment(req *Request) (*URL, os.Error) {
} }
proxyURL, err := ParseRequestURL(proxy) proxyURL, err := ParseRequestURL(proxy)
if err != nil { if err != nil {
return nil, os.ErrorString("invalid proxy address") return nil, os.NewError("invalid proxy address")
} }
if proxyURL.Host == "" { if proxyURL.Host == "" {
proxyURL, err = ParseRequestURL("http://" + proxy) proxyURL, err = ParseRequestURL("http://" + proxy)
if err != nil { if err != nil {
return nil, os.ErrorString("invalid proxy address") return nil, os.NewError("invalid proxy address")
} }
} }
return proxyURL, nil return proxyURL, nil
@ -331,7 +331,7 @@ func (t *Transport) getConn(cm *connectMethod) (*persistConn, os.Error) {
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
f := strings.Split(resp.Status, " ", 2) f := strings.Split(resp.Status, " ", 2)
conn.Close() conn.Close()
return nil, os.ErrorString(f[1]) return nil, os.NewError(f[1])
} }
} }

View File

@ -299,7 +299,7 @@ func getscheme(rawurl string) (scheme, path string, err os.Error) {
} }
case c == ':': case c == ':':
if i == 0 { if i == 0 {
return "", "", os.ErrorString("missing protocol scheme") return "", "", os.NewError("missing protocol scheme")
} }
return rawurl[0:i], rawurl[i+1:], nil return rawurl[0:i], rawurl[i+1:], nil
default: default:
@ -354,7 +354,7 @@ func parseURL(rawurl string, viaRequest bool) (url *URL, err os.Error) {
) )
if rawurl == "" { if rawurl == "" {
err = os.ErrorString("empty url") err = os.NewError("empty url")
goto Error goto Error
} }
url = new(URL) url = new(URL)
@ -380,7 +380,7 @@ func parseURL(rawurl string, viaRequest bool) (url *URL, err os.Error) {
url.OpaquePath = true url.OpaquePath = true
} else { } else {
if viaRequest && !leadingSlash { if viaRequest && !leadingSlash {
err = os.ErrorString("invalid URI for request") err = os.NewError("invalid URI for request")
goto Error goto Error
} }
@ -414,7 +414,7 @@ func parseURL(rawurl string, viaRequest bool) (url *URL, err os.Error) {
if strings.Contains(rawHost, "%") { if strings.Contains(rawHost, "%") {
// Host cannot contain escaped characters. // Host cannot contain escaped characters.
err = os.ErrorString("hexadecimal escape in host") err = os.NewError("hexadecimal escape in host")
goto Error goto Error
} }
url.Host = rawHost url.Host = rawHost

View File

@ -186,7 +186,7 @@ Loop:
return err return err
} }
if c != 0 { if c != 0 {
return os.ErrorString("gif: extra data after image") return os.NewError("gif: extra data after image")
} }
// Undo the interlacing if necessary. // Undo the interlacing if necessary.

View File

@ -12,9 +12,11 @@ import "os"
// Error represents an unexpected I/O behavior. // Error represents an unexpected I/O behavior.
type Error struct { type Error struct {
os.ErrorString ErrorString string
} }
func (err *Error) String() string { return err.ErrorString }
// ErrShortWrite means that a write accepted fewer bytes than requested // ErrShortWrite means that a write accepted fewer bytes than requested
// but failed to return an explicit error. // but failed to return an explicit error.
var ErrShortWrite os.Error = &Error{"short write"} var ErrShortWrite os.Error = &Error{"short write"}

View File

@ -96,7 +96,7 @@ func parseDate(date string) (*time.Time, os.Error) {
return t, nil return t, nil
} }
} }
return nil, os.ErrorString("mail: header could not be parsed") return nil, os.NewError("mail: header could not be parsed")
} }
// A Header represents the key-value pairs in a mail message header. // A Header represents the key-value pairs in a mail message header.
@ -108,7 +108,7 @@ func (h Header) Get(key string) string {
return textproto.MIMEHeader(h).Get(key) return textproto.MIMEHeader(h).Get(key)
} }
var ErrHeaderNotPresent = os.ErrorString("mail: header not in message") var ErrHeaderNotPresent = os.NewError("mail: header not in message")
// Date parses the Date header field. // Date parses the Date header field.
func (h Header) Date() (*time.Time, os.Error) { func (h Header) Date() (*time.Time, os.Error) {
@ -204,7 +204,7 @@ func (p *addrParser) parseAddressList() ([]*Address, os.Error) {
break break
} }
if !p.consume(',') { if !p.consume(',') {
return nil, os.ErrorString("mail: expected comma") return nil, os.NewError("mail: expected comma")
} }
} }
return list, nil return list, nil
@ -215,7 +215,7 @@ func (p *addrParser) parseAddress() (addr *Address, err os.Error) {
debug.Printf("parseAddress: %q", *p) debug.Printf("parseAddress: %q", *p)
p.skipSpace() p.skipSpace()
if p.empty() { if p.empty() {
return nil, os.ErrorString("mail: no address") return nil, os.NewError("mail: no address")
} }
// address = name-addr / addr-spec // address = name-addr / addr-spec
@ -246,14 +246,14 @@ func (p *addrParser) parseAddress() (addr *Address, err os.Error) {
// angle-addr = "<" addr-spec ">" // angle-addr = "<" addr-spec ">"
p.skipSpace() p.skipSpace()
if !p.consume('<') { if !p.consume('<') {
return nil, os.ErrorString("mail: no angle-addr") return nil, os.NewError("mail: no angle-addr")
} }
spec, err = p.consumeAddrSpec() spec, err = p.consumeAddrSpec()
if err != nil { if err != nil {
return nil, err return nil, err
} }
if !p.consume('>') { if !p.consume('>') {
return nil, os.ErrorString("mail: unclosed angle-addr") return nil, os.NewError("mail: unclosed angle-addr")
} }
debug.Printf("parseAddress: spec=%q", spec) debug.Printf("parseAddress: spec=%q", spec)
@ -278,7 +278,7 @@ func (p *addrParser) consumeAddrSpec() (spec string, err os.Error) {
var localPart string var localPart string
p.skipSpace() p.skipSpace()
if p.empty() { if p.empty() {
return "", os.ErrorString("mail: no addr-spec") return "", os.NewError("mail: no addr-spec")
} }
if p.peek() == '"' { if p.peek() == '"' {
// quoted-string // quoted-string
@ -295,14 +295,14 @@ func (p *addrParser) consumeAddrSpec() (spec string, err os.Error) {
} }
if !p.consume('@') { if !p.consume('@') {
return "", os.ErrorString("mail: missing @ in addr-spec") return "", os.NewError("mail: missing @ in addr-spec")
} }
// domain = dot-atom / domain-literal // domain = dot-atom / domain-literal
var domain string var domain string
p.skipSpace() p.skipSpace()
if p.empty() { if p.empty() {
return "", os.ErrorString("mail: no domain in addr-spec") return "", os.NewError("mail: no domain in addr-spec")
} }
// TODO(dsymonds): Handle domain-literal // TODO(dsymonds): Handle domain-literal
domain, err = p.consumeAtom(true) domain, err = p.consumeAtom(true)
@ -323,7 +323,7 @@ func (p *addrParser) consumePhrase() (phrase string, err os.Error) {
var word string var word string
p.skipSpace() p.skipSpace()
if p.empty() { if p.empty() {
return "", os.ErrorString("mail: missing phrase") return "", os.NewError("mail: missing phrase")
} }
if p.peek() == '"' { if p.peek() == '"' {
// quoted-string // quoted-string
@ -347,7 +347,7 @@ func (p *addrParser) consumePhrase() (phrase string, err os.Error) {
// Ignore any error if we got at least one word. // Ignore any error if we got at least one word.
if err != nil && len(words) == 0 { if err != nil && len(words) == 0 {
debug.Printf("consumePhrase: hit err: %v", err) debug.Printf("consumePhrase: hit err: %v", err)
return "", os.ErrorString("mail: missing word in phrase") return "", os.NewError("mail: missing word in phrase")
} }
phrase = strings.Join(words, " ") phrase = strings.Join(words, " ")
return phrase, nil return phrase, nil
@ -361,14 +361,14 @@ func (p *addrParser) consumeQuotedString() (qs string, err os.Error) {
Loop: Loop:
for { for {
if i >= p.len() { if i >= p.len() {
return "", os.ErrorString("mail: unclosed quoted-string") return "", os.NewError("mail: unclosed quoted-string")
} }
switch c := (*p)[i]; { switch c := (*p)[i]; {
case c == '"': case c == '"':
break Loop break Loop
case c == '\\': case c == '\\':
if i+1 == p.len() { if i+1 == p.len() {
return "", os.ErrorString("mail: unclosed quoted-string") return "", os.NewError("mail: unclosed quoted-string")
} }
qsb = append(qsb, (*p)[i+1]) qsb = append(qsb, (*p)[i+1])
i += 2 i += 2
@ -389,7 +389,7 @@ Loop:
// If dot is true, consumeAtom parses an RFC 5322 dot-atom instead. // 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 os.Error) {
if !isAtext(p.peek(), false) { if !isAtext(p.peek(), false) {
return "", os.ErrorString("mail: invalid string") return "", os.NewError("mail: invalid string")
} }
i := 1 i := 1
for ; i < p.len() && isAtext((*p)[i], dot); i++ { for ; i < p.len() && isAtext((*p)[i], dot); i++ {
@ -427,7 +427,7 @@ func (p *addrParser) len() int {
func decodeRFC2047Word(s string) (string, os.Error) { func decodeRFC2047Word(s string) (string, os.Error) {
fields := strings.Split(s, "?", -1) fields := strings.Split(s, "?", -1)
if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" { if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" {
return "", os.ErrorString("mail: address not RFC 2047 encoded") return "", os.NewError("mail: address not RFC 2047 encoded")
} }
charset, enc := strings.ToLower(fields[1]), strings.ToLower(fields[2]) charset, enc := strings.ToLower(fields[1]), strings.ToLower(fields[2])
if charset != "iso-8859-1" && charset != "utf-8" { if charset != "iso-8859-1" && charset != "utf-8" {

View File

@ -56,7 +56,7 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) {
return false, os.NewSyscallError("kevent", e) return false, os.NewSyscallError("kevent", e)
} }
if n != 1 || (ev.Flags&syscall.EV_ERROR) == 0 || int(ev.Ident) != fd || int(ev.Filter) != kmode { if n != 1 || (ev.Flags&syscall.EV_ERROR) == 0 || int(ev.Ident) != fd || int(ev.Filter) != kmode {
return false, os.ErrorString("kqueue phase error") return false, os.NewError("kqueue phase error")
} }
if ev.Data != 0 { if ev.Data != 0 {
return false, os.Errno(int(ev.Data)) return false, os.Errno(int(ev.Data))

View File

@ -294,7 +294,7 @@ func splitNetProto(netProto string) (net string, proto int, err os.Error) {
onceReadProtocols.Do(readProtocols) onceReadProtocols.Do(readProtocols)
i := last(netProto, ':') i := last(netProto, ':')
if i < 0 { // no colon if i < 0 { // no colon
return "", 0, os.ErrorString("no IP protocol specified") return "", 0, os.NewError("no IP protocol specified")
} }
net = netProto[0:i] net = netProto[0:i]
protostr := netProto[i+1:] protostr := netProto[i+1:]

View File

@ -115,7 +115,7 @@ type Listener interface {
Addr() Addr Addr() Addr
} }
var errMissingAddress = os.ErrorString("missing address") var errMissingAddress = os.NewError("missing address")
type OpError struct { type OpError struct {
Op string Op string

View File

@ -281,7 +281,7 @@ func (c *UDPConn) BindToDevice(device string) os.Error {
// Closing c does not affect f, and closing f does not affect c. // 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 os.Error) { return c.fd.dup() }
var errInvalidMulticast = os.ErrorString("invalid IPv4 multicast address") var errInvalidMulticast = os.NewError("invalid IPv4 multicast address")
// JoinGroup joins the IPv4 multicast group named by addr. // JoinGroup joins the IPv4 multicast group named by addr.
// The UDPConn must use the "udp4" network. // The UDPConn must use the "udp4" network.

View File

@ -153,7 +153,7 @@ func (cs *clientSet) drain(timeout int64) os.Error {
break break
} }
if timeout > 0 && time.Nanoseconds()-startTime >= timeout { if timeout > 0 && time.Nanoseconds()-startTime >= timeout {
return os.ErrorString("timeout") return os.NewError("timeout")
} }
time.Sleep(100 * 1e6) // 100 milliseconds time.Sleep(100 * 1e6) // 100 milliseconds
} }
@ -186,7 +186,7 @@ func (cs *clientSet) sync(timeout int64) os.Error {
break break
} }
if timeout > 0 && time.Nanoseconds()-startTime >= timeout { if timeout > 0 && time.Nanoseconds()-startTime >= timeout {
return os.ErrorString("timeout") return os.NewError("timeout")
} }
time.Sleep(100 * 1e6) // 100 milliseconds time.Sleep(100 * 1e6) // 100 milliseconds
} }

View File

@ -343,20 +343,20 @@ func (exp *Exporter) Sync(timeout int64) os.Error {
func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) { func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) {
chanType := reflect.TypeOf(chT) chanType := reflect.TypeOf(chT)
if chanType.Kind() != reflect.Chan { if chanType.Kind() != reflect.Chan {
return reflect.Value{}, os.ErrorString("not a channel") return reflect.Value{}, os.NewError("not a channel")
} }
if dir != Send && dir != Recv { if dir != Send && dir != Recv {
return reflect.Value{}, os.ErrorString("unknown channel direction") return reflect.Value{}, os.NewError("unknown channel direction")
} }
switch chanType.ChanDir() { switch chanType.ChanDir() {
case reflect.BothDir: case reflect.BothDir:
case reflect.SendDir: case reflect.SendDir:
if dir != Recv { if dir != Recv {
return reflect.Value{}, os.ErrorString("to import/export with Send, must provide <-chan") return reflect.Value{}, os.NewError("to import/export with Send, must provide <-chan")
} }
case reflect.RecvDir: case reflect.RecvDir:
if dir != Send { if dir != Send {
return reflect.Value{}, os.ErrorString("to import/export with Recv, must provide chan<-") return reflect.Value{}, os.NewError("to import/export with Recv, must provide chan<-")
} }
} }
return reflect.ValueOf(chT), nil return reflect.ValueOf(chT), nil
@ -376,7 +376,7 @@ func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error {
defer exp.mu.Unlock() defer exp.mu.Unlock()
_, present := exp.names[name] _, present := exp.names[name]
if present { if present {
return os.ErrorString("channel name already being exported:" + name) return os.NewError("channel name already being exported:" + name)
} }
exp.names[name] = &chanDir{ch, dir} exp.names[name] = &chanDir{ch, dir}
return nil return nil
@ -393,7 +393,7 @@ func (exp *Exporter) Hangup(name string) os.Error {
// TODO drop all instances of channel from client sets // TODO drop all instances of channel from client sets
exp.mu.Unlock() exp.mu.Unlock()
if !ok { if !ok {
return os.ErrorString("netchan export: hangup: no such channel: " + name) return os.NewError("netchan export: hangup: no such channel: " + name)
} }
chDir.ch.Close() chDir.ch.Close()
return nil return nil

View File

@ -102,7 +102,7 @@ func (imp *Importer) run() {
if err.Error != "" { if err.Error != "" {
impLog("response error:", err.Error) impLog("response error:", err.Error)
select { select {
case imp.errors <- os.ErrorString(err.Error): case imp.errors <- os.NewError(err.Error):
continue // errors are not acknowledged continue // errors are not acknowledged
default: default:
imp.shutdown() imp.shutdown()
@ -203,7 +203,7 @@ func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size,
defer imp.chanLock.Unlock() defer imp.chanLock.Unlock()
_, present := imp.names[name] _, present := imp.names[name]
if present { if present {
return os.ErrorString("channel name already being imported:" + name) return os.NewError("channel name already being imported:" + name)
} }
if size < 1 { if size < 1 {
size = 1 size = 1
@ -254,7 +254,7 @@ func (imp *Importer) Hangup(name string) os.Error {
defer imp.chanLock.Unlock() defer imp.chanLock.Unlock()
nc := imp.names[name] nc := imp.names[name]
if nc == nil { if nc == nil {
return os.ErrorString("netchan import: hangup: no such channel: " + name) return os.NewError("netchan import: hangup: no such channel: " + name)
} }
imp.names[name] = nil, false imp.names[name] = nil, false
imp.chans[nc.id] = nil, false imp.chans[nc.id] = nil, false
@ -279,7 +279,7 @@ func (imp *Importer) Drain(timeout int64) os.Error {
startTime := time.Nanoseconds() startTime := time.Nanoseconds()
for imp.unackedCount() > 0 { for imp.unackedCount() > 0 {
if timeout > 0 && time.Nanoseconds()-startTime >= timeout { if timeout > 0 && time.Nanoseconds()-startTime >= timeout {
return os.ErrorString("timeout") return os.NewError("timeout")
} }
time.Sleep(100 * 1e6) time.Sleep(100 * 1e6)
} }

View File

@ -9,20 +9,17 @@ type Error interface {
String() string String() string
} }
// A helper type that can be embedded or wrapped to simplify satisfying // // errorString is a helper type used by NewError.
// Error. type errorString string
type ErrorString string
func (e ErrorString) String() string { return string(e) } func (e errorString) String() string { return string(e) }
func (e ErrorString) Temporary() bool { return false }
func (e ErrorString) Timeout() bool { return false }
// Note: If the name of the function NewError changes, // Note: If the name of the function NewError changes,
// pkg/go/doc/doc.go should be adjusted since it hardwires // pkg/go/doc/doc.go should be adjusted since it hardwires
// this name in a heuristic. // this name in a heuristic.
// NewError converts s to an ErrorString, which satisfies the Error interface. // // NewError returns a new error with error.String() == s.
func NewError(s string) Error { return ErrorString(s) } func NewError(s string) Error { return errorString(s) }
// PathError records an error and the operation and file path that caused it. // PathError records an error and the operation and file path that caused it.
type PathError struct { type PathError struct {

View File

@ -45,12 +45,12 @@ func (this *statsResults) checkSimilarDistribution(expected *statsResults) os.Er
if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) { 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) s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError)
fmt.Println(s) fmt.Println(s)
return os.ErrorString(s) return os.NewError(s)
} }
if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) { 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) s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError)
fmt.Println(s) fmt.Println(s)
return os.ErrorString(s) return os.NewError(s)
} }
return nil return nil
} }

View File

@ -23,7 +23,7 @@ func (e ServerError) String() string {
return string(e) return string(e)
} }
const ErrShutdown = os.ErrorString("connection is shut down") var ErrShutdown = os.NewError("connection is shut down")
// Call represents an active RPC. // Call represents an active RPC.
type Call struct { type Call struct {
@ -110,7 +110,7 @@ func (client *Client) input() {
if response.Error == "" { if response.Error == "" {
err = client.codec.ReadResponseBody(c.Reply) err = client.codec.ReadResponseBody(c.Reply)
if err != nil { if err != nil {
c.Error = os.ErrorString("reading body " + err.String()) c.Error = os.NewError("reading body " + err.String())
} }
} else { } else {
// We've got an error response. Give this to the request; // We've got an error response. Give this to the request;
@ -119,7 +119,7 @@ func (client *Client) input() {
c.Error = ServerError(response.Error) c.Error = ServerError(response.Error)
err = client.codec.ReadResponseBody(nil) err = client.codec.ReadResponseBody(nil)
if err != nil { if err != nil {
err = os.ErrorString("reading error body: " + err.String()) err = os.NewError("reading error body: " + err.String())
} }
} }
c.done() c.done()
@ -221,7 +221,7 @@ func DialHTTPPath(network, address, path string) (*Client, os.Error) {
return NewClient(conn), nil return NewClient(conn), nil
} }
if err == nil { if err == nil {
err = os.ErrorString("unexpected HTTP response: " + resp.Status) err = os.NewError("unexpected HTTP response: " + resp.Status)
} }
conn.Close() conn.Close()
return nil, &net.OpError{"dial-http", network + " " + address, nil, err} return nil, &net.OpError{"dial-http", network + " " + address, nil, err}

View File

@ -35,7 +35,7 @@ func (t *Arith) Mul(args *Args, reply *Reply) os.Error {
func (t *Arith) Div(args *Args, reply *Reply) os.Error { func (t *Arith) Div(args *Args, reply *Reply) os.Error {
if args.B == 0 { if args.B == 0 {
return os.ErrorString("divide by zero") return os.NewError("divide by zero")
} }
reply.C = args.A / args.B reply.C = args.A / args.B
return nil return nil

View File

@ -242,10 +242,10 @@ func (server *Server) register(rcvr interface{}, name string, useName bool) os.E
if s.typ.PkgPath() != "" && !isExported(sname) && !useName { if s.typ.PkgPath() != "" && !isExported(sname) && !useName {
s := "rpc Register: type " + sname + " is not exported" s := "rpc Register: type " + sname + " is not exported"
log.Print(s) log.Print(s)
return os.ErrorString(s) return os.NewError(s)
} }
if _, present := server.serviceMap[sname]; present { if _, present := server.serviceMap[sname]; present {
return os.ErrorString("rpc: service already defined: " + sname) return os.NewError("rpc: service already defined: " + sname)
} }
s.name = sname s.name = sname
s.method = make(map[string]*methodType) s.method = make(map[string]*methodType)
@ -294,7 +294,7 @@ func (server *Server) register(rcvr interface{}, name string, useName bool) os.E
if len(s.method) == 0 { if len(s.method) == 0 {
s := "rpc Register: type " + sname + " has no exported methods of suitable type" s := "rpc Register: type " + sname + " has no exported methods of suitable type"
log.Print(s) log.Print(s)
return os.ErrorString(s) return os.NewError(s)
} }
server.serviceMap[s.name] = s server.serviceMap[s.name] = s
return nil return nil
@ -491,13 +491,13 @@ func (server *Server) readRequest(codec ServerCodec) (req *Request, service *ser
if err == os.EOF || err == io.ErrUnexpectedEOF { if err == os.EOF || err == io.ErrUnexpectedEOF {
return return
} }
err = os.ErrorString("rpc: server cannot decode request: " + err.String()) err = os.NewError("rpc: server cannot decode request: " + err.String())
return return
} }
serviceMethod := strings.Split(req.ServiceMethod, ".", -1) serviceMethod := strings.Split(req.ServiceMethod, ".", -1)
if len(serviceMethod) != 2 { if len(serviceMethod) != 2 {
err = os.ErrorString("rpc: service/method request ill-formed: " + req.ServiceMethod) err = os.NewError("rpc: service/method request ill-formed: " + req.ServiceMethod)
return return
} }
// Look up the request. // Look up the request.
@ -505,12 +505,12 @@ func (server *Server) readRequest(codec ServerCodec) (req *Request, service *ser
service = server.serviceMap[serviceMethod[0]] service = server.serviceMap[serviceMethod[0]]
server.Unlock() server.Unlock()
if service == nil { if service == nil {
err = os.ErrorString("rpc: can't find service " + req.ServiceMethod) err = os.NewError("rpc: can't find service " + req.ServiceMethod)
return return
} }
mtype = service.method[serviceMethod[1]] mtype = service.method[serviceMethod[1]]
if mtype == nil { if mtype == nil {
err = os.ErrorString("rpc: can't find method " + req.ServiceMethod) err = os.NewError("rpc: can't find method " + req.ServiceMethod)
} }
return return
} }

View File

@ -52,7 +52,7 @@ func (t *Arith) Mul(args *Args, reply *Reply) os.Error {
func (t *Arith) Div(args Args, reply *Reply) os.Error { func (t *Arith) Div(args Args, reply *Reply) os.Error {
if args.B == 0 { if args.B == 0 {
return os.ErrorString("divide by zero") return os.NewError("divide by zero")
} }
reply.C = args.A / args.B reply.C = args.A / args.B
return nil return nil

View File

@ -70,7 +70,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) {
} }
default: default:
err = os.ErrorString("invalid base " + Itoa(b)) err = os.NewError("invalid base " + Itoa(b))
goto Error goto Error
} }

View File

@ -49,7 +49,7 @@ func (r *Reader) ReadByte() (b byte, err os.Error) {
// read yet. // read yet.
func (r *Reader) UnreadByte() os.Error { func (r *Reader) UnreadByte() os.Error {
if r.i <= 0 { if r.i <= 0 {
return os.ErrorString("strings.Reader: at beginning of string") return os.NewError("strings.Reader: at beginning of string")
} }
r.i-- r.i--
r.prevRune = -1 r.prevRune = -1
@ -80,7 +80,7 @@ func (r *Reader) ReadRune() (rune int, size int, err os.Error) {
// The last method called on r must have been ReadRune. // The last method called on r must have been ReadRune.
func (r *Reader) UnreadRune() os.Error { func (r *Reader) UnreadRune() os.Error {
if r.prevRune < 0 { if r.prevRune < 0 {
return os.ErrorString("strings.Reader: previous operation was not ReadRune") return os.NewError("strings.Reader: previous operation was not ReadRune")
} }
r.i = r.prevRune r.i = r.prevRune
r.prevRune = -1 r.prevRune = -1

View File

@ -27,5 +27,5 @@ func unixSyslog() (conn serverConn, err os.Error) {
} }
} }
} }
return nil, os.ErrorString("Unix syslog delivery error") return nil, os.NewError("Unix syslog delivery error")
} }

View File

@ -355,7 +355,7 @@ func (t *Time) String() string {
return t.Format(UnixDate) return t.Format(UnixDate)
} }
var errBad = os.ErrorString("bad") // just a marker; not returned to user var errBad = os.NewError("bad") // just a marker; not returned to user
// ParseError describes a problem parsing a time string. // ParseError describes a problem parsing a time string.
type ParseError struct { type ParseError struct {

View File

@ -160,7 +160,7 @@ var onceStartTickerLoop sync.Once
// ns must be greater than zero; if not, NewTicker will panic. // ns must be greater than zero; if not, NewTicker will panic.
func NewTicker(ns int64) *Ticker { func NewTicker(ns int64) *Ticker {
if ns <= 0 { if ns <= 0 {
panic(os.ErrorString("non-positive interval for NewTicker")) panic(os.NewError("non-positive interval for NewTicker"))
} }
c := make(chan int64, 1) // See comment on send in tickerLoop c := make(chan int64, 1) // See comment on send in tickerLoop
t := &Ticker{ t := &Ticker{

View File

@ -19,11 +19,13 @@ import (
) )
type ProtocolError struct { type ProtocolError struct {
os.ErrorString ErrorString string
} }
func (err *ProtocolError) String() string { return string(err.ErrorString) }
var ( var (
ErrBadScheme = os.ErrorString("bad scheme") ErrBadScheme = &ProtocolError{"bad scheme"}
ErrBadStatus = &ProtocolError{"bad status"} ErrBadStatus = &ProtocolError{"bad status"}
ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"} ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"}
ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"} ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"}

View File

@ -251,7 +251,7 @@ func (p *Parser) unmarshal(val reflect.Value, start *StartElement) os.Error {
switch v := val; v.Kind() { switch v := val; v.Kind() {
default: default:
return os.ErrorString("unknown type " + v.Type().String()) return os.NewError("unknown type " + v.Type().String())
case reflect.Slice: case reflect.Slice:
typ := v.Type() typ := v.Type()
@ -508,7 +508,7 @@ func copyValue(dst reflect.Value, src []byte) (err os.Error) {
case reflect.Invalid: case reflect.Invalid:
// Probably a comment, handled below // Probably a comment, handled below
default: default:
return os.ErrorString("cannot happen: unknown type " + t.Type().String()) return os.NewError("cannot happen: unknown type " + t.Type().String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if !getInt64() { if !getInt64() {
return err return err

View File

@ -38,7 +38,7 @@ func Listen(x, y string) (T, string) {
} }
func (t T) Addr() os.Error { func (t T) Addr() os.Error {
return os.ErrorString("stringer") return os.NewError("stringer")
} }
func (t T) Accept() (int, string) { func (t T) Accept() (int, string) {
@ -49,4 +49,3 @@ func Dial(x, y, z string) (int, string) {
global <- 1 global <- 1
return 0, "" return 0, ""
} }