diff --git a/src/pkg/net/cgo_stub.go b/src/pkg/net/cgo_stub.go index 565cbe7fec..fbe6150c26 100644 --- a/src/pkg/net/cgo_stub.go +++ b/src/pkg/net/cgo_stub.go @@ -8,20 +8,18 @@ package net -import "os" - -func cgoLookupHost(name string) (addrs []string, err os.Error, completed bool) { +func cgoLookupHost(name string) (addrs []string, err error, completed bool) { return nil, nil, false } -func cgoLookupPort(network, service string) (port int, err os.Error, completed bool) { +func cgoLookupPort(network, service string) (port int, err error, completed bool) { return 0, nil, false } -func cgoLookupIP(name string) (addrs []IP, err os.Error, completed bool) { +func cgoLookupIP(name string) (addrs []IP, err error, completed bool) { return nil, nil, false } -func cgoLookupCNAME(name string) (cname string, err os.Error, completed bool) { +func cgoLookupCNAME(name string) (cname string, err error, completed bool) { return "", nil, false } diff --git a/src/pkg/net/cgo_unix.go b/src/pkg/net/cgo_unix.go index ec2a393e81..36a3f3d349 100644 --- a/src/pkg/net/cgo_unix.go +++ b/src/pkg/net/cgo_unix.go @@ -18,12 +18,11 @@ package net import "C" import ( - "os" "syscall" "unsafe" ) -func cgoLookupHost(name string) (addrs []string, err os.Error, completed bool) { +func cgoLookupHost(name string) (addrs []string, err error, completed bool) { ip, err, completed := cgoLookupIP(name) for _, p := range ip { addrs = append(addrs, p.String()) @@ -31,7 +30,7 @@ func cgoLookupHost(name string) (addrs []string, err os.Error, completed bool) { return } -func cgoLookupPort(net, service string) (port int, err os.Error, completed bool) { +func cgoLookupPort(net, service string) (port int, err error, completed bool) { var res *C.struct_addrinfo var hints C.struct_addrinfo @@ -78,7 +77,7 @@ func cgoLookupPort(net, service string) (port int, err os.Error, completed bool) return 0, &AddrError{"unknown port", net + "/" + service}, true } -func cgoLookupIPCNAME(name string) (addrs []IP, cname string, err os.Error, completed bool) { +func cgoLookupIPCNAME(name string) (addrs []IP, cname string, err error, completed bool) { var res *C.struct_addrinfo var hints C.struct_addrinfo @@ -98,11 +97,11 @@ func cgoLookupIPCNAME(name string) (addrs []IP, cname string, err os.Error, comp if gerrno == C.EAI_NONAME { str = noSuchHost } else if gerrno == C.EAI_SYSTEM { - str = err.String() + str = err.Error() } else { str = C.GoString(C.gai_strerror(gerrno)) } - return nil, "", &DNSError{Error: str, Name: name}, true + return nil, "", &DNSError{Err: str, Name: name}, true } defer C.freeaddrinfo(res) if res != nil { @@ -133,12 +132,12 @@ func cgoLookupIPCNAME(name string) (addrs []IP, cname string, err os.Error, comp return addrs, cname, nil, true } -func cgoLookupIP(name string) (addrs []IP, err os.Error, completed bool) { +func cgoLookupIP(name string) (addrs []IP, err error, completed bool) { addrs, _, err, completed = cgoLookupIPCNAME(name) return } -func cgoLookupCNAME(name string) (cname string, err os.Error, completed bool) { +func cgoLookupCNAME(name string) (cname string, err error, completed bool) { _, cname, err, completed = cgoLookupIPCNAME(name) return } diff --git a/src/pkg/net/dial.go b/src/pkg/net/dial.go index 85d54b3703..43866dcb51 100644 --- a/src/pkg/net/dial.go +++ b/src/pkg/net/dial.go @@ -4,9 +4,7 @@ package net -import "os" - -func resolveNetAddr(op, net, addr string) (a Addr, err os.Error) { +func resolveNetAddr(op, net, addr string) (a Addr, err error) { if addr == "" { return nil, &OpError{op, net, nil, errMissingAddress} } @@ -44,7 +42,7 @@ func resolveNetAddr(op, net, addr string) (a Addr, err os.Error) { // Dial("tcp", "google.com:80") // Dial("tcp", "[de:ad:be:ef::ca:fe]:80") // -func Dial(net, addr string) (c Conn, err os.Error) { +func Dial(net, addr string) (c Conn, err error) { addri, err := resolveNetAddr("dial", net, addr) if err != nil { return nil, err @@ -70,7 +68,7 @@ func Dial(net, addr string) (c Conn, err os.Error) { // Listen announces on the local network address laddr. // The network string net must be a stream-oriented // network: "tcp", "tcp4", "tcp6", or "unix", or "unixpacket". -func Listen(net, laddr string) (l Listener, err os.Error) { +func Listen(net, laddr string) (l Listener, err error) { switch net { case "tcp", "tcp4", "tcp6": var la *TCPAddr @@ -103,7 +101,7 @@ func Listen(net, laddr string) (l Listener, err os.Error) { // ListenPacket announces on the local network address laddr. // The network string net must be a packet-oriented network: // "udp", "udp4", "udp6", or "unixgram". -func ListenPacket(net, laddr string) (c PacketConn, err os.Error) { +func ListenPacket(net, laddr string) (c PacketConn, err error) { switch net { case "udp", "udp4", "udp6": var la *UDPAddr diff --git a/src/pkg/net/dict/dict.go b/src/pkg/net/dict/dict.go index b146ea2123..e7f5290f55 100644 --- a/src/pkg/net/dict/dict.go +++ b/src/pkg/net/dict/dict.go @@ -8,7 +8,6 @@ package dict import ( "net/textproto" - "os" "strconv" "strings" ) @@ -20,7 +19,7 @@ type Client struct { // Dial returns a new client connected to a dictionary server at // addr on the given network. -func Dial(network, addr string) (*Client, os.Error) { +func Dial(network, addr string) (*Client, error) { text, err := textproto.Dial(network, addr) if err != nil { return nil, err @@ -34,7 +33,7 @@ func Dial(network, addr string) (*Client, os.Error) { } // Close closes the connection to the dictionary server. -func (c *Client) Close() os.Error { +func (c *Client) Close() error { return c.text.Close() } @@ -45,7 +44,7 @@ type Dict struct { } // Dicts returns a list of the dictionaries available on the server. -func (c *Client) Dicts() ([]Dict, os.Error) { +func (c *Client) Dicts() ([]Dict, error) { id, err := c.text.Cmd("SHOW DB") if err != nil { return nil, err @@ -93,7 +92,7 @@ type Defn struct { // The special dictionary name "!" means to look in all the // server's dictionaries in turn, stopping after finding the word // in one of them. -func (c *Client) Define(dict, word string) ([]*Defn, os.Error) { +func (c *Client) Define(dict, word string) ([]*Defn, error) { id, err := c.text.Cmd("DEFINE %s %q", dict, word) if err != nil { return nil, err @@ -142,7 +141,7 @@ func (c *Client) Define(dict, word string) ([]*Defn, os.Error) { // Fields returns the fields in s. // Fields are space separated unquoted words // or quoted with single or double quote. -func fields(s string) ([]string, os.Error) { +func fields(s string) ([]string, error) { var v []string i := 0 for { diff --git a/src/pkg/net/dnsclient.go b/src/pkg/net/dnsclient.go index 93c04f6b59..e66f28c195 100644 --- a/src/pkg/net/dnsclient.go +++ b/src/pkg/net/dnsclient.go @@ -7,20 +7,19 @@ package net import ( "bytes" "fmt" - "os" "rand" "sort" ) // DNSError represents a DNS lookup error. type DNSError struct { - Error string // description of the error + Err string // description of the error Name string // name looked for Server string // server used IsTimeout bool } -func (e *DNSError) String() string { +func (e *DNSError) Error() string { if e == nil { return "" } @@ -28,7 +27,7 @@ func (e *DNSError) String() string { if e.Server != "" { s += " on " + e.Server } - s += ": " + e.Error + s += ": " + e.Err return s } @@ -40,10 +39,10 @@ const noSuchHost = "no such host" // reverseaddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP // address addr suitable for rDNS (PTR) record lookup or an error if it fails // to parse the IP address. -func reverseaddr(addr string) (arpa string, err os.Error) { +func reverseaddr(addr string) (arpa string, err error) { ip := ParseIP(addr) if ip == nil { - return "", &DNSError{Error: "unrecognized address", Name: addr} + return "", &DNSError{Err: "unrecognized address", Name: addr} } if ip.To4() != nil { return fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", ip[15], ip[14], ip[13], ip[12]), nil @@ -64,18 +63,18 @@ func reverseaddr(addr string) (arpa string, err os.Error) { // Find answer for name in dns message. // On return, if err == nil, addrs != nil. -func answer(name, server string, dns *dnsMsg, qtype uint16) (cname string, addrs []dnsRR, err os.Error) { +func answer(name, server string, dns *dnsMsg, qtype uint16) (cname string, addrs []dnsRR, err error) { addrs = make([]dnsRR, 0, len(dns.answer)) if dns.rcode == dnsRcodeNameError && dns.recursion_available { - return "", nil, &DNSError{Error: noSuchHost, Name: name} + return "", nil, &DNSError{Err: noSuchHost, Name: name} } if dns.rcode != dnsRcodeSuccess { // None of the error codes make sense // for the query we sent. If we didn't get // a name error and we didn't get success, // the server is behaving incorrectly. - return "", nil, &DNSError{Error: "server misbehaving", Name: name, Server: server} + return "", nil, &DNSError{Err: "server misbehaving", Name: name, Server: server} } // Look for the name. @@ -107,12 +106,12 @@ Cname: } } if len(addrs) == 0 { - return "", nil, &DNSError{Error: noSuchHost, Name: name, Server: server} + return "", nil, &DNSError{Err: noSuchHost, Name: name, Server: server} } return name, addrs, nil } - return "", nil, &DNSError{Error: "too many redirects", Name: name, Server: server} + return "", nil, &DNSError{Err: "too many redirects", Name: name, Server: server} } func isDomainName(s string) bool { diff --git a/src/pkg/net/dnsclient_unix.go b/src/pkg/net/dnsclient_unix.go index eb7db5e270..e321ed9abe 100644 --- a/src/pkg/net/dnsclient_unix.go +++ b/src/pkg/net/dnsclient_unix.go @@ -17,7 +17,6 @@ package net import ( - "os" "rand" "sync" "time" @@ -25,9 +24,9 @@ import ( // Send a request on the connection and hope for a reply. // Up to cfg.attempts attempts. -func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Error) { +func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, error) { if len(name) >= 256 { - return nil, &DNSError{Error: "name too long", Name: name} + return nil, &DNSError{Err: "name too long", Name: name} } out := new(dnsMsg) out.id = uint16(rand.Int()) ^ uint16(time.Nanoseconds()) @@ -37,7 +36,7 @@ func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Er out.recursion_desired = true msg, ok := out.Pack() if !ok { - return nil, &DNSError{Error: "internal error - cannot pack message", Name: name} + return nil, &DNSError{Err: "internal error - cannot pack message", Name: name} } for attempt := 0; attempt < cfg.attempts; attempt++ { @@ -67,14 +66,14 @@ func exchange(cfg *dnsConfig, c Conn, name string, qtype uint16) (*dnsMsg, os.Er if a := c.RemoteAddr(); a != nil { server = a.String() } - return nil, &DNSError{Error: "no answer from server", Name: name, Server: server, IsTimeout: true} + return nil, &DNSError{Err: "no answer from server", Name: name, Server: server, IsTimeout: true} } // Do a lookup for a single name, which must be rooted // (otherwise answer will not find the answers). -func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) { +func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs []dnsRR, err error) { if len(cfg.servers) == 0 { - return "", nil, &DNSError{Error: "no DNS servers", Name: name} + return "", nil, &DNSError{Err: "no DNS servers", Name: name} } for i := 0; i < len(cfg.servers); i++ { // Calling Dial here is scary -- we have to be sure @@ -96,7 +95,7 @@ func tryOneName(cfg *dnsConfig, name string, qtype uint16) (cname string, addrs continue } cname, addrs, err = answer(name, server, msg, qtype) - if err == nil || err.(*DNSError).Error == noSuchHost { + if err == nil || err.(*DNSError).Err == noSuchHost { break } } @@ -123,15 +122,15 @@ func convertRR_AAAA(records []dnsRR) []IP { } var cfg *dnsConfig -var dnserr os.Error +var dnserr error func loadConfig() { cfg, dnserr = dnsReadConfig() } var onceLoadConfig sync.Once -func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err os.Error) { +func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err error) { if !isDomainName(name) { - return name, nil, &DNSError{Error: "invalid domain name", Name: name} + return name, nil, &DNSError{Err: "invalid domain name", Name: name} } onceLoadConfig.Do(loadConfig) if dnserr != nil || cfg == nil { @@ -186,7 +185,7 @@ func lookup(name string, qtype uint16) (cname string, addrs []dnsRR, err os.Erro // Normally we let cgo use the C library resolver instead of // depending on our lookup code, so that Go and C get the same // answers. -func goLookupHost(name string) (addrs []string, err os.Error) { +func goLookupHost(name string) (addrs []string, err error) { // Use entries from /etc/hosts if they match. addrs = lookupStaticHost(name) if len(addrs) > 0 { @@ -214,7 +213,7 @@ func goLookupHost(name string) (addrs []string, err os.Error) { // Normally we let cgo use the C library resolver instead of // depending on our lookup code, so that Go and C get the same // answers. -func goLookupIP(name string) (addrs []IP, err os.Error) { +func goLookupIP(name string) (addrs []IP, err error) { // Use entries from /etc/hosts if possible. haddrs := lookupStaticHost(name) if len(haddrs) > 0 { @@ -260,7 +259,7 @@ func goLookupIP(name string) (addrs []IP, err os.Error) { // Normally we let cgo use the C library resolver instead of // depending on our lookup code, so that Go and C get the same // answers. -func goLookupCNAME(name string) (cname string, err os.Error) { +func goLookupCNAME(name string) (cname string, err error) { onceLoadConfig.Do(loadConfig) if dnserr != nil || cfg == nil { err = dnserr diff --git a/src/pkg/net/dnsconfig.go b/src/pkg/net/dnsconfig.go index afc0599177..379fec95b8 100644 --- a/src/pkg/net/dnsconfig.go +++ b/src/pkg/net/dnsconfig.go @@ -8,8 +8,6 @@ package net -import "os" - type dnsConfig struct { servers []string // servers to use search []string // suffixes to append to local name @@ -19,14 +17,14 @@ type dnsConfig struct { rotate bool // round robin among servers } -var dnsconfigError os.Error +var dnsconfigError error type DNSConfigError struct { - Error os.Error + Err error } -func (e *DNSConfigError) String() string { - return "error reading DNS config: " + e.Error.String() +func (e *DNSConfigError) Error() string { + return "error reading DNS config: " + e.Err.Error() } func (e *DNSConfigError) Timeout() bool { return false } @@ -36,7 +34,7 @@ func (e *DNSConfigError) Temporary() bool { return false } // TODO(rsc): Supposed to call uname() and chop the beginning // of the host name to get the default search domain. // We assume it's in resolv.conf anyway. -func dnsReadConfig() (*dnsConfig, os.Error) { +func dnsReadConfig() (*dnsConfig, error) { file, err := open("/etc/resolv.conf") if err != nil { return nil, &DNSConfigError{err} diff --git a/src/pkg/net/fd.go b/src/pkg/net/fd.go index 80d40af766..025075de48 100644 --- a/src/pkg/net/fd.go +++ b/src/pkg/net/fd.go @@ -46,7 +46,7 @@ type netFD struct { type InvalidConnError struct{} -func (e *InvalidConnError) String() string { return "invalid net.Conn" } +func (e *InvalidConnError) Error() string { return "invalid net.Conn" } func (e *InvalidConnError) Temporary() bool { return false } func (e *InvalidConnError) Timeout() bool { return false } @@ -126,7 +126,7 @@ func (s *pollServer) AddFD(fd *netFD, mode int) { wake, err := s.poll.AddFD(intfd, mode, false) if err != nil { - panic("pollServer AddFD " + err.String()) + panic("pollServer AddFD " + err.Error()) } if wake { doWakeup = true @@ -227,7 +227,7 @@ func (s *pollServer) Run() { } fd, mode, err := s.poll.WaitFD(s, t) if err != nil { - print("pollServer WaitFD: ", err.String(), "\n") + print("pollServer WaitFD: ", err.Error(), "\n") return } if fd < 0 { @@ -271,12 +271,12 @@ var onceStartServer sync.Once func startServer() { p, err := newPollServer() if err != nil { - print("Start pollServer: ", err.String(), "\n") + print("Start pollServer: ", err.Error(), "\n") } pollserver = p } -func newFD(fd, family, proto int, net string) (f *netFD, err os.Error) { +func newFD(fd, family, proto int, net string) (f *netFD, err error) { onceStartServer.Do(startServer) if e := syscall.SetNonblock(fd, true); e != 0 { return nil, os.Errno(e) @@ -305,7 +305,7 @@ func (fd *netFD) setAddr(laddr, raddr Addr) { fd.sysfile = os.NewFile(fd.sysfd, fd.net+":"+ls+"->"+rs) } -func (fd *netFD) connect(ra syscall.Sockaddr) (err os.Error) { +func (fd *netFD) connect(ra syscall.Sockaddr) (err error) { e := syscall.Connect(fd.sysfd, ra) if e == syscall.EINPROGRESS { var errno int @@ -346,7 +346,7 @@ func (fd *netFD) decref() { fd.sysmu.Unlock() } -func (fd *netFD) Close() os.Error { +func (fd *netFD) Close() error { if fd == nil || fd.sysfile == nil { return os.EINVAL } @@ -358,7 +358,7 @@ func (fd *netFD) Close() os.Error { return nil } -func (fd *netFD) shutdown(how int) os.Error { +func (fd *netFD) shutdown(how int) error { if fd == nil || fd.sysfile == nil { return os.EINVAL } @@ -369,15 +369,15 @@ func (fd *netFD) shutdown(how int) os.Error { return nil } -func (fd *netFD) CloseRead() os.Error { +func (fd *netFD) CloseRead() error { return fd.shutdown(syscall.SHUT_RD) } -func (fd *netFD) CloseWrite() os.Error { +func (fd *netFD) CloseWrite() error { return fd.shutdown(syscall.SHUT_WR) } -func (fd *netFD) Read(p []byte) (n int, err os.Error) { +func (fd *netFD) Read(p []byte) (n int, err error) { if fd == nil { return 0, os.EINVAL } @@ -393,7 +393,7 @@ func (fd *netFD) Read(p []byte) (n int, err os.Error) { } else { fd.rdeadline = 0 } - var oserr os.Error + var oserr error for { var errno int n, errno = syscall.Read(fd.sysfile.Fd(), p) @@ -405,7 +405,7 @@ func (fd *netFD) Read(p []byte) (n int, err os.Error) { n = 0 oserr = os.Errno(errno) } else if n == 0 && errno == 0 && fd.proto != syscall.SOCK_DGRAM { - err = os.EOF + err = io.EOF } break } @@ -415,7 +415,7 @@ func (fd *netFD) Read(p []byte) (n int, err os.Error) { return } -func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err os.Error) { +func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err error) { if fd == nil || fd.sysfile == nil { return 0, nil, os.EINVAL } @@ -428,7 +428,7 @@ func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err os.Error) { } else { fd.rdeadline = 0 } - var oserr os.Error + var oserr error for { var errno int n, sa, errno = syscall.Recvfrom(fd.sysfd, p, 0) @@ -448,7 +448,7 @@ func (fd *netFD) ReadFrom(p []byte) (n int, sa syscall.Sockaddr, err os.Error) { return } -func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err os.Error) { +func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error) { if fd == nil || fd.sysfile == nil { return 0, 0, 0, nil, os.EINVAL } @@ -461,7 +461,7 @@ func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.S } else { fd.rdeadline = 0 } - var oserr os.Error + var oserr error for { var errno int n, oobn, flags, sa, errno = syscall.Recvmsg(fd.sysfd, p, oob, 0) @@ -473,7 +473,7 @@ func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.S oserr = os.Errno(errno) } if n == 0 { - oserr = os.EOF + oserr = io.EOF } break } @@ -484,7 +484,7 @@ func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.S return } -func (fd *netFD) Write(p []byte) (n int, err os.Error) { +func (fd *netFD) Write(p []byte) (n int, err error) { if fd == nil { return 0, os.EINVAL } @@ -501,7 +501,7 @@ func (fd *netFD) Write(p []byte) (n int, err os.Error) { fd.wdeadline = 0 } nn := 0 - var oserr os.Error + var oserr error for { n, errno := syscall.Write(fd.sysfile.Fd(), p[nn:]) @@ -531,7 +531,7 @@ func (fd *netFD) Write(p []byte) (n int, err os.Error) { return nn, err } -func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err os.Error) { +func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err error) { if fd == nil || fd.sysfile == nil { return 0, os.EINVAL } @@ -544,7 +544,7 @@ func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err os.Error) { } else { fd.wdeadline = 0 } - var oserr os.Error + var oserr error for { errno := syscall.Sendto(fd.sysfd, p, 0, sa) if errno == syscall.EAGAIN && fd.wdeadline >= 0 { @@ -564,7 +564,7 @@ func (fd *netFD) WriteTo(p []byte, sa syscall.Sockaddr) (n int, err os.Error) { return } -func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err os.Error) { +func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) { if fd == nil || fd.sysfile == nil { return 0, 0, os.EINVAL } @@ -577,7 +577,7 @@ func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oob } else { fd.wdeadline = 0 } - var oserr os.Error + var oserr error for { var errno int errno = syscall.Sendmsg(fd.sysfd, p, oob, sa, 0) @@ -599,7 +599,7 @@ func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oob return } -func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os.Error) { +func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err error) { if fd == nil || fd.sysfile == nil { return nil, os.EINVAL } @@ -647,7 +647,7 @@ func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os. return nfd, nil } -func (fd *netFD) dup() (f *os.File, err os.Error) { +func (fd *netFD) dup() (f *os.File, err error) { ns, e := syscall.Dup(fd.sysfd) if e != 0 { return nil, &OpError{"dup", fd.net, fd.laddr, os.Errno(e)} diff --git a/src/pkg/net/fd_darwin.go b/src/pkg/net/fd_darwin.go index 7e3d549ebc..c25a510f34 100644 --- a/src/pkg/net/fd_darwin.go +++ b/src/pkg/net/fd_darwin.go @@ -7,6 +7,7 @@ package net import ( + "errors" "os" "syscall" ) @@ -21,7 +22,7 @@ type pollster struct { kbuf [1]syscall.Kevent_t } -func newpollster() (p *pollster, err os.Error) { +func newpollster() (p *pollster, err error) { p = new(pollster) var e int if p.kq, e = syscall.Kqueue(); e != 0 { @@ -31,7 +32,7 @@ func newpollster() (p *pollster, err os.Error) { return p, nil } -func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) { +func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, error) { // pollServer is locked. var kmode int @@ -56,7 +57,7 @@ func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) { return false, os.NewSyscallError("kevent", e) } if n != 1 || (ev.Flags&syscall.EV_ERROR) == 0 || int(ev.Ident) != fd || int(ev.Filter) != kmode { - return false, os.NewError("kqueue phase error") + return false, errors.New("kqueue phase error") } if ev.Data != 0 { return false, os.Errno(int(ev.Data)) @@ -81,7 +82,7 @@ func (p *pollster) DelFD(fd int, mode int) { syscall.Kevent(p.kq, p.kbuf[0:], p.kbuf[0:], nil) } -func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.Error) { +func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err error) { var t *syscall.Timespec for len(p.events) == 0 { if nsec > 0 { @@ -117,4 +118,4 @@ func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.E return fd, mode, nil } -func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } +func (p *pollster) Close() error { return os.NewSyscallError("close", syscall.Close(p.kq)) } diff --git a/src/pkg/net/fd_freebsd.go b/src/pkg/net/fd_freebsd.go index e50883e940..f61008a2fe 100644 --- a/src/pkg/net/fd_freebsd.go +++ b/src/pkg/net/fd_freebsd.go @@ -21,7 +21,7 @@ type pollster struct { kbuf [1]syscall.Kevent_t } -func newpollster() (p *pollster, err os.Error) { +func newpollster() (p *pollster, err error) { p = new(pollster) var e int if p.kq, e = syscall.Kqueue(); e != 0 { @@ -31,7 +31,7 @@ func newpollster() (p *pollster, err os.Error) { return p, nil } -func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) { +func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, error) { // pollServer is locked. var kmode int @@ -77,7 +77,7 @@ func (p *pollster) DelFD(fd int, mode int) { syscall.Kevent(p.kq, p.kbuf[:], nil, nil) } -func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.Error) { +func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err error) { var t *syscall.Timespec for len(p.events) == 0 { if nsec > 0 { @@ -113,4 +113,4 @@ func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.E return fd, mode, nil } -func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } +func (p *pollster) Close() error { return os.NewSyscallError("close", syscall.Close(p.kq)) } diff --git a/src/pkg/net/fd_linux.go b/src/pkg/net/fd_linux.go index c860c842af..56c6a2890e 100644 --- a/src/pkg/net/fd_linux.go +++ b/src/pkg/net/fd_linux.go @@ -33,7 +33,7 @@ type pollster struct { ctlEvent syscall.EpollEvent } -func newpollster() (p *pollster, err os.Error) { +func newpollster() (p *pollster, err error) { p = new(pollster) var e int @@ -47,7 +47,7 @@ func newpollster() (p *pollster, err os.Error) { return p, nil } -func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) { +func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, error) { // pollServer is locked. var already bool @@ -130,7 +130,7 @@ func (p *pollster) DelFD(fd int, mode int) { } } -func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.Error) { +func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err error) { for len(p.waitEvents) == 0 { var msec int = -1 if nsec > 0 { @@ -177,6 +177,6 @@ func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.E return fd, 'r', nil } -func (p *pollster) Close() os.Error { +func (p *pollster) Close() error { return os.NewSyscallError("close", syscall.Close(p.epfd)) } diff --git a/src/pkg/net/fd_openbsd.go b/src/pkg/net/fd_openbsd.go index e50883e940..f61008a2fe 100644 --- a/src/pkg/net/fd_openbsd.go +++ b/src/pkg/net/fd_openbsd.go @@ -21,7 +21,7 @@ type pollster struct { kbuf [1]syscall.Kevent_t } -func newpollster() (p *pollster, err os.Error) { +func newpollster() (p *pollster, err error) { p = new(pollster) var e int if p.kq, e = syscall.Kqueue(); e != 0 { @@ -31,7 +31,7 @@ func newpollster() (p *pollster, err os.Error) { return p, nil } -func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, os.Error) { +func (p *pollster) AddFD(fd int, mode int, repeat bool) (bool, error) { // pollServer is locked. var kmode int @@ -77,7 +77,7 @@ func (p *pollster) DelFD(fd int, mode int) { syscall.Kevent(p.kq, p.kbuf[:], nil, nil) } -func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.Error) { +func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err error) { var t *syscall.Timespec for len(p.events) == 0 { if nsec > 0 { @@ -113,4 +113,4 @@ func (p *pollster) WaitFD(s *pollServer, nsec int64) (fd int, mode int, err os.E return fd, mode, nil } -func (p *pollster) Close() os.Error { return os.NewSyscallError("close", syscall.Close(p.kq)) } +func (p *pollster) Close() error { return os.NewSyscallError("close", syscall.Close(p.kq)) } diff --git a/src/pkg/net/fd_windows.go b/src/pkg/net/fd_windows.go index 8e8b3b746d..ce228e91ed 100644 --- a/src/pkg/net/fd_windows.go +++ b/src/pkg/net/fd_windows.go @@ -5,6 +5,7 @@ package net import ( + "io" "os" "runtime" "sync" @@ -15,11 +16,11 @@ import ( type InvalidConnError struct{} -func (e *InvalidConnError) String() string { return "invalid net.Conn" } +func (e *InvalidConnError) Error() string { return "invalid net.Conn" } func (e *InvalidConnError) Temporary() bool { return false } func (e *InvalidConnError) Timeout() bool { return false } -var initErr os.Error +var initErr error func init() { var d syscall.WSAData @@ -151,7 +152,7 @@ func (s *ioSrv) ProcessRemoteIO() { // ExecIO executes a single io operation. It either executes it // inline, or, if timeouts are employed, passes the request onto // a special goroutine and waits for completion or cancels request. -func (s *ioSrv) ExecIO(oi anOpIface, deadline_delta int64) (n int, err os.Error) { +func (s *ioSrv) ExecIO(oi anOpIface, deadline_delta int64) (n int, err error) { var e int o := oi.Op() if deadline_delta > 0 { @@ -249,7 +250,7 @@ func allocFD(fd syscall.Handle, family, proto int, net string) (f *netFD) { return f } -func newFD(fd syscall.Handle, family, proto int, net string) (f *netFD, err os.Error) { +func newFD(fd syscall.Handle, family, proto int, net string) (f *netFD, err error) { if initErr != nil { return nil, initErr } @@ -266,7 +267,7 @@ func (fd *netFD) setAddr(laddr, raddr Addr) { fd.raddr = raddr } -func (fd *netFD) connect(ra syscall.Sockaddr) (err os.Error) { +func (fd *netFD) connect(ra syscall.Sockaddr) (err error) { e := syscall.Connect(fd.sysfd, ra) if e != 0 { return os.Errno(e) @@ -300,7 +301,7 @@ func (fd *netFD) decref() { fd.sysmu.Unlock() } -func (fd *netFD) Close() os.Error { +func (fd *netFD) Close() error { if fd == nil || fd.sysfd == syscall.InvalidHandle { return os.EINVAL } @@ -312,7 +313,7 @@ func (fd *netFD) Close() os.Error { return nil } -func (fd *netFD) shutdown(how int) os.Error { +func (fd *netFD) shutdown(how int) error { if fd == nil || fd.sysfd == syscall.InvalidHandle { return os.EINVAL } @@ -323,11 +324,11 @@ func (fd *netFD) shutdown(how int) os.Error { return nil } -func (fd *netFD) CloseRead() os.Error { +func (fd *netFD) CloseRead() error { return fd.shutdown(syscall.SHUT_RD) } -func (fd *netFD) CloseWrite() os.Error { +func (fd *netFD) CloseWrite() error { return fd.shutdown(syscall.SHUT_WR) } @@ -346,7 +347,7 @@ func (o *readOp) Name() string { return "WSARecv" } -func (fd *netFD) Read(buf []byte) (n int, err os.Error) { +func (fd *netFD) Read(buf []byte) (n int, err error) { if fd == nil { return 0, os.EINVAL } @@ -361,7 +362,7 @@ func (fd *netFD) Read(buf []byte) (n int, err os.Error) { o.Init(fd, buf, 'r') n, err = iosrv.ExecIO(&o, fd.rdeadline_delta) if err == nil && n == 0 { - err = os.EOF + err = io.EOF } return } @@ -383,7 +384,7 @@ func (o *readFromOp) Name() string { return "WSARecvFrom" } -func (fd *netFD) ReadFrom(buf []byte) (n int, sa syscall.Sockaddr, err os.Error) { +func (fd *netFD) ReadFrom(buf []byte) (n int, sa syscall.Sockaddr, err error) { if fd == nil { return 0, nil, os.EINVAL } @@ -423,7 +424,7 @@ func (o *writeOp) Name() string { return "WSASend" } -func (fd *netFD) Write(buf []byte) (n int, err os.Error) { +func (fd *netFD) Write(buf []byte) (n int, err error) { if fd == nil { return 0, os.EINVAL } @@ -455,7 +456,7 @@ func (o *writeToOp) Name() string { return "WSASendto" } -func (fd *netFD) WriteTo(buf []byte, sa syscall.Sockaddr) (n int, err os.Error) { +func (fd *netFD) WriteTo(buf []byte, sa syscall.Sockaddr) (n int, err error) { if fd == nil { return 0, os.EINVAL } @@ -494,7 +495,7 @@ func (o *acceptOp) Name() string { return "AcceptEx" } -func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os.Error) { +func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err error) { if fd == nil || fd.sysfd == syscall.InvalidHandle { return nil, os.EINVAL } @@ -551,15 +552,15 @@ func (fd *netFD) accept(toAddr func(syscall.Sockaddr) Addr) (nfd *netFD, err os. // Unimplemented functions. -func (fd *netFD) dup() (f *os.File, err os.Error) { +func (fd *netFD) dup() (f *os.File, err error) { // TODO: Implement this return nil, os.NewSyscallError("dup", syscall.EWINDOWS) } -func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err os.Error) { +func (fd *netFD) ReadMsg(p []byte, oob []byte) (n, oobn, flags int, sa syscall.Sockaddr, err error) { return 0, 0, 0, nil, os.EAFNOSUPPORT } -func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err os.Error) { +func (fd *netFD) WriteMsg(p []byte, oob []byte, sa syscall.Sockaddr) (n int, oobn int, err error) { return 0, 0, os.EAFNOSUPPORT } diff --git a/src/pkg/net/file.go b/src/pkg/net/file.go index ed2559d8c3..0ad869dbd5 100644 --- a/src/pkg/net/file.go +++ b/src/pkg/net/file.go @@ -11,7 +11,7 @@ import ( "syscall" ) -func newFileFD(f *os.File) (nfd *netFD, err os.Error) { +func newFileFD(f *os.File) (nfd *netFD, err error) { fd, errno := syscall.Dup(f.Fd()) if errno != 0 { return nil, os.NewSyscallError("dup", errno) @@ -67,7 +67,7 @@ func newFileFD(f *os.File) (nfd *netFD, err os.Error) { // the open file f. It is the caller's responsibility to close f when // finished. Closing c does not affect f, and closing f does not // affect c. -func FileConn(f *os.File) (c Conn, err os.Error) { +func FileConn(f *os.File) (c Conn, err error) { fd, err := newFileFD(f) if err != nil { return nil, err @@ -90,7 +90,7 @@ func FileConn(f *os.File) (c Conn, err os.Error) { // to the open file f. It is the caller's responsibility to close l // when finished. Closing c does not affect l, and closing l does not // affect c. -func FileListener(f *os.File) (l Listener, err os.Error) { +func FileListener(f *os.File) (l Listener, err error) { fd, err := newFileFD(f) if err != nil { return nil, err @@ -109,7 +109,7 @@ func FileListener(f *os.File) (l Listener, err os.Error) { // corresponding to the open file f. It is the caller's // responsibility to close f when finished. Closing c does not affect // f, and closing f does not affect c. -func FilePacketConn(f *os.File) (c PacketConn, err os.Error) { +func FilePacketConn(f *os.File) (c PacketConn, err error) { fd, err := newFileFD(f) if err != nil { return nil, err diff --git a/src/pkg/net/file_plan9.go b/src/pkg/net/file_plan9.go index a07e743318..06d7cc8984 100644 --- a/src/pkg/net/file_plan9.go +++ b/src/pkg/net/file_plan9.go @@ -12,7 +12,7 @@ import ( // the open file f. It is the caller's responsibility to close f when // finished. Closing c does not affect f, and closing f does not // affect c. -func FileConn(f *os.File) (c Conn, err os.Error) { +func FileConn(f *os.File) (c Conn, err error) { return nil, os.EPLAN9 } @@ -20,7 +20,7 @@ func FileConn(f *os.File) (c Conn, err os.Error) { // to the open file f. It is the caller's responsibility to close l // when finished. Closing c does not affect l, and closing l does not // affect c. -func FileListener(f *os.File) (l Listener, err os.Error) { +func FileListener(f *os.File) (l Listener, err error) { return nil, os.EPLAN9 } @@ -28,6 +28,6 @@ func FileListener(f *os.File) (l Listener, err os.Error) { // corresponding to the open file f. It is the caller's // responsibility to close f when finished. Closing c does not affect // f, and closing f does not affect c. -func FilePacketConn(f *os.File) (c PacketConn, err os.Error) { +func FilePacketConn(f *os.File) (c PacketConn, err error) { return nil, os.EPLAN9 } diff --git a/src/pkg/net/file_test.go b/src/pkg/net/file_test.go index 0fa6740769..7867fa8df3 100644 --- a/src/pkg/net/file_test.go +++ b/src/pkg/net/file_test.go @@ -14,17 +14,17 @@ import ( type listenerFile interface { Listener - File() (f *os.File, err os.Error) + File() (f *os.File, err error) } type packetConnFile interface { PacketConn - File() (f *os.File, err os.Error) + File() (f *os.File, err error) } type connFile interface { Conn - File() (f *os.File, err os.Error) + File() (f *os.File, err error) } func testFileListener(t *testing.T, net, laddr string) { diff --git a/src/pkg/net/file_windows.go b/src/pkg/net/file_windows.go index 94aa583755..c50c32e210 100644 --- a/src/pkg/net/file_windows.go +++ b/src/pkg/net/file_windows.go @@ -9,17 +9,17 @@ import ( "syscall" ) -func FileConn(f *os.File) (c Conn, err os.Error) { +func FileConn(f *os.File) (c Conn, err error) { // TODO: Implement this return nil, os.NewSyscallError("FileConn", syscall.EWINDOWS) } -func FileListener(f *os.File) (l Listener, err os.Error) { +func FileListener(f *os.File) (l Listener, err error) { // TODO: Implement this return nil, os.NewSyscallError("FileListener", syscall.EWINDOWS) } -func FilePacketConn(f *os.File) (c PacketConn, err os.Error) { +func FilePacketConn(f *os.File) (c PacketConn, err error) { // TODO: Implement this return nil, os.NewSyscallError("FilePacketConn", syscall.EWINDOWS) } diff --git a/src/pkg/net/interface.go b/src/pkg/net/interface.go index 2696b7f4c5..95486a6301 100644 --- a/src/pkg/net/interface.go +++ b/src/pkg/net/interface.go @@ -8,8 +8,8 @@ package net import ( "bytes" + "errors" "fmt" - "os" ) // A HardwareAddr represents a physical hardware address. @@ -34,7 +34,7 @@ func (a HardwareAddr) String() string { // 01-23-45-67-89-ab-cd-ef // 0123.4567.89ab // 0123.4567.89ab.cdef -func ParseMAC(s string) (hw HardwareAddr, err os.Error) { +func ParseMAC(s string) (hw HardwareAddr, err error) { if len(s) < 14 { goto error } @@ -80,7 +80,7 @@ func ParseMAC(s string) (hw HardwareAddr, err os.Error) { return hw, nil error: - return nil, os.NewError("invalid MAC address: " + s) + return nil, errors.New("invalid MAC address: " + s) } // Interface represents a mapping between network interface name @@ -129,37 +129,37 @@ func (f Flags) String() string { } // Addrs returns interface addresses for a specific interface. -func (ifi *Interface) Addrs() ([]Addr, os.Error) { +func (ifi *Interface) Addrs() ([]Addr, error) { if ifi == nil { - return nil, os.NewError("net: invalid interface") + return nil, errors.New("net: invalid interface") } return interfaceAddrTable(ifi.Index) } // MulticastAddrs returns multicast, joined group addresses for // a specific interface. -func (ifi *Interface) MulticastAddrs() ([]Addr, os.Error) { +func (ifi *Interface) MulticastAddrs() ([]Addr, error) { if ifi == nil { - return nil, os.NewError("net: invalid interface") + return nil, errors.New("net: invalid interface") } return interfaceMulticastAddrTable(ifi.Index) } // Interfaces returns a list of the systems's network interfaces. -func Interfaces() ([]Interface, os.Error) { +func Interfaces() ([]Interface, error) { return interfaceTable(0) } // InterfaceAddrs returns a list of the system's network interface // addresses. -func InterfaceAddrs() ([]Addr, os.Error) { +func InterfaceAddrs() ([]Addr, error) { return interfaceAddrTable(0) } // InterfaceByIndex returns the interface specified by index. -func InterfaceByIndex(index int) (*Interface, os.Error) { +func InterfaceByIndex(index int) (*Interface, error) { if index <= 0 { - return nil, os.NewError("net: invalid interface index") + return nil, errors.New("net: invalid interface index") } ift, err := interfaceTable(index) if err != nil { @@ -168,13 +168,13 @@ func InterfaceByIndex(index int) (*Interface, os.Error) { for _, ifi := range ift { return &ifi, nil } - return nil, os.NewError("net: no such interface") + return nil, errors.New("net: no such interface") } // InterfaceByName returns the interface specified by name. -func InterfaceByName(name string) (*Interface, os.Error) { +func InterfaceByName(name string) (*Interface, error) { if name == "" { - return nil, os.NewError("net: invalid interface name") + return nil, errors.New("net: invalid interface name") } ift, err := interfaceTable(0) if err != nil { @@ -185,5 +185,5 @@ func InterfaceByName(name string) (*Interface, os.Error) { return &ifi, nil } } - return nil, os.NewError("net: no such interface") + return nil, errors.New("net: no such interface") } diff --git a/src/pkg/net/interface_bsd.go b/src/pkg/net/interface_bsd.go index 54fa5ddeb6..b026e01104 100644 --- a/src/pkg/net/interface_bsd.go +++ b/src/pkg/net/interface_bsd.go @@ -17,7 +17,7 @@ import ( // If the ifindex is zero, interfaceTable returns mappings of all // network interfaces. Otheriwse it returns a mapping of a specific // interface. -func interfaceTable(ifindex int) ([]Interface, os.Error) { +func interfaceTable(ifindex int) ([]Interface, error) { var ( tab []byte e int @@ -51,7 +51,7 @@ func interfaceTable(ifindex int) ([]Interface, os.Error) { return ift, nil } -func newLink(m *syscall.InterfaceMessage) ([]Interface, os.Error) { +func newLink(m *syscall.InterfaceMessage) ([]Interface, error) { var ift []Interface sas, e := syscall.ParseRoutingSockaddr(m) @@ -107,7 +107,7 @@ func linkFlags(rawFlags int32) Flags { // If the ifindex is zero, interfaceAddrTable returns addresses // for all network interfaces. Otherwise it returns addresses // for a specific interface. -func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceAddrTable(ifindex int) ([]Addr, error) { var ( tab []byte e int @@ -141,7 +141,7 @@ func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { return ifat, nil } -func newAddr(m *syscall.InterfaceAddrMessage) ([]Addr, os.Error) { +func newAddr(m *syscall.InterfaceAddrMessage) ([]Addr, error) { var ifat []Addr sas, e := syscall.ParseRoutingSockaddr(m) diff --git a/src/pkg/net/interface_darwin.go b/src/pkg/net/interface_darwin.go index a7b68ad7f7..1472afb884 100644 --- a/src/pkg/net/interface_darwin.go +++ b/src/pkg/net/interface_darwin.go @@ -14,7 +14,7 @@ import ( // If the ifindex is zero, interfaceMulticastAddrTable returns // addresses for all network interfaces. Otherwise it returns // addresses for a specific interface. -func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) { var ( tab []byte e int @@ -48,7 +48,7 @@ func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { return ifmat, nil } -func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, os.Error) { +func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, error) { var ifmat []Addr sas, e := syscall.ParseRoutingSockaddr(m) diff --git a/src/pkg/net/interface_freebsd.go b/src/pkg/net/interface_freebsd.go index 20f506b08b..b0274f68d7 100644 --- a/src/pkg/net/interface_freebsd.go +++ b/src/pkg/net/interface_freebsd.go @@ -14,7 +14,7 @@ import ( // If the ifindex is zero, interfaceMulticastAddrTable returns // addresses for all network interfaces. Otherwise it returns // addresses for a specific interface. -func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) { var ( tab []byte e int @@ -48,7 +48,7 @@ func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { return ifmat, nil } -func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, os.Error) { +func newMulticastAddr(m *syscall.InterfaceMulticastAddrMessage) ([]Addr, error) { var ifmat []Addr sas, e := syscall.ParseRoutingSockaddr(m) diff --git a/src/pkg/net/interface_linux.go b/src/pkg/net/interface_linux.go index 36ae04ffa7..cd0339d61b 100644 --- a/src/pkg/net/interface_linux.go +++ b/src/pkg/net/interface_linux.go @@ -16,7 +16,7 @@ import ( // If the ifindex is zero, interfaceTable returns mappings of all // network interfaces. Otheriwse it returns a mapping of a specific // interface. -func interfaceTable(ifindex int) ([]Interface, os.Error) { +func interfaceTable(ifindex int) ([]Interface, error) { var ( ift []Interface tab []byte @@ -101,11 +101,11 @@ func linkFlags(rawFlags uint32) Flags { // If the ifindex is zero, interfaceAddrTable returns addresses // for all network interfaces. Otherwise it returns addresses // for a specific interface. -func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceAddrTable(ifindex int) ([]Addr, error) { var ( tab []byte e int - err os.Error + err error ifat []Addr msgs []syscall.NetlinkMessage ) @@ -128,7 +128,7 @@ func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { return ifat, nil } -func addrTable(msgs []syscall.NetlinkMessage, ifindex int) ([]Addr, os.Error) { +func addrTable(msgs []syscall.NetlinkMessage, ifindex int) ([]Addr, error) { var ifat []Addr for _, m := range msgs { @@ -175,10 +175,10 @@ func newAddr(attrs []syscall.NetlinkRouteAttr, family int) []Addr { // If the ifindex is zero, interfaceMulticastAddrTable returns // addresses for all network interfaces. Otherwise it returns // addresses for a specific interface. -func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) { var ( ifi *Interface - err os.Error + err error ) if ifindex > 0 { diff --git a/src/pkg/net/interface_openbsd.go b/src/pkg/net/interface_openbsd.go index f18149393a..d8adb46765 100644 --- a/src/pkg/net/interface_openbsd.go +++ b/src/pkg/net/interface_openbsd.go @@ -6,11 +6,9 @@ package net -import "os" - // If the ifindex is zero, interfaceMulticastAddrTable returns // addresses for all network interfaces. Otherwise it returns // addresses for a specific interface. -func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) { return nil, nil } diff --git a/src/pkg/net/interface_stub.go b/src/pkg/net/interface_stub.go index 282b38b5e4..4876b3af35 100644 --- a/src/pkg/net/interface_stub.go +++ b/src/pkg/net/interface_stub.go @@ -8,25 +8,23 @@ package net -import "os" - // If the ifindex is zero, interfaceTable returns mappings of all // network interfaces. Otheriwse it returns a mapping of a specific // interface. -func interfaceTable(ifindex int) ([]Interface, os.Error) { +func interfaceTable(ifindex int) ([]Interface, error) { return nil, nil } // If the ifindex is zero, interfaceAddrTable returns addresses // for all network interfaces. Otherwise it returns addresses // for a specific interface. -func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceAddrTable(ifindex int) ([]Addr, error) { return nil, nil } // If the ifindex is zero, interfaceMulticastAddrTable returns // addresses for all network interfaces. Otherwise it returns // addresses for a specific interface. -func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) { return nil, nil } diff --git a/src/pkg/net/interface_test.go b/src/pkg/net/interface_test.go index c918f247f9..cc614910fa 100644 --- a/src/pkg/net/interface_test.go +++ b/src/pkg/net/interface_test.go @@ -6,7 +6,6 @@ package net import ( "bytes" - "os" "reflect" "strings" "testing" @@ -101,11 +100,11 @@ var mactests = []struct { {"0123.4567.89AB.CDEF", HardwareAddr{1, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, ""}, } -func match(err os.Error, s string) bool { +func match(err error, s string) bool { if s == "" { return err == nil } - return err != nil && strings.Contains(err.String(), s) + return err != nil && strings.Contains(err.Error(), s) } func TestParseMAC(t *testing.T) { diff --git a/src/pkg/net/interface_windows.go b/src/pkg/net/interface_windows.go index 7f5169c879..a1c8d95161 100644 --- a/src/pkg/net/interface_windows.go +++ b/src/pkg/net/interface_windows.go @@ -21,7 +21,7 @@ func bytePtrToString(p *uint8) string { return string(a[:i]) } -func getAdapterList() (*syscall.IpAdapterInfo, os.Error) { +func getAdapterList() (*syscall.IpAdapterInfo, error) { b := make([]byte, 1000) l := uint32(len(b)) a := (*syscall.IpAdapterInfo)(unsafe.Pointer(&b[0])) @@ -37,7 +37,7 @@ func getAdapterList() (*syscall.IpAdapterInfo, os.Error) { return a, nil } -func getInterfaceList() ([]syscall.InterfaceInfo, os.Error) { +func getInterfaceList() ([]syscall.InterfaceInfo, error) { s, e := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP) if e != 0 { return nil, os.NewSyscallError("Socket", e) @@ -58,7 +58,7 @@ func getInterfaceList() ([]syscall.InterfaceInfo, os.Error) { // If the ifindex is zero, interfaceTable returns mappings of all // network interfaces. Otheriwse it returns a mapping of a specific // interface. -func interfaceTable(ifindex int) ([]Interface, os.Error) { +func interfaceTable(ifindex int) ([]Interface, error) { ai, e := getAdapterList() if e != nil { return nil, e @@ -129,7 +129,7 @@ func interfaceTable(ifindex int) ([]Interface, os.Error) { // If the ifindex is zero, interfaceAddrTable returns addresses // for all network interfaces. Otherwise it returns addresses // for a specific interface. -func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceAddrTable(ifindex int) ([]Addr, error) { ai, e := getAdapterList() if e != nil { return nil, e @@ -153,6 +153,6 @@ func interfaceAddrTable(ifindex int) ([]Addr, os.Error) { // If the ifindex is zero, interfaceMulticastAddrTable returns // addresses for all network interfaces. Otherwise it returns // addresses for a specific interface. -func interfaceMulticastAddrTable(ifindex int) ([]Addr, os.Error) { +func interfaceMulticastAddrTable(ifindex int) ([]Addr, error) { return nil, nil } diff --git a/src/pkg/net/ip.go b/src/pkg/net/ip.go index 61dc3be909..4a38882787 100644 --- a/src/pkg/net/ip.go +++ b/src/pkg/net/ip.go @@ -12,8 +12,6 @@ package net -import "os" - // IP address lengths (bytes). const ( IPv4len = 4 @@ -594,7 +592,7 @@ type ParseError struct { Text string } -func (e *ParseError) String() string { +func (e *ParseError) Error() string { return "invalid " + e.Type + ": " + e.Text } @@ -627,7 +625,7 @@ func ParseIP(s string) IP { // It returns the IP address and the network implied by the IP // and mask. For example, ParseCIDR("192.168.100.1/16") returns // the IP address 192.168.100.1 and the network 192.168.0.0/16. -func ParseCIDR(s string) (IP, *IPNet, os.Error) { +func ParseCIDR(s string) (IP, *IPNet, error) { i := byteIndex(s, '/') if i < 0 { return nil, nil, &ParseError{"CIDR address", s} diff --git a/src/pkg/net/ip_test.go b/src/pkg/net/ip_test.go index 07e627aef4..0ca315e7c0 100644 --- a/src/pkg/net/ip_test.go +++ b/src/pkg/net/ip_test.go @@ -8,7 +8,6 @@ import ( "bytes" "reflect" "testing" - "os" "runtime" ) @@ -113,7 +112,7 @@ var parsecidrtests = []struct { in string ip IP net *IPNet - err os.Error + err error }{ {"135.104.0.0/32", IPv4(135, 104, 0, 0), &IPNet{IPv4(135, 104, 0, 0), IPv4Mask(255, 255, 255, 255)}, nil}, {"0.0.0.0/24", IPv4(0, 0, 0, 0), &IPNet{IPv4(0, 0, 0, 0), IPv4Mask(255, 255, 255, 0)}, nil}, diff --git a/src/pkg/net/ipraw_test.go b/src/pkg/net/ipraw_test.go index 6894ce656d..60c405ab4a 100644 --- a/src/pkg/net/ipraw_test.go +++ b/src/pkg/net/ipraw_test.go @@ -71,7 +71,7 @@ func TestICMP(t *testing.T) { var ( laddr *IPAddr - err os.Error + err error ) if *srchost != "" { laddr, err = ResolveIPAddr("ip4", *srchost) diff --git a/src/pkg/net/iprawsock.go b/src/pkg/net/iprawsock.go index 662b9f57bd..b23213ee19 100644 --- a/src/pkg/net/iprawsock.go +++ b/src/pkg/net/iprawsock.go @@ -6,10 +6,6 @@ package net -import ( - "os" -) - // IPAddr represents the address of a IP end point. type IPAddr struct { IP IP @@ -29,7 +25,7 @@ func (a *IPAddr) String() string { // names to numeric addresses on the network net, which must be // "ip", "ip4" or "ip6". A literal IPv6 host address must be // enclosed in square brackets, as in "[::]". -func ResolveIPAddr(net, addr string) (*IPAddr, os.Error) { +func ResolveIPAddr(net, addr string) (*IPAddr, error) { ip, err := hostToIP(net, addr) if err != nil { return nil, err @@ -38,7 +34,7 @@ func ResolveIPAddr(net, addr string) (*IPAddr, os.Error) { } // Convert "host" into IP address. -func hostToIP(net, host string) (ip IP, err os.Error) { +func hostToIP(net, host string) (ip IP, err error) { var addr IP // Try as an IP address. addr = ParseIP(host) diff --git a/src/pkg/net/iprawsock_plan9.go b/src/pkg/net/iprawsock_plan9.go index 808e17974f..7e4bc56fac 100644 --- a/src/pkg/net/iprawsock_plan9.go +++ b/src/pkg/net/iprawsock_plan9.go @@ -17,17 +17,17 @@ type IPConn bool // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *IPConn) Read(b []byte) (n int, err os.Error) { +func (c *IPConn) Read(b []byte) (n int, err error) { return 0, os.EPLAN9 } // Write implements the net.Conn Write method. -func (c *IPConn) Write(b []byte) (n int, err os.Error) { +func (c *IPConn) Write(b []byte) (n int, err error) { return 0, os.EPLAN9 } // Close closes the IP connection. -func (c *IPConn) Close() os.Error { +func (c *IPConn) Close() error { return os.EPLAN9 } @@ -42,24 +42,24 @@ func (c *IPConn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *IPConn) SetTimeout(nsec int64) os.Error { +func (c *IPConn) SetTimeout(nsec int64) error { return os.EPLAN9 } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *IPConn) SetReadTimeout(nsec int64) os.Error { +func (c *IPConn) SetReadTimeout(nsec int64) error { return os.EPLAN9 } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *IPConn) SetWriteTimeout(nsec int64) os.Error { +func (c *IPConn) SetWriteTimeout(nsec int64) error { return os.EPLAN9 } // IP-specific methods. // ReadFrom implements the net.PacketConn ReadFrom method. -func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { +func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err error) { err = os.EPLAN9 return } @@ -70,23 +70,23 @@ func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. -func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err os.Error) { +func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err error) { return 0, os.EPLAN9 } // WriteTo implements the net.PacketConn WriteTo method. -func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { +func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err error) { return 0, os.EPLAN9 } -func splitNetProto(netProto string) (net string, proto int, err os.Error) { +func splitNetProto(netProto string) (net string, proto int, err error) { err = os.EPLAN9 return } // DialIP connects to the remote address raddr on the network net, // which must be "ip", "ip4", or "ip6". -func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) { +func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err error) { return nil, os.EPLAN9 } @@ -94,6 +94,6 @@ func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) { // local address laddr. The returned connection c's ReadFrom // and WriteTo methods can be used to receive and send IP // packets with per-packet addressing. -func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) { +func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err error) { return nil, os.EPLAN9 } diff --git a/src/pkg/net/iprawsock_posix.go b/src/pkg/net/iprawsock_posix.go index dafbdab780..3bb99f9a57 100644 --- a/src/pkg/net/iprawsock_posix.go +++ b/src/pkg/net/iprawsock_posix.go @@ -9,6 +9,7 @@ package net import ( + "errors" "os" "syscall" ) @@ -33,7 +34,7 @@ func (a *IPAddr) family() int { return syscall.AF_INET6 } -func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { +func (a *IPAddr) sockaddr(family int) (syscall.Sockaddr, error) { return ipToSockaddr(family, a.IP, 0) } @@ -57,13 +58,13 @@ func (c *IPConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *IPConn) Read(b []byte) (n int, err os.Error) { +func (c *IPConn) Read(b []byte) (n int, err error) { n, _, err = c.ReadFrom(b) return } // Write implements the net.Conn Write method. -func (c *IPConn) Write(b []byte) (n int, err os.Error) { +func (c *IPConn) Write(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -71,7 +72,7 @@ func (c *IPConn) Write(b []byte) (n int, err os.Error) { } // Close closes the IP connection. -func (c *IPConn) Close() os.Error { +func (c *IPConn) Close() error { if !c.ok() { return os.EINVAL } @@ -97,7 +98,7 @@ func (c *IPConn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *IPConn) SetTimeout(nsec int64) os.Error { +func (c *IPConn) SetTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -105,7 +106,7 @@ func (c *IPConn) SetTimeout(nsec int64) os.Error { } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *IPConn) SetReadTimeout(nsec int64) os.Error { +func (c *IPConn) SetReadTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -113,7 +114,7 @@ func (c *IPConn) SetReadTimeout(nsec int64) os.Error { } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *IPConn) SetWriteTimeout(nsec int64) os.Error { +func (c *IPConn) SetWriteTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -122,7 +123,7 @@ func (c *IPConn) SetWriteTimeout(nsec int64) os.Error { // SetReadBuffer sets the size of the operating system's // receive buffer associated with the connection. -func (c *IPConn) SetReadBuffer(bytes int) os.Error { +func (c *IPConn) SetReadBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -131,7 +132,7 @@ func (c *IPConn) SetReadBuffer(bytes int) os.Error { // SetWriteBuffer sets the size of the operating system's // transmit buffer associated with the connection. -func (c *IPConn) SetWriteBuffer(bytes int) os.Error { +func (c *IPConn) SetWriteBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -147,7 +148,7 @@ func (c *IPConn) SetWriteBuffer(bytes int) os.Error { // ReadFromIP can be made to time out and return an error with // Timeout() == true after a fixed time limit; see SetTimeout and // SetReadTimeout. -func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err os.Error) { +func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -169,7 +170,7 @@ func (c *IPConn) ReadFromIP(b []byte) (n int, addr *IPAddr, err os.Error) { } // ReadFrom implements the net.PacketConn ReadFrom method. -func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { +func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -183,19 +184,19 @@ func (c *IPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. -func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err os.Error) { +func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } sa, err1 := addr.sockaddr(c.fd.family) if err1 != nil { - return 0, &OpError{Op: "write", Net: "ip", Addr: addr, Error: err1} + return 0, &OpError{Op: "write", Net: "ip", Addr: addr, Err: err1} } return c.fd.WriteTo(b, sa) } // WriteTo implements the net.PacketConn WriteTo method. -func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { +func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -206,10 +207,10 @@ func (c *IPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { return c.WriteToIP(b, a) } -func splitNetProto(netProto string) (net string, proto int, err os.Error) { +func splitNetProto(netProto string) (net string, proto int, err error) { i := last(netProto, ':') if i < 0 { // no colon - return "", 0, os.NewError("no IP protocol specified") + return "", 0, errors.New("no IP protocol specified") } net = netProto[0:i] protostr := netProto[i+1:] @@ -225,7 +226,7 @@ func splitNetProto(netProto string) (net string, proto int, err os.Error) { // DialIP connects to the remote address raddr on the network net, // which must be "ip", "ip4", or "ip6". -func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) { +func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err error) { net, proto, err := splitNetProto(netProto) if err != nil { return @@ -249,7 +250,7 @@ func DialIP(netProto string, laddr, raddr *IPAddr) (c *IPConn, err os.Error) { // local address laddr. The returned connection c's ReadFrom // and WriteTo methods can be used to receive and send IP // packets with per-packet addressing. -func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) { +func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err error) { net, proto, err := splitNetProto(netProto) if err != nil { return @@ -267,7 +268,7 @@ func ListenIP(netProto string, laddr *IPAddr) (c *IPConn, err os.Error) { } // BindToDevice binds an IPConn to a network interface. -func (c *IPConn) BindToDevice(device string) os.Error { +func (c *IPConn) BindToDevice(device string) error { if !c.ok() { return os.EINVAL } @@ -279,4 +280,4 @@ func (c *IPConn) BindToDevice(device string) os.Error { // File returns a copy of the underlying os.File, set to blocking mode. // It is the caller's responsibility to close f when finished. // Closing c does not affect f, and closing f does not affect c. -func (c *IPConn) File() (f *os.File, err os.Error) { return c.fd.dup() } +func (c *IPConn) File() (f *os.File, err error) { return c.fd.dup() } diff --git a/src/pkg/net/ipsock.go b/src/pkg/net/ipsock.go index 4e2a5622b3..716454d8a9 100644 --- a/src/pkg/net/ipsock.go +++ b/src/pkg/net/ipsock.go @@ -6,10 +6,6 @@ package net -import ( - "os" -) - var supportsIPv6, supportsIPv4map = probeIPv6Stack() func firstFavoriteAddr(filter func(IP) IP, addrs []string) (addr IP) { @@ -61,14 +57,14 @@ func ipv6only(x IP) IP { type InvalidAddrError string -func (e InvalidAddrError) String() string { return string(e) } +func (e InvalidAddrError) Error() string { return string(e) } func (e InvalidAddrError) Timeout() bool { return false } func (e InvalidAddrError) Temporary() bool { return false } // SplitHostPort splits a network address of the form // "host:port" or "[host]:port" into host and port. // The latter form must be used when host contains a colon. -func SplitHostPort(hostport string) (host, port string, err os.Error) { +func SplitHostPort(hostport string) (host, port string, err error) { // The port starts after the last colon. i := last(hostport, ':') if i < 0 { @@ -102,7 +98,7 @@ func JoinHostPort(host, port string) string { } // Convert "host:port" into IP address and port. -func hostPortToIP(net, hostport string) (ip IP, iport int, err os.Error) { +func hostPortToIP(net, hostport string) (ip IP, iport int, err error) { var ( addr IP p, i int diff --git a/src/pkg/net/ipsock_plan9.go b/src/pkg/net/ipsock_plan9.go index 9e5da6d38a..42fb408041 100644 --- a/src/pkg/net/ipsock_plan9.go +++ b/src/pkg/net/ipsock_plan9.go @@ -7,6 +7,8 @@ package net import ( + "errors" + "io" "os" ) @@ -18,7 +20,7 @@ func probeIPv6Stack() (supportsIPv6, supportsIPv4map bool) { } // parsePlan9Addr parses address of the form [ip!]port (e.g. 127.0.0.1!80). -func parsePlan9Addr(s string) (ip IP, iport int, err os.Error) { +func parsePlan9Addr(s string) (ip IP, iport int, err error) { var ( addr IP p, i int @@ -29,13 +31,13 @@ func parsePlan9Addr(s string) (ip IP, iport int, err os.Error) { if i >= 0 { addr = ParseIP(s[:i]) if addr == nil { - err = os.NewError("net: parsing IP failed") + err = errors.New("net: parsing IP failed") goto Error } } p, _, ok = dtoi(s[i+1:], 0) if !ok { - err = os.NewError("net: parsing port failed") + err = errors.New("net: parsing port failed") goto Error } if p < 0 || p > 0xFFFF { @@ -48,7 +50,7 @@ Error: return nil, 0, err } -func readPlan9Addr(proto, filename string) (addr Addr, err os.Error) { +func readPlan9Addr(proto, filename string) (addr Addr, err error) { var buf [128]byte f, err := os.Open(filename) @@ -69,7 +71,7 @@ func readPlan9Addr(proto, filename string) (addr Addr, err os.Error) { case "udp": addr = &UDPAddr{ip, port} default: - return nil, os.NewError("unknown protocol " + proto) + return nil, errors.New("unknown protocol " + proto) } return addr, nil } @@ -89,7 +91,7 @@ func (c *plan9Conn) ok() bool { return c != nil && c.ctl != nil } // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *plan9Conn) Read(b []byte) (n int, err os.Error) { +func (c *plan9Conn) Read(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -100,7 +102,7 @@ func (c *plan9Conn) Read(b []byte) (n int, err os.Error) { } } n, err = c.data.Read(b) - if c.proto == "udp" && err == os.EOF { + if c.proto == "udp" && err == io.EOF { n = 0 err = nil } @@ -108,7 +110,7 @@ func (c *plan9Conn) Read(b []byte) (n int, err os.Error) { } // Write implements the net.Conn Write method. -func (c *plan9Conn) Write(b []byte) (n int, err os.Error) { +func (c *plan9Conn) Write(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -122,7 +124,7 @@ func (c *plan9Conn) Write(b []byte) (n int, err os.Error) { } // Close closes the connection. -func (c *plan9Conn) Close() os.Error { +func (c *plan9Conn) Close() error { if !c.ok() { return os.EINVAL } @@ -155,7 +157,7 @@ func (c *plan9Conn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *plan9Conn) SetTimeout(nsec int64) os.Error { +func (c *plan9Conn) SetTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -163,7 +165,7 @@ func (c *plan9Conn) SetTimeout(nsec int64) os.Error { } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *plan9Conn) SetReadTimeout(nsec int64) os.Error { +func (c *plan9Conn) SetReadTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -171,14 +173,14 @@ func (c *plan9Conn) SetReadTimeout(nsec int64) os.Error { } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *plan9Conn) SetWriteTimeout(nsec int64) os.Error { +func (c *plan9Conn) SetWriteTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } return os.EPLAN9 } -func startPlan9(net string, addr Addr) (ctl *os.File, dest, proto, name string, err os.Error) { +func startPlan9(net string, addr Addr) (ctl *os.File, dest, proto, name string, err error) { var ( ip IP port int @@ -213,7 +215,7 @@ func startPlan9(net string, addr Addr) (ctl *os.File, dest, proto, name string, return f, dest, proto, string(buf[:n]), nil } -func dialPlan9(net string, laddr, raddr Addr) (c *plan9Conn, err os.Error) { +func dialPlan9(net string, laddr, raddr Addr) (c *plan9Conn, err error) { f, dest, proto, name, err := startPlan9(net, raddr) if err != nil { return @@ -239,7 +241,7 @@ type plan9Listener struct { laddr Addr } -func listenPlan9(net string, laddr Addr) (l *plan9Listener, err os.Error) { +func listenPlan9(net string, laddr Addr) (l *plan9Listener, err error) { f, dest, proto, name, err := startPlan9(net, laddr) if err != nil { return @@ -265,7 +267,7 @@ func (l *plan9Listener) plan9Conn() *plan9Conn { return newPlan9Conn(l.proto, l.name, l.ctl, l.laddr, nil) } -func (l *plan9Listener) acceptPlan9() (c *plan9Conn, err os.Error) { +func (l *plan9Listener) acceptPlan9() (c *plan9Conn, err error) { f, err := os.Open(l.dir + "/listen") if err != nil { return @@ -287,7 +289,7 @@ func (l *plan9Listener) acceptPlan9() (c *plan9Conn, err os.Error) { return newPlan9Conn(l.proto, name, f, laddr, raddr), nil } -func (l *plan9Listener) Accept() (c Conn, err os.Error) { +func (l *plan9Listener) Accept() (c Conn, err error) { c1, err := l.acceptPlan9() if err != nil { return @@ -295,7 +297,7 @@ func (l *plan9Listener) Accept() (c Conn, err os.Error) { return c1, nil } -func (l *plan9Listener) Close() os.Error { +func (l *plan9Listener) Close() error { if l == nil || l.ctl == nil { return os.EINVAL } diff --git a/src/pkg/net/ipsock_posix.go b/src/pkg/net/ipsock_posix.go index 049df9ea4c..d5b8f2189c 100644 --- a/src/pkg/net/ipsock_posix.go +++ b/src/pkg/net/ipsock_posix.go @@ -6,10 +6,7 @@ package net -import ( - "os" - "syscall" -) +import "syscall" // Should we try to use the IPv4 socket interface if we're // only dealing with IPv4 sockets? As long as the host system @@ -105,12 +102,12 @@ func listenBacklog() int { return syscall.SOMAXCONN } // be converted into a syscall.Sockaddr. type sockaddr interface { Addr - sockaddr(family int) (syscall.Sockaddr, os.Error) + sockaddr(family int) (syscall.Sockaddr, error) family() int } -func internetSocket(net string, laddr, raddr sockaddr, socktype, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) { - var oserr os.Error +func internetSocket(net string, laddr, raddr sockaddr, socktype, proto int, mode string, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err error) { + var oserr error var la, ra syscall.Sockaddr family := favoriteAddrFamily(net, raddr, laddr, mode) if laddr != nil { @@ -137,7 +134,7 @@ Error: return nil, &OpError{mode, net, addr, oserr} } -func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, os.Error) { +func ipToSockaddr(family int, ip IP, port int) (syscall.Sockaddr, error) { switch family { case syscall.AF_INET: if len(ip) == 0 { diff --git a/src/pkg/net/lookup_plan9.go b/src/pkg/net/lookup_plan9.go index a14c592e8f..027794a5e4 100644 --- a/src/pkg/net/lookup_plan9.go +++ b/src/pkg/net/lookup_plan9.go @@ -5,10 +5,11 @@ package net import ( + "errors" "os" ) -func query(filename, query string, bufSize int) (res []string, err os.Error) { +func query(filename, query string, bufSize int) (res []string, err error) { file, err := os.OpenFile(filename, os.O_RDWR, 0) if err != nil { return @@ -34,7 +35,7 @@ func query(filename, query string, bufSize int) (res []string, err os.Error) { return } -func queryCS(net, host, service string) (res []string, err os.Error) { +func queryCS(net, host, service string) (res []string, err error) { switch net { case "tcp4", "tcp6": net = "tcp" @@ -47,7 +48,7 @@ func queryCS(net, host, service string) (res []string, err os.Error) { return query("/net/cs", net+"!"+host+"!"+service, 128) } -func queryCS1(net string, ip IP, port int) (clone, dest string, err os.Error) { +func queryCS1(net string, ip IP, port int) (clone, dest string, err error) { ips := "*" if len(ip) != 0 && !ip.IsUnspecified() { ips = ip.String() @@ -58,19 +59,19 @@ func queryCS1(net string, ip IP, port int) (clone, dest string, err os.Error) { } f := getFields(lines[0]) if len(f) < 2 { - return "", "", os.NewError("net: bad response from ndb/cs") + return "", "", errors.New("net: bad response from ndb/cs") } clone, dest = f[0], f[1] return } -func queryDNS(addr string, typ string) (res []string, err os.Error) { +func queryDNS(addr string, typ string) (res []string, err error) { return query("/net/dns", addr+" "+typ, 1024) } // LookupHost looks up the given host using the local resolver. // It returns an array of that host's addresses. -func LookupHost(host string) (addrs []string, err os.Error) { +func LookupHost(host string) (addrs []string, err error) { // Use /net/cs insead of /net/dns because cs knows about // host names in local network (e.g. from /lib/ndb/local) lines, err := queryCS("tcp", host, "1") @@ -96,7 +97,7 @@ func LookupHost(host string) (addrs []string, err os.Error) { // LookupIP looks up host using the local resolver. // It returns an array of that host's IPv4 and IPv6 addresses. -func LookupIP(host string) (ips []IP, err os.Error) { +func LookupIP(host string) (ips []IP, err error) { addrs, err := LookupHost(host) if err != nil { return @@ -110,7 +111,7 @@ func LookupIP(host string) (ips []IP, err os.Error) { } // LookupPort looks up the port for the given network and service. -func LookupPort(network, service string) (port int, err os.Error) { +func LookupPort(network, service string) (port int, err error) { switch network { case "tcp4", "tcp6": network = "tcp" @@ -143,7 +144,7 @@ func LookupPort(network, service string) (port int, err os.Error) { // Callers that do not care about the canonical name can call // LookupHost or LookupIP directly; both take care of resolving // the canonical name as part of the lookup. -func LookupCNAME(name string) (cname string, err os.Error) { +func LookupCNAME(name string) (cname string, err error) { lines, err := queryDNS(name, "cname") if err != nil { return @@ -153,7 +154,7 @@ func LookupCNAME(name string) (cname string, err os.Error) { return f[2] + ".", nil } } - return "", os.NewError("net: bad response from ndb/dns") + return "", errors.New("net: bad response from ndb/dns") } // LookupSRV tries to resolve an SRV query of the given service, @@ -165,7 +166,7 @@ func LookupCNAME(name string) (cname string, err os.Error) { // That is, it looks up _service._proto.name. To accommodate services // publishing SRV records under non-standard names, if both service // and proto are empty strings, LookupSRV looks up name directly. -func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) { +func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) { var target string if service == "" && proto == "" { target = name @@ -195,7 +196,7 @@ func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os. } // LookupMX returns the DNS MX records for the given domain name sorted by preference. -func LookupMX(name string) (mx []*MX, err os.Error) { +func LookupMX(name string) (mx []*MX, err error) { lines, err := queryDNS(name, "mx") if err != nil { return @@ -214,7 +215,7 @@ func LookupMX(name string) (mx []*MX, err os.Error) { } // LookupTXT returns the DNS TXT records for the given domain name. -func LookupTXT(name string) (txt []string, err os.Error) { +func LookupTXT(name string) (txt []string, err error) { lines, err := queryDNS(name, "txt") if err != nil { return @@ -229,7 +230,7 @@ func LookupTXT(name string) (txt []string, err os.Error) { // LookupAddr performs a reverse lookup for the given address, returning a list // of names mapping to that address. -func LookupAddr(addr string) (name []string, err os.Error) { +func LookupAddr(addr string) (name []string, err error) { arpa, err := reverseaddr(addr) if err != nil { return diff --git a/src/pkg/net/lookup_unix.go b/src/pkg/net/lookup_unix.go index 6e79295a94..aae6d6ceb9 100644 --- a/src/pkg/net/lookup_unix.go +++ b/src/pkg/net/lookup_unix.go @@ -7,7 +7,7 @@ package net import ( - "os" + "errors" "sync" ) @@ -43,18 +43,18 @@ func readProtocols() { // lookupProtocol looks up IP protocol name in /etc/protocols and // returns correspondent protocol number. -func lookupProtocol(name string) (proto int, err os.Error) { +func lookupProtocol(name string) (proto int, err error) { onceReadProtocols.Do(readProtocols) proto, found := protocols[name] if !found { - return 0, os.NewError("unknown IP protocol specified: " + name) + return 0, errors.New("unknown IP protocol specified: " + name) } return } // LookupHost looks up the given host using the local resolver. // It returns an array of that host's addresses. -func LookupHost(host string) (addrs []string, err os.Error) { +func LookupHost(host string) (addrs []string, err error) { addrs, err, ok := cgoLookupHost(host) if !ok { addrs, err = goLookupHost(host) @@ -64,7 +64,7 @@ func LookupHost(host string) (addrs []string, err os.Error) { // LookupIP looks up host using the local resolver. // It returns an array of that host's IPv4 and IPv6 addresses. -func LookupIP(host string) (addrs []IP, err os.Error) { +func LookupIP(host string) (addrs []IP, err error) { addrs, err, ok := cgoLookupIP(host) if !ok { addrs, err = goLookupIP(host) @@ -73,7 +73,7 @@ func LookupIP(host string) (addrs []IP, err os.Error) { } // LookupPort looks up the port for the given network and service. -func LookupPort(network, service string) (port int, err os.Error) { +func LookupPort(network, service string) (port int, err error) { port, err, ok := cgoLookupPort(network, service) if !ok { port, err = goLookupPort(network, service) @@ -85,7 +85,7 @@ func LookupPort(network, service string) (port int, err os.Error) { // Callers that do not care about the canonical name can call // LookupHost or LookupIP directly; both take care of resolving // the canonical name as part of the lookup. -func LookupCNAME(name string) (cname string, err os.Error) { +func LookupCNAME(name string) (cname string, err error) { cname, err, ok := cgoLookupCNAME(name) if !ok { cname, err = goLookupCNAME(name) @@ -102,7 +102,7 @@ func LookupCNAME(name string) (cname string, err os.Error) { // That is, it looks up _service._proto.name. To accommodate services // publishing SRV records under non-standard names, if both service // and proto are empty strings, LookupSRV looks up name directly. -func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) { +func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) { var target string if service == "" && proto == "" { target = name @@ -124,7 +124,7 @@ func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os. } // LookupMX returns the DNS MX records for the given domain name sorted by preference. -func LookupMX(name string) (mx []*MX, err os.Error) { +func LookupMX(name string) (mx []*MX, err error) { _, records, err := lookup(name, dnsTypeMX) if err != nil { return @@ -139,7 +139,7 @@ func LookupMX(name string) (mx []*MX, err os.Error) { } // LookupTXT returns the DNS TXT records for the given domain name. -func LookupTXT(name string) (txt []string, err os.Error) { +func LookupTXT(name string) (txt []string, err error) { _, records, err := lookup(name, dnsTypeTXT) if err != nil { return @@ -153,7 +153,7 @@ func LookupTXT(name string) (txt []string, err os.Error) { // LookupAddr performs a reverse lookup for the given address, returning a list // of names mapping to that address. -func LookupAddr(addr string) (name []string, err os.Error) { +func LookupAddr(addr string) (name []string, err error) { name = lookupStaticAddr(addr) if len(name) > 0 { return diff --git a/src/pkg/net/lookup_windows.go b/src/pkg/net/lookup_windows.go index ea939f8598..53cb8f468a 100644 --- a/src/pkg/net/lookup_windows.go +++ b/src/pkg/net/lookup_windows.go @@ -5,6 +5,7 @@ package net import ( + "errors" "syscall" "unsafe" "os" @@ -18,7 +19,7 @@ var ( ) // lookupProtocol looks up IP protocol name and returns correspondent protocol number. -func lookupProtocol(name string) (proto int, err os.Error) { +func lookupProtocol(name string) (proto int, err error) { protoentLock.Lock() defer protoentLock.Unlock() p, e := syscall.GetProtoByName(name) @@ -28,7 +29,7 @@ func lookupProtocol(name string) (proto int, err os.Error) { return int(p.Proto), nil } -func LookupHost(name string) (addrs []string, err os.Error) { +func LookupHost(name string) (addrs []string, err error) { ips, err := LookupIP(name) if err != nil { return @@ -40,7 +41,7 @@ func LookupHost(name string) (addrs []string, err os.Error) { return } -func LookupIP(name string) (addrs []IP, err os.Error) { +func LookupIP(name string) (addrs []IP, err error) { hostentLock.Lock() defer hostentLock.Unlock() h, e := syscall.GetHostByName(name) @@ -61,7 +62,7 @@ func LookupIP(name string) (addrs []IP, err os.Error) { return addrs, nil } -func LookupPort(network, service string) (port int, err os.Error) { +func LookupPort(network, service string) (port int, err error) { switch network { case "tcp4", "tcp6": network = "tcp" @@ -77,7 +78,7 @@ func LookupPort(network, service string) (port int, err os.Error) { return int(syscall.Ntohs(s.Port)), nil } -func LookupCNAME(name string) (cname string, err os.Error) { +func LookupCNAME(name string) (cname string, err error) { var r *syscall.DNSRecord e := syscall.DnsQuery(name, syscall.DNS_TYPE_CNAME, 0, nil, &r, nil) if int(e) != 0 { @@ -100,7 +101,7 @@ func LookupCNAME(name string) (cname string, err os.Error) { // That is, it looks up _service._proto.name. To accommodate services // publishing SRV records under non-standard names, if both service // and proto are empty strings, LookupSRV looks up name directly. -func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os.Error) { +func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) { var target string if service == "" && proto == "" { target = name @@ -122,7 +123,7 @@ func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err os. return name, addrs, nil } -func LookupMX(name string) (mx []*MX, err os.Error) { +func LookupMX(name string) (mx []*MX, err error) { var r *syscall.DNSRecord e := syscall.DnsQuery(name, syscall.DNS_TYPE_MX, 0, nil, &r, nil) if int(e) != 0 { @@ -138,11 +139,11 @@ func LookupMX(name string) (mx []*MX, err os.Error) { return mx, nil } -func LookupTXT(name string) (txt []string, err os.Error) { - return nil, os.NewError("net.LookupTXT is not implemented on Windows") +func LookupTXT(name string) (txt []string, err error) { + return nil, errors.New("net.LookupTXT is not implemented on Windows") } -func LookupAddr(addr string) (name []string, err os.Error) { +func LookupAddr(addr string) (name []string, err error) { arpa, err := reverseaddr(addr) if err != nil { return nil, err diff --git a/src/pkg/net/net.go b/src/pkg/net/net.go index 5c84d34348..48f0ae791c 100644 --- a/src/pkg/net/net.go +++ b/src/pkg/net/net.go @@ -9,7 +9,7 @@ package net // TODO(rsc): // support for raw ethernet sockets -import "os" +import "errors" // Addr represents a network end point address. type Addr interface { @@ -22,15 +22,15 @@ type Conn interface { // Read reads data from the connection. // Read can be made to time out and return a net.Error with Timeout() == true // after a fixed time limit; see SetTimeout and SetReadTimeout. - Read(b []byte) (n int, err os.Error) + Read(b []byte) (n int, err error) // Write writes data to the connection. // Write can be made to time out and return a net.Error with Timeout() == true // after a fixed time limit; see SetTimeout and SetWriteTimeout. - Write(b []byte) (n int, err os.Error) + Write(b []byte) (n int, err error) // Close closes the connection. - Close() os.Error + Close() error // LocalAddr returns the local network address. LocalAddr() Addr @@ -40,24 +40,24 @@ type Conn interface { // SetTimeout sets the read and write deadlines associated // with the connection. - SetTimeout(nsec int64) os.Error + SetTimeout(nsec int64) error // SetReadTimeout sets the time (in nanoseconds) that // Read will wait for data before returning an error with Timeout() == true. // Setting nsec == 0 (the default) disables the deadline. - SetReadTimeout(nsec int64) os.Error + SetReadTimeout(nsec int64) error // SetWriteTimeout sets the time (in nanoseconds) that // Write will wait to send its data before returning an error with Timeout() == true. // Setting nsec == 0 (the default) disables the deadline. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. - SetWriteTimeout(nsec int64) os.Error + SetWriteTimeout(nsec int64) error } // An Error represents a network error. type Error interface { - os.Error + error Timeout() bool // Is the error a timeout? Temporary() bool // Is the error temporary? } @@ -71,60 +71,60 @@ type PacketConn interface { // ReadFrom can be made to time out and return // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetReadTimeout. - ReadFrom(b []byte) (n int, addr Addr, err os.Error) + ReadFrom(b []byte) (n int, addr Addr, err error) // WriteTo writes a packet with payload b to addr. // WriteTo can be made to time out and return // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. - WriteTo(b []byte, addr Addr) (n int, err os.Error) + WriteTo(b []byte, addr Addr) (n int, err error) // Close closes the connection. - Close() os.Error + Close() error // LocalAddr returns the local network address. LocalAddr() Addr // SetTimeout sets the read and write deadlines associated // with the connection. - SetTimeout(nsec int64) os.Error + SetTimeout(nsec int64) error // SetReadTimeout sets the time (in nanoseconds) that // Read will wait for data before returning an error with Timeout() == true. // Setting nsec == 0 (the default) disables the deadline. - SetReadTimeout(nsec int64) os.Error + SetReadTimeout(nsec int64) error // SetWriteTimeout sets the time (in nanoseconds) that // Write will wait to send its data before returning an error with Timeout() == true. // Setting nsec == 0 (the default) disables the deadline. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. - SetWriteTimeout(nsec int64) os.Error + SetWriteTimeout(nsec int64) error } // A Listener is a generic network listener for stream-oriented protocols. type Listener interface { // Accept waits for and returns the next connection to the listener. - Accept() (c Conn, err os.Error) + Accept() (c Conn, err error) // Close closes the listener. - Close() os.Error + Close() error // Addr returns the listener's network address. Addr() Addr } -var errMissingAddress = os.NewError("missing address") +var errMissingAddress = errors.New("missing address") type OpError struct { - Op string - Net string - Addr Addr - Error os.Error + Op string + Net string + Addr Addr + Err error } -func (e *OpError) String() string { +func (e *OpError) Error() string { if e == nil { return "" } @@ -135,7 +135,7 @@ func (e *OpError) String() string { if e.Addr != nil { s += " " + e.Addr.String() } - s += ": " + e.Error.String() + s += ": " + e.Err.Error() return s } @@ -144,7 +144,7 @@ type temporary interface { } func (e *OpError) Temporary() bool { - t, ok := e.Error.(temporary) + t, ok := e.Err.(temporary) return ok && t.Temporary() } @@ -153,20 +153,20 @@ type timeout interface { } func (e *OpError) Timeout() bool { - t, ok := e.Error.(timeout) + t, ok := e.Err.(timeout) return ok && t.Timeout() } type AddrError struct { - Error string - Addr string + Err string + Addr string } -func (e *AddrError) String() string { +func (e *AddrError) Error() string { if e == nil { return "" } - s := e.Error + s := e.Err if e.Addr != "" { s += " " + e.Addr } @@ -183,6 +183,6 @@ func (e *AddrError) Timeout() bool { type UnknownNetworkError string -func (e UnknownNetworkError) String() string { return "unknown network " + string(e) } +func (e UnknownNetworkError) Error() string { return "unknown network " + string(e) } func (e UnknownNetworkError) Temporary() bool { return false } func (e UnknownNetworkError) Timeout() bool { return false } diff --git a/src/pkg/net/net_test.go b/src/pkg/net/net_test.go index 94d620e47e..d2839d719f 100644 --- a/src/pkg/net/net_test.go +++ b/src/pkg/net/net_test.go @@ -6,7 +6,7 @@ package net import ( "flag" - "os" + "io" "regexp" "runtime" "testing" @@ -79,7 +79,7 @@ func TestDialError(t *testing.T) { t.Errorf("#%d: nil error, want match for %#q", i, tt.Pattern) continue } - s := e.String() + s := e.Error() match, _ := regexp.MatchString(tt.Pattern, s) if !match { t.Errorf("#%d: %q, want match for %#q", i, s, tt.Pattern) @@ -119,8 +119,8 @@ func TestReverseAddress(t *testing.T) { if len(tt.ErrPrefix) == 0 && e != nil { t.Errorf("#%d: expected , got %q (error)", i, e) } - if e != nil && e.(*DNSError).Error != tt.ErrPrefix { - t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, e.(*DNSError).Error) + if e != nil && e.(*DNSError).Err != tt.ErrPrefix { + t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, e.(*DNSError).Err) } if a != tt.Reverse { t.Errorf("#%d: expected %q, got %q (reverse address)", i, tt.Reverse, a) @@ -146,7 +146,7 @@ func TestShutdown(t *testing.T) { } var buf [10]byte n, err := c.Read(buf[:]) - if n != 0 || err != os.EOF { + if n != 0 || err != io.EOF { t.Fatalf("server Read = %d, %v; want 0, os.EOF", n, err) } c.Write([]byte("response")) diff --git a/src/pkg/net/newpollserver.go b/src/pkg/net/newpollserver.go index 3c9a6da537..9ad6f7ba27 100644 --- a/src/pkg/net/newpollserver.go +++ b/src/pkg/net/newpollserver.go @@ -11,7 +11,7 @@ import ( "syscall" ) -func newPollServer() (s *pollServer, err os.Error) { +func newPollServer() (s *pollServer, err error) { s = new(pollServer) s.cr = make(chan *netFD, 1) s.cw = make(chan *netFD, 1) diff --git a/src/pkg/net/parse.go b/src/pkg/net/parse.go index 0d30a7ac60..4c4200a49b 100644 --- a/src/pkg/net/parse.go +++ b/src/pkg/net/parse.go @@ -54,7 +54,7 @@ func (f *file) readLine() (s string, ok bool) { if n >= 0 { f.data = f.data[0 : ln+n] } - if err == os.EOF { + if err == io.EOF { f.atEOF = true } } @@ -62,7 +62,7 @@ func (f *file) readLine() (s string, ok bool) { return } -func open(name string) (*file, os.Error) { +func open(name string) (*file, error) { fd, err := os.Open(name) if err != nil { return nil, err diff --git a/src/pkg/net/pipe.go b/src/pkg/net/pipe.go index c0bbd356b3..b99e6e658d 100644 --- a/src/pkg/net/pipe.go +++ b/src/pkg/net/pipe.go @@ -1,8 +1,8 @@ package net import ( + "errors" "io" - "os" ) // Pipe creates a synchronous, in-memory, full duplex @@ -32,7 +32,7 @@ func (pipeAddr) String() string { return "pipe" } -func (p *pipe) Close() os.Error { +func (p *pipe) Close() error { err := p.PipeReader.Close() err1 := p.PipeWriter.Close() if err == nil { @@ -49,14 +49,14 @@ func (p *pipe) RemoteAddr() Addr { return pipeAddr(0) } -func (p *pipe) SetTimeout(nsec int64) os.Error { - return os.NewError("net.Pipe does not support timeouts") +func (p *pipe) SetTimeout(nsec int64) error { + return errors.New("net.Pipe does not support timeouts") } -func (p *pipe) SetReadTimeout(nsec int64) os.Error { - return os.NewError("net.Pipe does not support timeouts") +func (p *pipe) SetReadTimeout(nsec int64) error { + return errors.New("net.Pipe does not support timeouts") } -func (p *pipe) SetWriteTimeout(nsec int64) os.Error { - return os.NewError("net.Pipe does not support timeouts") +func (p *pipe) SetWriteTimeout(nsec int64) error { + return errors.New("net.Pipe does not support timeouts") } diff --git a/src/pkg/net/pipe_test.go b/src/pkg/net/pipe_test.go index 7e4c6db443..afe4f2408f 100644 --- a/src/pkg/net/pipe_test.go +++ b/src/pkg/net/pipe_test.go @@ -7,7 +7,6 @@ package net import ( "bytes" "io" - "os" "testing" ) @@ -22,7 +21,7 @@ func checkWrite(t *testing.T, w io.Writer, data []byte, c chan int) { c <- 0 } -func checkRead(t *testing.T, r io.Reader, data []byte, wantErr os.Error) { +func checkRead(t *testing.T, r io.Reader, data []byte, wantErr error) { buf := make([]byte, len(data)+10) n, err := r.Read(buf) if err != wantErr { @@ -52,6 +51,6 @@ func TestPipe(t *testing.T) { checkRead(t, srv, []byte("a third line"), nil) <-c go srv.Close() - checkRead(t, cli, nil, os.EOF) + checkRead(t, cli, nil, io.EOF) cli.Close() } diff --git a/src/pkg/net/port.go b/src/pkg/net/port.go index a8ca60c60a..80597f7555 100644 --- a/src/pkg/net/port.go +++ b/src/pkg/net/port.go @@ -8,13 +8,10 @@ package net -import ( - "os" - "sync" -) +import "sync" var services map[string]map[string]int -var servicesError os.Error +var servicesError error var onceReadServices sync.Once func readServices() { @@ -53,7 +50,7 @@ func readServices() { } // goLookupPort is the native Go implementation of LookupPort. -func goLookupPort(network, service string) (port int, err os.Error) { +func goLookupPort(network, service string) (port int, err error) { onceReadServices.Do(readServices) switch network { diff --git a/src/pkg/net/sendfile_linux.go b/src/pkg/net/sendfile_linux.go index 6a5a06c8c5..36c7578578 100644 --- a/src/pkg/net/sendfile_linux.go +++ b/src/pkg/net/sendfile_linux.go @@ -21,7 +21,7 @@ const maxSendfileSize int = 4 << 20 // non-EOF error. // // if handled == false, sendFile performed no work. -func sendFile(c *netFD, r io.Reader) (written int64, err os.Error, handled bool) { +func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool) { var remain int64 = 1 << 62 // by default, copy until EOF lr, ok := r.(*io.LimitedReader) diff --git a/src/pkg/net/sendfile_stub.go b/src/pkg/net/sendfile_stub.go index c55be6c080..b0adea4787 100644 --- a/src/pkg/net/sendfile_stub.go +++ b/src/pkg/net/sendfile_stub.go @@ -6,11 +6,8 @@ package net -import ( - "io" - "os" -) +import "io" -func sendFile(c *netFD, r io.Reader) (n int64, err os.Error, handled bool) { +func sendFile(c *netFD, r io.Reader) (n int64, err error, handled bool) { return 0, nil, false } diff --git a/src/pkg/net/sendfile_windows.go b/src/pkg/net/sendfile_windows.go index d9c2f537a3..0b31572771 100644 --- a/src/pkg/net/sendfile_windows.go +++ b/src/pkg/net/sendfile_windows.go @@ -33,7 +33,7 @@ func (o *sendfileOp) Name() string { // if handled == false, sendFile performed no work. // // Note that sendfile for windows does not suppport >2GB file. -func sendFile(c *netFD, r io.Reader) (written int64, err os.Error, handled bool) { +func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool) { var n int64 = 0 // by default, copy until EOF lr, ok := r.(*io.LimitedReader) diff --git a/src/pkg/net/server_test.go b/src/pkg/net/server_test.go index a2ff218e70..9e5444980f 100644 --- a/src/pkg/net/server_test.go +++ b/src/pkg/net/server_test.go @@ -55,7 +55,7 @@ func runServe(t *testing.T, network, addr string, listening chan<- string, done func connect(t *testing.T, network, addr string, isEmpty bool) { var fd Conn - var err os.Error + var err error if network == "unixgram" { fd, err = DialUnix(network, &UnixAddr{addr + ".local", network}, &UnixAddr{addr, network}) } else { diff --git a/src/pkg/net/sock.go b/src/pkg/net/sock.go index 2359014ad6..d9df02cd63 100644 --- a/src/pkg/net/sock.go +++ b/src/pkg/net/sock.go @@ -24,7 +24,7 @@ func boolint(b bool) int { } // Generic socket creation. -func socket(net string, f, p, t int, la, ra syscall.Sockaddr, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err os.Error) { +func socket(net string, f, p, t int, la, ra syscall.Sockaddr, toAddr func(syscall.Sockaddr) Addr) (fd *netFD, err error) { // See ../syscall/exec.go for description of ForkLock. syscall.ForkLock.RLock() s, e := syscall.Socket(f, p, t) @@ -67,74 +67,74 @@ func socket(net string, f, p, t int, la, ra syscall.Sockaddr, toAddr func(syscal return fd, nil } -func setsockoptInt(fd *netFD, level, opt int, value int) os.Error { +func setsockoptInt(fd *netFD, level, opt int, value int) error { return os.NewSyscallError("setsockopt", syscall.SetsockoptInt(fd.sysfd, level, opt, value)) } -func setsockoptNsec(fd *netFD, level, opt int, nsec int64) os.Error { +func setsockoptNsec(fd *netFD, level, opt int, nsec int64) error { var tv = syscall.NsecToTimeval(nsec) return os.NewSyscallError("setsockopt", syscall.SetsockoptTimeval(fd.sysfd, level, opt, &tv)) } -func setReadBuffer(fd *netFD, bytes int) os.Error { +func setReadBuffer(fd *netFD, bytes int) error { fd.incref() defer fd.decref() return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bytes) } -func setWriteBuffer(fd *netFD, bytes int) os.Error { +func setWriteBuffer(fd *netFD, bytes int) error { fd.incref() defer fd.decref() return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bytes) } -func setReadTimeout(fd *netFD, nsec int64) os.Error { +func setReadTimeout(fd *netFD, nsec int64) error { fd.rdeadline_delta = nsec return nil } -func setWriteTimeout(fd *netFD, nsec int64) os.Error { +func setWriteTimeout(fd *netFD, nsec int64) error { fd.wdeadline_delta = nsec return nil } -func setTimeout(fd *netFD, nsec int64) os.Error { +func setTimeout(fd *netFD, nsec int64) error { if e := setReadTimeout(fd, nsec); e != nil { return e } return setWriteTimeout(fd, nsec) } -func setReuseAddr(fd *netFD, reuse bool) os.Error { +func setReuseAddr(fd *netFD, reuse bool) error { fd.incref() defer fd.decref() return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, boolint(reuse)) } -func bindToDevice(fd *netFD, dev string) os.Error { +func bindToDevice(fd *netFD, dev string) error { // TODO(rsc): call setsockopt with null-terminated string pointer return os.EINVAL } -func setDontRoute(fd *netFD, dontroute bool) os.Error { +func setDontRoute(fd *netFD, dontroute bool) error { fd.incref() defer fd.decref() return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_DONTROUTE, boolint(dontroute)) } -func setKeepAlive(fd *netFD, keepalive bool) os.Error { +func setKeepAlive(fd *netFD, keepalive bool) error { fd.incref() defer fd.decref() return setsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, boolint(keepalive)) } -func setNoDelay(fd *netFD, noDelay bool) os.Error { +func setNoDelay(fd *netFD, noDelay bool) error { fd.incref() defer fd.decref() return setsockoptInt(fd, syscall.IPPROTO_TCP, syscall.TCP_NODELAY, boolint(noDelay)) } -func setLinger(fd *netFD, sec int) os.Error { +func setLinger(fd *netFD, sec int) error { var l syscall.Linger if sec >= 0 { l.Onoff = 1 @@ -153,7 +153,7 @@ type UnknownSocketError struct { sa syscall.Sockaddr } -func (e *UnknownSocketError) String() string { +func (e *UnknownSocketError) Error() string { return "unknown socket address type " + reflect.TypeOf(e.sa).String() } @@ -163,7 +163,7 @@ type writerOnly struct { // Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't // applicable. -func genericReadFrom(w io.Writer, r io.Reader) (n int64, err os.Error) { +func genericReadFrom(w io.Writer, r io.Reader) (n int64, err error) { // Use wrapper to hide existing r.ReadFrom from io.Copy. return io.Copy(writerOnly{w}, r) } diff --git a/src/pkg/net/tcpsock.go b/src/pkg/net/tcpsock.go index f5c0a27810..47fbf29198 100644 --- a/src/pkg/net/tcpsock.go +++ b/src/pkg/net/tcpsock.go @@ -6,10 +6,6 @@ package net -import ( - "os" -) - // TCPAddr represents the address of a TCP end point. type TCPAddr struct { IP IP @@ -31,7 +27,7 @@ func (a *TCPAddr) String() string { // numeric addresses on the network net, which must be "tcp", // "tcp4" or "tcp6". A literal IPv6 host address must be // enclosed in square brackets, as in "[::]:80". -func ResolveTCPAddr(net, addr string) (*TCPAddr, os.Error) { +func ResolveTCPAddr(net, addr string) (*TCPAddr, error) { ip, port, err := hostPortToIP(net, addr) if err != nil { return nil, err diff --git a/src/pkg/net/tcpsock_plan9.go b/src/pkg/net/tcpsock_plan9.go index 3319e57c33..69fae03614 100644 --- a/src/pkg/net/tcpsock_plan9.go +++ b/src/pkg/net/tcpsock_plan9.go @@ -18,7 +18,7 @@ type TCPConn struct { // CloseRead shuts down the reading side of the TCP connection. // Most callers should just use Close. -func (c *TCPConn) CloseRead() os.Error { +func (c *TCPConn) CloseRead() error { if !c.ok() { return os.EINVAL } @@ -27,7 +27,7 @@ func (c *TCPConn) CloseRead() os.Error { // CloseWrite shuts down the writing side of the TCP connection. // Most callers should just use Close. -func (c *TCPConn) CloseWrite() os.Error { +func (c *TCPConn) CloseWrite() error { if !c.ok() { return os.EINVAL } @@ -37,7 +37,7 @@ func (c *TCPConn) CloseWrite() os.Error { // DialTCP connects to the remote address raddr on the network net, // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used // as the local address for the connection. -func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) { +func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err error) { switch net { case "tcp", "tcp4", "tcp6": default: @@ -64,7 +64,7 @@ type TCPListener struct { // Net must be "tcp", "tcp4", or "tcp6". // If laddr has a port of 0, it means to listen on some available port. // The caller can use l.Addr() to retrieve the chosen address. -func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) { +func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err error) { switch net { case "tcp", "tcp4", "tcp6": default: diff --git a/src/pkg/net/tcpsock_posix.go b/src/pkg/net/tcpsock_posix.go index 740a63d303..a726b45c15 100644 --- a/src/pkg/net/tcpsock_posix.go +++ b/src/pkg/net/tcpsock_posix.go @@ -39,7 +39,7 @@ func (a *TCPAddr) family() int { return syscall.AF_INET6 } -func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { +func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) { return ipToSockaddr(family, a.IP, a.Port) } @@ -67,7 +67,7 @@ func (c *TCPConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *TCPConn) Read(b []byte) (n int, err os.Error) { +func (c *TCPConn) Read(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -75,7 +75,7 @@ func (c *TCPConn) Read(b []byte) (n int, err os.Error) { } // ReadFrom implements the io.ReaderFrom ReadFrom method. -func (c *TCPConn) ReadFrom(r io.Reader) (int64, os.Error) { +func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) { if n, err, handled := sendFile(c.fd, r); handled { return n, err } @@ -83,7 +83,7 @@ func (c *TCPConn) ReadFrom(r io.Reader) (int64, os.Error) { } // Write implements the net.Conn Write method. -func (c *TCPConn) Write(b []byte) (n int, err os.Error) { +func (c *TCPConn) Write(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -91,7 +91,7 @@ func (c *TCPConn) Write(b []byte) (n int, err os.Error) { } // Close closes the TCP connection. -func (c *TCPConn) Close() os.Error { +func (c *TCPConn) Close() error { if !c.ok() { return os.EINVAL } @@ -102,7 +102,7 @@ func (c *TCPConn) Close() os.Error { // CloseRead shuts down the reading side of the TCP connection. // Most callers should just use Close. -func (c *TCPConn) CloseRead() os.Error { +func (c *TCPConn) CloseRead() error { if !c.ok() { return os.EINVAL } @@ -111,7 +111,7 @@ func (c *TCPConn) CloseRead() os.Error { // CloseWrite shuts down the writing side of the TCP connection. // Most callers should just use Close. -func (c *TCPConn) CloseWrite() os.Error { +func (c *TCPConn) CloseWrite() error { if !c.ok() { return os.EINVAL } @@ -135,7 +135,7 @@ func (c *TCPConn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *TCPConn) SetTimeout(nsec int64) os.Error { +func (c *TCPConn) SetTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -143,7 +143,7 @@ func (c *TCPConn) SetTimeout(nsec int64) os.Error { } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *TCPConn) SetReadTimeout(nsec int64) os.Error { +func (c *TCPConn) SetReadTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -151,7 +151,7 @@ func (c *TCPConn) SetReadTimeout(nsec int64) os.Error { } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *TCPConn) SetWriteTimeout(nsec int64) os.Error { +func (c *TCPConn) SetWriteTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -160,7 +160,7 @@ func (c *TCPConn) SetWriteTimeout(nsec int64) os.Error { // SetReadBuffer sets the size of the operating system's // receive buffer associated with the connection. -func (c *TCPConn) SetReadBuffer(bytes int) os.Error { +func (c *TCPConn) SetReadBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -169,7 +169,7 @@ func (c *TCPConn) SetReadBuffer(bytes int) os.Error { // SetWriteBuffer sets the size of the operating system's // transmit buffer associated with the connection. -func (c *TCPConn) SetWriteBuffer(bytes int) os.Error { +func (c *TCPConn) SetWriteBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -187,7 +187,7 @@ func (c *TCPConn) SetWriteBuffer(bytes int) os.Error { // // If sec > 0, Close blocks for at most sec seconds waiting for // data to be sent and acknowledged. -func (c *TCPConn) SetLinger(sec int) os.Error { +func (c *TCPConn) SetLinger(sec int) error { if !c.ok() { return os.EINVAL } @@ -196,7 +196,7 @@ func (c *TCPConn) SetLinger(sec int) os.Error { // SetKeepAlive sets whether the operating system should send // keepalive messages on the connection. -func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error { +func (c *TCPConn) SetKeepAlive(keepalive bool) error { if !c.ok() { return os.EINVAL } @@ -207,7 +207,7 @@ func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error { // packet transmission in hopes of sending fewer packets // (Nagle's algorithm). The default is true (no delay), meaning // that data is sent as soon as possible after a Write. -func (c *TCPConn) SetNoDelay(noDelay bool) os.Error { +func (c *TCPConn) SetNoDelay(noDelay bool) error { if !c.ok() { return os.EINVAL } @@ -217,12 +217,12 @@ func (c *TCPConn) SetNoDelay(noDelay bool) os.Error { // File returns a copy of the underlying os.File, set to blocking mode. // It is the caller's responsibility to close f when finished. // Closing c does not affect f, and closing f does not affect c. -func (c *TCPConn) File() (f *os.File, err os.Error) { return c.fd.dup() } +func (c *TCPConn) File() (f *os.File, err error) { return c.fd.dup() } // DialTCP connects to the remote address raddr on the network net, // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used // as the local address for the connection. -func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) { +func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err error) { if raddr == nil { return nil, &OpError{"dial", "tcp", nil, errMissingAddress} } @@ -244,7 +244,7 @@ type TCPListener struct { // Net must be "tcp", "tcp4", or "tcp6". // If laddr has a port of 0, it means to listen on some available port. // The caller can use l.Addr() to retrieve the chosen address. -func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) { +func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err error) { fd, err := internetSocket(net, laddr.toAddr(), nil, syscall.SOCK_STREAM, 0, "listen", sockaddrToTCP) if err != nil { return nil, err @@ -261,7 +261,7 @@ func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error) { // AcceptTCP accepts the next incoming call and returns the new connection // and the remote address. -func (l *TCPListener) AcceptTCP() (c *TCPConn, err os.Error) { +func (l *TCPListener) AcceptTCP() (c *TCPConn, err error) { if l == nil || l.fd == nil || l.fd.sysfd < 0 { return nil, os.EINVAL } @@ -274,7 +274,7 @@ func (l *TCPListener) AcceptTCP() (c *TCPConn, err os.Error) { // Accept implements the Accept method in the Listener interface; // it waits for the next call and returns a generic Conn. -func (l *TCPListener) Accept() (c Conn, err os.Error) { +func (l *TCPListener) Accept() (c Conn, err error) { c1, err := l.AcceptTCP() if err != nil { return nil, err @@ -284,7 +284,7 @@ func (l *TCPListener) Accept() (c Conn, err os.Error) { // Close stops listening on the TCP address. // Already Accepted connections are not closed. -func (l *TCPListener) Close() os.Error { +func (l *TCPListener) Close() error { if l == nil || l.fd == nil { return os.EINVAL } @@ -295,7 +295,7 @@ func (l *TCPListener) Close() os.Error { func (l *TCPListener) Addr() Addr { return l.fd.laddr } // SetTimeout sets the deadline associated with the listener -func (l *TCPListener) SetTimeout(nsec int64) os.Error { +func (l *TCPListener) SetTimeout(nsec int64) error { if l == nil || l.fd == nil { return os.EINVAL } @@ -305,4 +305,4 @@ func (l *TCPListener) SetTimeout(nsec int64) os.Error { // File returns a copy of the underlying os.File, set to blocking mode. // It is the caller's responsibility to close f when finished. // Closing c does not affect f, and closing f does not affect c. -func (l *TCPListener) File() (f *os.File, err os.Error) { return l.fd.dup() } +func (l *TCPListener) File() (f *os.File, err error) { return l.fd.dup() } diff --git a/src/pkg/net/textproto/reader.go b/src/pkg/net/textproto/reader.go index 98b39276b8..658b5c282e 100644 --- a/src/pkg/net/textproto/reader.go +++ b/src/pkg/net/textproto/reader.go @@ -9,7 +9,6 @@ import ( "bytes" "io" "io/ioutil" - "os" "strconv" "strings" ) @@ -32,13 +31,13 @@ func NewReader(r *bufio.Reader) *Reader { // ReadLine reads a single line from r, // eliding the final \n or \r\n from the returned string. -func (r *Reader) ReadLine() (string, os.Error) { +func (r *Reader) ReadLine() (string, error) { line, err := r.readLineSlice() return string(line), err } // ReadLineBytes is like ReadLine but returns a []byte instead of a string. -func (r *Reader) ReadLineBytes() ([]byte, os.Error) { +func (r *Reader) ReadLineBytes() ([]byte, error) { line, err := r.readLineSlice() if line != nil { buf := make([]byte, len(line)) @@ -48,7 +47,7 @@ func (r *Reader) ReadLineBytes() ([]byte, os.Error) { return line, err } -func (r *Reader) readLineSlice() ([]byte, os.Error) { +func (r *Reader) readLineSlice() ([]byte, error) { r.closeDot() var line []byte for { @@ -87,7 +86,7 @@ func (r *Reader) readLineSlice() ([]byte, os.Error) { // // A line consisting of only white space is never continued. // -func (r *Reader) ReadContinuedLine() (string, os.Error) { +func (r *Reader) ReadContinuedLine() (string, error) { line, err := r.readContinuedLineSlice() return string(line), err } @@ -108,7 +107,7 @@ func trim(s []byte) []byte { // ReadContinuedLineBytes is like ReadContinuedLine but // returns a []byte instead of a string. -func (r *Reader) ReadContinuedLineBytes() ([]byte, os.Error) { +func (r *Reader) ReadContinuedLineBytes() ([]byte, error) { line, err := r.readContinuedLineSlice() if line != nil { buf := make([]byte, len(line)) @@ -118,7 +117,7 @@ func (r *Reader) ReadContinuedLineBytes() ([]byte, os.Error) { return line, err } -func (r *Reader) readContinuedLineSlice() ([]byte, os.Error) { +func (r *Reader) readContinuedLineSlice() ([]byte, error) { // Read the first line. line, err := r.readLineSlice() if err != nil { @@ -192,7 +191,7 @@ func (r *Reader) readContinuedLineSlice() ([]byte, os.Error) { return line, err } -func (r *Reader) readCodeLine(expectCode int) (code int, continued bool, message string, err os.Error) { +func (r *Reader) readCodeLine(expectCode int) (code int, continued bool, message string, err error) { line, err := r.ReadLine() if err != nil { return @@ -200,7 +199,7 @@ func (r *Reader) readCodeLine(expectCode int) (code int, continued bool, message return parseCodeLine(line, expectCode) } -func parseCodeLine(line string, expectCode int) (code int, continued bool, message string, err os.Error) { +func parseCodeLine(line string, expectCode int) (code int, continued bool, message string, err error) { if len(line) < 4 || line[3] != ' ' && line[3] != '-' { err = ProtocolError("short response: " + line) return @@ -235,7 +234,7 @@ func parseCodeLine(line string, expectCode int) (code int, continued bool, messa // // An expectCode <= 0 disables the check of the status code. // -func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err os.Error) { +func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error) { code, continued, message, err := r.readCodeLine(expectCode) if err == nil && continued { err = ProtocolError("unexpected multi-line response: " + message) @@ -265,7 +264,7 @@ func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err os. // // An expectCode <= 0 disables the check of the status code. // -func (r *Reader) ReadResponse(expectCode int) (code int, message string, err os.Error) { +func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error) { code, continued, message, err := r.readCodeLine(expectCode) for err == nil && continued { line, err := r.ReadLine() @@ -314,7 +313,7 @@ type dotReader struct { } // Read satisfies reads by decoding dot-encoded data read from d.r. -func (d *dotReader) Read(b []byte) (n int, err os.Error) { +func (d *dotReader) Read(b []byte) (n int, err error) { // Run data through a simple state machine to // elide leading dots, rewrite trailing \r\n into \n, // and detect ending .\r\n line. @@ -331,7 +330,7 @@ func (d *dotReader) Read(b []byte) (n int, err os.Error) { var c byte c, err = br.ReadByte() if err != nil { - if err == os.EOF { + if err == io.EOF { err = io.ErrUnexpectedEOF } break @@ -393,7 +392,7 @@ func (d *dotReader) Read(b []byte) (n int, err os.Error) { n++ } if err == nil && d.state == stateEOF { - err = os.EOF + err = io.EOF } if err != nil && d.r.dot == d { d.r.dot = nil @@ -418,7 +417,7 @@ func (r *Reader) closeDot() { // ReadDotBytes reads a dot-encoding and returns the decoded data. // // See the documentation for the DotReader method for details about dot-encoding. -func (r *Reader) ReadDotBytes() ([]byte, os.Error) { +func (r *Reader) ReadDotBytes() ([]byte, error) { return ioutil.ReadAll(r.DotReader()) } @@ -426,17 +425,17 @@ func (r *Reader) ReadDotBytes() ([]byte, os.Error) { // containing the decoded lines, with the final \r\n or \n elided from each. // // See the documentation for the DotReader method for details about dot-encoding. -func (r *Reader) ReadDotLines() ([]string, os.Error) { +func (r *Reader) ReadDotLines() ([]string, error) { // We could use ReadDotBytes and then Split it, // but reading a line at a time avoids needing a // large contiguous block of memory and is simpler. var v []string - var err os.Error + var err error for { var line string line, err = r.ReadLine() if err != nil { - if err == os.EOF { + if err == io.EOF { err = io.ErrUnexpectedEOF } break @@ -474,7 +473,7 @@ func (r *Reader) ReadDotLines() ([]string, os.Error) { // "Long-Key": {"Even Longer Value"}, // } // -func (r *Reader) ReadMIMEHeader() (MIMEHeader, os.Error) { +func (r *Reader) ReadMIMEHeader() (MIMEHeader, error) { m := make(MIMEHeader) for { kv, err := r.readContinuedLineSlice() diff --git a/src/pkg/net/textproto/reader_test.go b/src/pkg/net/textproto/reader_test.go index a087e29d91..5aefe39867 100644 --- a/src/pkg/net/textproto/reader_test.go +++ b/src/pkg/net/textproto/reader_test.go @@ -7,7 +7,6 @@ package textproto import ( "bufio" "io" - "os" "reflect" "strings" "testing" @@ -49,7 +48,7 @@ func TestReadLine(t *testing.T) { t.Fatalf("Line 2: %s, %v", s, err) } s, err = r.ReadLine() - if s != "" || err != os.EOF { + if s != "" || err != io.EOF { t.Fatalf("EOF: %s, %v", s, err) } } @@ -69,7 +68,7 @@ func TestReadContinuedLine(t *testing.T) { t.Fatalf("Line 3: %s, %v", s, err) } s, err = r.ReadContinuedLine() - if s != "" || err != os.EOF { + if s != "" || err != io.EOF { t.Fatalf("EOF: %s, %v", s, err) } } @@ -92,7 +91,7 @@ func TestReadCodeLine(t *testing.T) { t.Fatalf("Line 3: wrong error %v\n", err) } code, msg, err = r.ReadCodeLine(1) - if code != 0 || msg != "" || err != os.EOF { + if code != 0 || msg != "" || err != io.EOF { t.Fatalf("EOF: %d, %s, %v", code, msg, err) } } diff --git a/src/pkg/net/textproto/textproto.go b/src/pkg/net/textproto/textproto.go index 9f19b5495d..317ec72b0c 100644 --- a/src/pkg/net/textproto/textproto.go +++ b/src/pkg/net/textproto/textproto.go @@ -27,7 +27,6 @@ import ( "fmt" "io" "net" - "os" ) // An Error represents a numeric error response from a server. @@ -36,7 +35,7 @@ type Error struct { Msg string } -func (e *Error) String() string { +func (e *Error) Error() string { return fmt.Sprintf("%03d %s", e.Code, e.Msg) } @@ -44,7 +43,7 @@ func (e *Error) String() string { // as an invalid response or a hung-up connection. type ProtocolError string -func (p ProtocolError) String() string { +func (p ProtocolError) Error() string { return string(p) } @@ -70,13 +69,13 @@ func NewConn(conn io.ReadWriteCloser) *Conn { } // Close closes the connection. -func (c *Conn) Close() os.Error { +func (c *Conn) Close() error { return c.conn.Close() } // Dial connects to the given address on the given network using net.Dial // and then returns a new Conn for the connection. -func Dial(network, addr string) (*Conn, os.Error) { +func Dial(network, addr string) (*Conn, error) { c, err := net.Dial(network, addr) if err != nil { return nil, err @@ -109,7 +108,7 @@ func Dial(network, addr string) (*Conn, os.Error) { // } // return c.ReadCodeLine(250) // -func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err os.Error) { +func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err error) { id = c.Next() c.StartRequest(id) err = c.PrintfLine(format, args...) diff --git a/src/pkg/net/textproto/writer.go b/src/pkg/net/textproto/writer.go index 4e705f6c3e..03e2fd658e 100644 --- a/src/pkg/net/textproto/writer.go +++ b/src/pkg/net/textproto/writer.go @@ -8,7 +8,6 @@ import ( "bufio" "fmt" "io" - "os" ) // A Writer implements convenience methods for writing @@ -27,7 +26,7 @@ var crnl = []byte{'\r', '\n'} var dotcrnl = []byte{'.', '\r', '\n'} // PrintfLine writes the formatted output followed by \r\n. -func (w *Writer) PrintfLine(format string, args ...interface{}) os.Error { +func (w *Writer) PrintfLine(format string, args ...interface{}) error { w.closeDot() fmt.Fprintf(w.W, format, args...) w.W.Write(crnl) @@ -64,7 +63,7 @@ const ( wstateData // writing data in middle of line ) -func (d *dotWriter) Write(b []byte) (n int, err os.Error) { +func (d *dotWriter) Write(b []byte) (n int, err error) { bw := d.w.W for n < len(b) { c := b[n] @@ -100,7 +99,7 @@ func (d *dotWriter) Write(b []byte) (n int, err os.Error) { return } -func (d *dotWriter) Close() os.Error { +func (d *dotWriter) Close() error { if d.w.dot == d { d.w.dot = nil } diff --git a/src/pkg/net/timeout_test.go b/src/pkg/net/timeout_test.go index 2c2c36fff5..3c884ca7cf 100644 --- a/src/pkg/net/timeout_test.go +++ b/src/pkg/net/timeout_test.go @@ -5,7 +5,6 @@ package net import ( - "os" "runtime" "testing" "time" @@ -22,7 +21,7 @@ func testTimeout(t *testing.T, network, addr string, readFrom bool) { fd.SetReadTimeout(1e8) // 100ms var b [100]byte var n int - var err1 os.Error + var err1 error if readFrom { n, _, err1 = fd.(PacketConn).ReadFrom(b[0:]) } else { diff --git a/src/pkg/net/udpsock.go b/src/pkg/net/udpsock.go index 3dfa71675f..b3520cf09f 100644 --- a/src/pkg/net/udpsock.go +++ b/src/pkg/net/udpsock.go @@ -6,10 +6,6 @@ package net -import ( - "os" -) - // UDPAddr represents the address of a UDP end point. type UDPAddr struct { IP IP @@ -31,7 +27,7 @@ func (a *UDPAddr) String() string { // numeric addresses on the network net, which must be "udp", // "udp4" or "udp6". A literal IPv6 host address must be // enclosed in square brackets, as in "[::]:80". -func ResolveUDPAddr(net, addr string) (*UDPAddr, os.Error) { +func ResolveUDPAddr(net, addr string) (*UDPAddr, error) { ip, port, err := hostPortToIP(net, addr) if err != nil { return nil, err diff --git a/src/pkg/net/udpsock_plan9.go b/src/pkg/net/udpsock_plan9.go index d5c6ccb904..60dec81228 100644 --- a/src/pkg/net/udpsock_plan9.go +++ b/src/pkg/net/udpsock_plan9.go @@ -7,6 +7,7 @@ package net import ( + "errors" "os" ) @@ -24,7 +25,7 @@ type UDPConn struct { // // ReadFromUDP can be made to time out and return an error with Timeout() == true // after a fixed time limit; see SetTimeout and SetReadTimeout. -func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) { +func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -40,7 +41,7 @@ func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) { return } if m < udpHeaderSize { - return 0, nil, os.NewError("short read reading UDP header") + return 0, nil, errors.New("short read reading UDP header") } buf = buf[:m] @@ -50,7 +51,7 @@ func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) { } // ReadFrom implements the net.PacketConn ReadFrom method. -func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { +func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -63,7 +64,7 @@ func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. -func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) { +func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -87,7 +88,7 @@ func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) { } // WriteTo implements the net.PacketConn WriteTo method. -func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { +func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -101,7 +102,7 @@ func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { // DialUDP connects to the remote address raddr on the network net, // which must be "udp", "udp4", or "udp6". If laddr is not nil, it is used // as the local address for the connection. -func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error) { +func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err error) { switch net { case "udp", "udp4", "udp6": default: @@ -149,7 +150,7 @@ func unmarshalUDPHeader(b []byte) (*udpHeader, []byte) { // local address laddr. The returned connection c's ReadFrom // and WriteTo methods can be used to receive and send UDP // packets with per-packet addressing. -func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) { +func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err error) { switch net { case "udp", "udp4", "udp6": default: @@ -172,7 +173,7 @@ func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) { // JoinGroup joins the IP multicast group named by addr on ifi, // which specifies the interface to join. JoinGroup uses the // default multicast interface if ifi is nil. -func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) os.Error { +func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) error { if !c.ok() { return os.EINVAL } @@ -180,7 +181,7 @@ func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) os.Error { } // LeaveGroup exits the IP multicast group named by addr on ifi. -func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) os.Error { +func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) error { if !c.ok() { return os.EINVAL } diff --git a/src/pkg/net/udpsock_posix.go b/src/pkg/net/udpsock_posix.go index 06298ee40c..2cfcc609d4 100644 --- a/src/pkg/net/udpsock_posix.go +++ b/src/pkg/net/udpsock_posix.go @@ -34,7 +34,7 @@ func (a *UDPAddr) family() int { return syscall.AF_INET6 } -func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, os.Error) { +func (a *UDPAddr) sockaddr(family int) (syscall.Sockaddr, error) { return ipToSockaddr(family, a.IP, a.Port) } @@ -58,7 +58,7 @@ func (c *UDPConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *UDPConn) Read(b []byte) (n int, err os.Error) { +func (c *UDPConn) Read(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -66,7 +66,7 @@ func (c *UDPConn) Read(b []byte) (n int, err os.Error) { } // Write implements the net.Conn Write method. -func (c *UDPConn) Write(b []byte) (n int, err os.Error) { +func (c *UDPConn) Write(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -74,7 +74,7 @@ func (c *UDPConn) Write(b []byte) (n int, err os.Error) { } // Close closes the UDP connection. -func (c *UDPConn) Close() os.Error { +func (c *UDPConn) Close() error { if !c.ok() { return os.EINVAL } @@ -100,7 +100,7 @@ func (c *UDPConn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *UDPConn) SetTimeout(nsec int64) os.Error { +func (c *UDPConn) SetTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -108,7 +108,7 @@ func (c *UDPConn) SetTimeout(nsec int64) os.Error { } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *UDPConn) SetReadTimeout(nsec int64) os.Error { +func (c *UDPConn) SetReadTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -116,7 +116,7 @@ func (c *UDPConn) SetReadTimeout(nsec int64) os.Error { } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *UDPConn) SetWriteTimeout(nsec int64) os.Error { +func (c *UDPConn) SetWriteTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -125,7 +125,7 @@ func (c *UDPConn) SetWriteTimeout(nsec int64) os.Error { // SetReadBuffer sets the size of the operating system's // receive buffer associated with the connection. -func (c *UDPConn) SetReadBuffer(bytes int) os.Error { +func (c *UDPConn) SetReadBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -134,7 +134,7 @@ func (c *UDPConn) SetReadBuffer(bytes int) os.Error { // SetWriteBuffer sets the size of the operating system's // transmit buffer associated with the connection. -func (c *UDPConn) SetWriteBuffer(bytes int) os.Error { +func (c *UDPConn) SetWriteBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -149,7 +149,7 @@ func (c *UDPConn) SetWriteBuffer(bytes int) os.Error { // // ReadFromUDP can be made to time out and return an error with Timeout() == true // after a fixed time limit; see SetTimeout and SetReadTimeout. -func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) { +func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -164,7 +164,7 @@ func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.Error) { } // ReadFrom implements the net.PacketConn ReadFrom method. -func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { +func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -178,19 +178,19 @@ func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. -func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) { +func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } sa, err1 := addr.sockaddr(c.fd.family) if err1 != nil { - return 0, &OpError{Op: "write", Net: "udp", Addr: addr, Error: err1} + return 0, &OpError{Op: "write", Net: "udp", Addr: addr, Err: err1} } return c.fd.WriteTo(b, sa) } // WriteTo implements the net.PacketConn WriteTo method. -func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { +func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -204,7 +204,7 @@ func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { // DialUDP connects to the remote address raddr on the network net, // which must be "udp", "udp4", or "udp6". If laddr is not nil, it is used // as the local address for the connection. -func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error) { +func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err error) { switch net { case "udp", "udp4", "udp6": default: @@ -224,7 +224,7 @@ func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.Error) { // local address laddr. The returned connection c's ReadFrom // and WriteTo methods can be used to receive and send UDP // packets with per-packet addressing. -func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) { +func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err error) { switch net { case "udp", "udp4", "udp6": default: @@ -241,7 +241,7 @@ func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) { } // BindToDevice binds a UDPConn to a network interface. -func (c *UDPConn) BindToDevice(device string) os.Error { +func (c *UDPConn) BindToDevice(device string) error { if !c.ok() { return os.EINVAL } @@ -253,12 +253,12 @@ func (c *UDPConn) BindToDevice(device string) os.Error { // File returns a copy of the underlying os.File, set to blocking mode. // It is the caller's responsibility to close f when finished. // Closing c does not affect f, and closing f does not affect c. -func (c *UDPConn) File() (f *os.File, err os.Error) { return c.fd.dup() } +func (c *UDPConn) File() (f *os.File, err error) { return c.fd.dup() } // JoinGroup joins the IP multicast group named by addr on ifi, // which specifies the interface to join. JoinGroup uses the // default multicast interface if ifi is nil. -func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) os.Error { +func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) error { if !c.ok() { return os.EINVAL } @@ -270,7 +270,7 @@ func (c *UDPConn) JoinGroup(ifi *Interface, addr IP) os.Error { } // LeaveGroup exits the IP multicast group named by addr on ifi. -func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) os.Error { +func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) error { if !c.ok() { return os.EINVAL } @@ -281,7 +281,7 @@ func (c *UDPConn) LeaveGroup(ifi *Interface, addr IP) os.Error { return leaveIPv6GroupUDP(c, ifi, addr) } -func joinIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { +func joinIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) error { mreq := &syscall.IPMreq{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}} if err := setIPv4InterfaceToJoin(mreq, ifi); err != nil { return &OpError{"joinipv4group", "udp", &IPAddr{ip}, err} @@ -292,7 +292,7 @@ func joinIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { return nil } -func leaveIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { +func leaveIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) error { mreq := &syscall.IPMreq{Multiaddr: [4]byte{ip[0], ip[1], ip[2], ip[3]}} if err := setIPv4InterfaceToJoin(mreq, ifi); err != nil { return &OpError{"leaveipv4group", "udp", &IPAddr{ip}, err} @@ -303,7 +303,7 @@ func leaveIPv4GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { return nil } -func setIPv4InterfaceToJoin(mreq *syscall.IPMreq, ifi *Interface) os.Error { +func setIPv4InterfaceToJoin(mreq *syscall.IPMreq, ifi *Interface) error { if ifi == nil { return nil } @@ -323,7 +323,7 @@ func setIPv4InterfaceToJoin(mreq *syscall.IPMreq, ifi *Interface) os.Error { return nil } -func joinIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { +func joinIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) error { mreq := &syscall.IPv6Mreq{} copy(mreq.Multiaddr[:], ip) if ifi != nil { @@ -335,7 +335,7 @@ func joinIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { return nil } -func leaveIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) os.Error { +func leaveIPv6GroupUDP(c *UDPConn, ifi *Interface, ip IP) error { mreq := &syscall.IPv6Mreq{} copy(mreq.Multiaddr[:], ip) if ifi != nil { diff --git a/src/pkg/net/unixsock.go b/src/pkg/net/unixsock.go index d5040f9a29..ae0956958f 100644 --- a/src/pkg/net/unixsock.go +++ b/src/pkg/net/unixsock.go @@ -6,10 +6,6 @@ package net -import ( - "os" -) - // UnixAddr represents the address of a Unix domain socket end point. type UnixAddr struct { Name string @@ -38,7 +34,7 @@ func (a *UnixAddr) toAddr() Addr { // ResolveUnixAddr parses addr as a Unix domain socket address. // The string net gives the network name, "unix", "unixgram" or // "unixpacket". -func ResolveUnixAddr(net, addr string) (*UnixAddr, os.Error) { +func ResolveUnixAddr(net, addr string) (*UnixAddr, error) { switch net { case "unix": case "unixpacket": diff --git a/src/pkg/net/unixsock_plan9.go b/src/pkg/net/unixsock_plan9.go index 7e212df8a3..ac502d1d76 100644 --- a/src/pkg/net/unixsock_plan9.go +++ b/src/pkg/net/unixsock_plan9.go @@ -17,17 +17,17 @@ type UnixConn bool // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *UnixConn) Read(b []byte) (n int, err os.Error) { +func (c *UnixConn) Read(b []byte) (n int, err error) { return 0, os.EPLAN9 } // Write implements the net.Conn Write method. -func (c *UnixConn) Write(b []byte) (n int, err os.Error) { +func (c *UnixConn) Write(b []byte) (n int, err error) { return 0, os.EPLAN9 } // Close closes the Unix domain connection. -func (c *UnixConn) Close() os.Error { +func (c *UnixConn) Close() error { return os.EPLAN9 } @@ -45,28 +45,28 @@ func (c *UnixConn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *UnixConn) SetTimeout(nsec int64) os.Error { +func (c *UnixConn) SetTimeout(nsec int64) error { return os.EPLAN9 } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *UnixConn) SetReadTimeout(nsec int64) os.Error { +func (c *UnixConn) SetReadTimeout(nsec int64) error { return os.EPLAN9 } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error { +func (c *UnixConn) SetWriteTimeout(nsec int64) error { return os.EPLAN9 } // ReadFrom implements the net.PacketConn ReadFrom method. -func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { +func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err error) { err = os.EPLAN9 return } // WriteTo implements the net.PacketConn WriteTo method. -func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { +func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error) { err = os.EPLAN9 return } @@ -74,7 +74,7 @@ func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { // DialUnix connects to the remote address raddr on the network net, // which must be "unix" or "unixgram". If laddr is not nil, it is used // as the local address for the connection. -func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err os.Error) { +func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err error) { return nil, os.EPLAN9 } @@ -85,19 +85,19 @@ type UnixListener bool // ListenUnix announces on the Unix domain socket laddr and returns a Unix listener. // Net must be "unix" (stream sockets). -func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) { +func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err error) { return nil, os.EPLAN9 } // Accept implements the Accept method in the Listener interface; // it waits for the next call and returns a generic Conn. -func (l *UnixListener) Accept() (c Conn, err os.Error) { +func (l *UnixListener) Accept() (c Conn, err error) { return nil, os.EPLAN9 } // Close stops listening on the Unix address. // Already accepted connections are not closed. -func (l *UnixListener) Close() os.Error { +func (l *UnixListener) Close() error { return os.EPLAN9 } diff --git a/src/pkg/net/unixsock_posix.go b/src/pkg/net/unixsock_posix.go index fccf0189c0..6ba692e508 100644 --- a/src/pkg/net/unixsock_posix.go +++ b/src/pkg/net/unixsock_posix.go @@ -13,7 +13,7 @@ import ( "syscall" ) -func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err os.Error) { +func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err error) { var proto int switch net { default: @@ -38,7 +38,7 @@ func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err if raddr != nil { ra = &syscall.SockaddrUnix{Name: raddr.Name} } else if proto != syscall.SOCK_DGRAM || laddr == nil { - return nil, &OpError{Op: mode, Net: net, Error: errMissingAddress} + return nil, &OpError{Op: mode, Net: net, Err: errMissingAddress} } case "listen": @@ -47,7 +47,7 @@ func unixSocket(net string, laddr, raddr *UnixAddr, mode string) (fd *netFD, err } la = &syscall.SockaddrUnix{Name: laddr.Name} if raddr != nil { - return nil, &OpError{Op: mode, Net: net, Addr: raddr, Error: &AddrError{Error: "unexpected remote address", Addr: raddr.String()}} + return nil, &OpError{Op: mode, Net: net, Addr: raddr, Err: &AddrError{Err: "unexpected remote address", Addr: raddr.String()}} } } @@ -69,7 +69,7 @@ Error: if mode == "listen" { addr = laddr } - return nil, &OpError{Op: mode, Net: net, Addr: addr, Error: oserr} + return nil, &OpError{Op: mode, Net: net, Addr: addr, Err: oserr} } func sockaddrToUnix(sa syscall.Sockaddr) Addr { @@ -120,7 +120,7 @@ func (c *UnixConn) ok() bool { return c != nil && c.fd != nil } // Implementation of the Conn interface - see Conn for documentation. // Read implements the net.Conn Read method. -func (c *UnixConn) Read(b []byte) (n int, err os.Error) { +func (c *UnixConn) Read(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -128,7 +128,7 @@ func (c *UnixConn) Read(b []byte) (n int, err os.Error) { } // Write implements the net.Conn Write method. -func (c *UnixConn) Write(b []byte) (n int, err os.Error) { +func (c *UnixConn) Write(b []byte) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -136,7 +136,7 @@ func (c *UnixConn) Write(b []byte) (n int, err os.Error) { } // Close closes the Unix domain connection. -func (c *UnixConn) Close() os.Error { +func (c *UnixConn) Close() error { if !c.ok() { return os.EINVAL } @@ -165,7 +165,7 @@ func (c *UnixConn) RemoteAddr() Addr { } // SetTimeout implements the net.Conn SetTimeout method. -func (c *UnixConn) SetTimeout(nsec int64) os.Error { +func (c *UnixConn) SetTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -173,7 +173,7 @@ func (c *UnixConn) SetTimeout(nsec int64) os.Error { } // SetReadTimeout implements the net.Conn SetReadTimeout method. -func (c *UnixConn) SetReadTimeout(nsec int64) os.Error { +func (c *UnixConn) SetReadTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -181,7 +181,7 @@ func (c *UnixConn) SetReadTimeout(nsec int64) os.Error { } // SetWriteTimeout implements the net.Conn SetWriteTimeout method. -func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error { +func (c *UnixConn) SetWriteTimeout(nsec int64) error { if !c.ok() { return os.EINVAL } @@ -190,7 +190,7 @@ func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error { // SetReadBuffer sets the size of the operating system's // receive buffer associated with the connection. -func (c *UnixConn) SetReadBuffer(bytes int) os.Error { +func (c *UnixConn) SetReadBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -199,7 +199,7 @@ func (c *UnixConn) SetReadBuffer(bytes int) os.Error { // SetWriteBuffer sets the size of the operating system's // transmit buffer associated with the connection. -func (c *UnixConn) SetWriteBuffer(bytes int) os.Error { +func (c *UnixConn) SetWriteBuffer(bytes int) error { if !c.ok() { return os.EINVAL } @@ -213,7 +213,7 @@ func (c *UnixConn) SetWriteBuffer(bytes int) os.Error { // ReadFromUnix can be made to time out and return // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetReadTimeout. -func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err os.Error) { +func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -226,7 +226,7 @@ func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err os.Error) } // ReadFrom implements the net.PacketConn ReadFrom method. -func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { +func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err error) { if !c.ok() { return 0, nil, os.EINVAL } @@ -240,7 +240,7 @@ func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) { // an error with Timeout() == true after a fixed time limit; // see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. -func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err os.Error) { +func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -252,7 +252,7 @@ func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err os.Error) { } // WriteTo implements the net.PacketConn WriteTo method. -func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { +func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error) { if !c.ok() { return 0, os.EINVAL } @@ -263,7 +263,7 @@ func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) { return c.WriteToUnix(b, a) } -func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err os.Error) { +func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error) { if !c.ok() { return 0, 0, 0, nil, os.EINVAL } @@ -275,7 +275,7 @@ func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAdd return } -func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err os.Error) { +func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error) { if !c.ok() { return 0, 0, os.EINVAL } @@ -292,12 +292,12 @@ func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err // File returns a copy of the underlying os.File, set to blocking mode. // It is the caller's responsibility to close f when finished. // Closing c does not affect f, and closing f does not affect c. -func (c *UnixConn) File() (f *os.File, err os.Error) { return c.fd.dup() } +func (c *UnixConn) File() (f *os.File, err error) { return c.fd.dup() } // DialUnix connects to the remote address raddr on the network net, // which must be "unix" or "unixgram". If laddr is not nil, it is used // as the local address for the connection. -func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err os.Error) { +func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err error) { fd, e := unixSocket(net, laddr, raddr, "dial") if e != nil { return nil, e @@ -315,7 +315,7 @@ type UnixListener struct { // ListenUnix announces on the Unix domain socket laddr and returns a Unix listener. // Net must be "unix" (stream sockets). -func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) { +func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err error) { if net != "unix" && net != "unixgram" && net != "unixpacket" { return nil, UnknownNetworkError(net) } @@ -329,14 +329,14 @@ func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) { e1 := syscall.Listen(fd.sysfd, 8) // listenBacklog()); if e1 != 0 { closesocket(fd.sysfd) - return nil, &OpError{Op: "listen", Net: "unix", Addr: laddr, Error: os.Errno(e1)} + return nil, &OpError{Op: "listen", Net: "unix", Addr: laddr, Err: os.Errno(e1)} } return &UnixListener{fd, laddr.Name}, nil } // AcceptUnix accepts the next incoming call and returns the new connection // and the remote address. -func (l *UnixListener) AcceptUnix() (c *UnixConn, err os.Error) { +func (l *UnixListener) AcceptUnix() (c *UnixConn, err error) { if l == nil || l.fd == nil { return nil, os.EINVAL } @@ -350,7 +350,7 @@ func (l *UnixListener) AcceptUnix() (c *UnixConn, err os.Error) { // Accept implements the Accept method in the Listener interface; // it waits for the next call and returns a generic Conn. -func (l *UnixListener) Accept() (c Conn, err os.Error) { +func (l *UnixListener) Accept() (c Conn, err error) { c1, err := l.AcceptUnix() if err != nil { return nil, err @@ -360,7 +360,7 @@ func (l *UnixListener) Accept() (c Conn, err os.Error) { // Close stops listening on the Unix address. // Already accepted connections are not closed. -func (l *UnixListener) Close() os.Error { +func (l *UnixListener) Close() error { if l == nil || l.fd == nil { return os.EINVAL } @@ -387,7 +387,7 @@ func (l *UnixListener) Close() os.Error { func (l *UnixListener) Addr() Addr { return l.fd.laddr } // SetTimeout sets the deadline associated wuth the listener -func (l *UnixListener) SetTimeout(nsec int64) (err os.Error) { +func (l *UnixListener) SetTimeout(nsec int64) (err error) { if l == nil || l.fd == nil { return os.EINVAL } @@ -397,13 +397,13 @@ func (l *UnixListener) SetTimeout(nsec int64) (err os.Error) { // File returns a copy of the underlying os.File, set to blocking mode. // It is the caller's responsibility to close f when finished. // Closing c does not affect f, and closing f does not affect c. -func (l *UnixListener) File() (f *os.File, err os.Error) { return l.fd.dup() } +func (l *UnixListener) File() (f *os.File, err error) { return l.fd.dup() } // ListenUnixgram listens for incoming Unix datagram packets addressed to the // local address laddr. The returned connection c's ReadFrom // and WriteTo methods can be used to receive and send UDP // packets with per-packet addressing. The network net must be "unixgram". -func ListenUnixgram(net string, laddr *UnixAddr) (c *UDPConn, err os.Error) { +func ListenUnixgram(net string, laddr *UnixAddr) (c *UDPConn, err error) { switch net { case "unixgram": default: diff --git a/src/pkg/old/netchan/common.go b/src/pkg/old/netchan/common.go index ac1ca12f5f..855b7175f7 100644 --- a/src/pkg/old/netchan/common.go +++ b/src/pkg/old/netchan/common.go @@ -5,9 +5,9 @@ package netchan import ( + "errors" "gob" "io" - "os" "reflect" "sync" "time" @@ -60,7 +60,7 @@ type request struct { } // Sent with a header to report an error. -type error struct { +type error_ struct { Error string } @@ -101,7 +101,7 @@ func newEncDec(conn io.ReadWriter) *encDec { } // Decode an item from the connection. -func (ed *encDec) decode(value reflect.Value) os.Error { +func (ed *encDec) decode(value reflect.Value) error { ed.decLock.Lock() err := ed.dec.DecodeValue(value) if err != nil { @@ -112,7 +112,7 @@ func (ed *encDec) decode(value reflect.Value) os.Error { } // Encode a header and payload onto the connection. -func (ed *encDec) encode(hdr *header, payloadType int, payload interface{}) os.Error { +func (ed *encDec) encode(hdr *header, payloadType int, payload interface{}) error { ed.encLock.Lock() hdr.PayloadType = payloadType err := ed.enc.Encode(hdr) @@ -129,7 +129,7 @@ func (ed *encDec) encode(hdr *header, payloadType int, payload interface{}) os.E } // See the comment for Exporter.Drain. -func (cs *clientSet) drain(timeout int64) os.Error { +func (cs *clientSet) drain(timeout int64) error { startTime := time.Nanoseconds() for { pending := false @@ -153,7 +153,7 @@ func (cs *clientSet) drain(timeout int64) os.Error { break } if timeout > 0 && time.Nanoseconds()-startTime >= timeout { - return os.NewError("timeout") + return errors.New("timeout") } time.Sleep(100 * 1e6) // 100 milliseconds } @@ -161,7 +161,7 @@ func (cs *clientSet) drain(timeout int64) os.Error { } // See the comment for Exporter.Sync. -func (cs *clientSet) sync(timeout int64) os.Error { +func (cs *clientSet) sync(timeout int64) error { startTime := time.Nanoseconds() // seq remembers the clients and their seqNum at point of entry. seq := make(map[unackedCounter]int64) @@ -186,7 +186,7 @@ func (cs *clientSet) sync(timeout int64) os.Error { break } if timeout > 0 && time.Nanoseconds()-startTime >= timeout { - return os.NewError("timeout") + return errors.New("timeout") } time.Sleep(100 * 1e6) // 100 milliseconds } diff --git a/src/pkg/old/netchan/export.go b/src/pkg/old/netchan/export.go index 99d5d7e05d..a4c4c6aeb5 100644 --- a/src/pkg/old/netchan/export.go +++ b/src/pkg/old/netchan/export.go @@ -22,10 +22,10 @@ package netchan // BUG: can't use range clause to receive when using ImportNValues to limit the count. import ( + "errors" "log" "io" "net" - "os" "reflect" "strconv" "sync" @@ -68,7 +68,7 @@ func newClient(exp *Exporter, conn io.ReadWriter) *expClient { } func (client *expClient) sendError(hdr *header, err string) { - error := &error{err} + error := &error_{err} expLog("sending error to client:", error.Error) client.encode(hdr, payError, error) // ignore any encode error, hope client gets it client.mu.Lock() @@ -114,11 +114,11 @@ func (client *expClient) run() { hdrValue := reflect.ValueOf(hdr) req := new(request) reqValue := reflect.ValueOf(req) - error := new(error) + error := new(error_) for { *hdr = header{} if err := client.decode(hdrValue); err != nil { - if err != os.EOF { + if err != io.EOF { expLog("error decoding client header:", err) } break @@ -201,7 +201,7 @@ func (client *expClient) serveRecv(nch *netChan, hdr header, count int64) { client.seqLock.Unlock() if err != nil { expLog("error encoding client response:", err) - client.sendError(&hdr, err.String()) + client.sendError(&hdr, err.Error()) break } // Negative count means run forever. @@ -293,7 +293,7 @@ func NewExporter() *Exporter { // ListenAndServe exports the exporter's channels through the // given network and local address defined as in net.Listen. -func (exp *Exporter) ListenAndServe(network, localaddr string) os.Error { +func (exp *Exporter) ListenAndServe(network, localaddr string) error { listener, err := net.Listen(network, localaddr) if err != nil { return err @@ -324,7 +324,7 @@ func (exp *Exporter) delClient(client *expClient) { // waits until all the exporter's messages have been received by a client. // If the timeout (measured in nanoseconds) is positive and Drain takes // longer than that to complete, an error is returned. -func (exp *Exporter) Drain(timeout int64) os.Error { +func (exp *Exporter) Drain(timeout int64) error { // This wrapper function is here so the method's comment will appear in godoc. return exp.clientSet.drain(timeout) } @@ -335,28 +335,28 @@ func (exp *Exporter) Drain(timeout int64) os.Error { // dispatched to any client. If the timeout (measured in nanoseconds) is // positive and Sync takes longer than that to complete, an error is // returned. -func (exp *Exporter) Sync(timeout int64) os.Error { +func (exp *Exporter) Sync(timeout int64) error { // This wrapper function is here so the method's comment will appear in godoc. return exp.clientSet.sync(timeout) } -func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) { +func checkChan(chT interface{}, dir Dir) (reflect.Value, error) { chanType := reflect.TypeOf(chT) if chanType.Kind() != reflect.Chan { - return reflect.Value{}, os.NewError("not a channel") + return reflect.Value{}, errors.New("not a channel") } if dir != Send && dir != Recv { - return reflect.Value{}, os.NewError("unknown channel direction") + return reflect.Value{}, errors.New("unknown channel direction") } switch chanType.ChanDir() { case reflect.BothDir: case reflect.SendDir: if dir != Recv { - return reflect.Value{}, os.NewError("to import/export with Send, must provide <-chan") + return reflect.Value{}, errors.New("to import/export with Send, must provide <-chan") } case reflect.RecvDir: if dir != Send { - return reflect.Value{}, os.NewError("to import/export with Recv, must provide chan<-") + return reflect.Value{}, errors.New("to import/export with Recv, must provide chan<-") } } return reflect.ValueOf(chT), nil @@ -367,7 +367,7 @@ func checkChan(chT interface{}, dir Dir) (reflect.Value, os.Error) { // channel type. // Despite the literal signature, the effective signature is // Export(name string, chT chan T, dir Dir) -func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error { +func (exp *Exporter) Export(name string, chT interface{}, dir Dir) error { ch, err := checkChan(chT, dir) if err != nil { return err @@ -376,7 +376,7 @@ func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error { defer exp.mu.Unlock() _, present := exp.names[name] if present { - return os.NewError("channel name already being exported:" + name) + return errors.New("channel name already being exported:" + name) } exp.names[name] = &chanDir{ch, dir} return nil @@ -384,7 +384,7 @@ func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error { // Hangup disassociates the named channel from the Exporter and closes // the channel. Messages in flight for the channel may be dropped. -func (exp *Exporter) Hangup(name string) os.Error { +func (exp *Exporter) Hangup(name string) error { exp.mu.Lock() chDir, ok := exp.names[name] if ok { @@ -393,7 +393,7 @@ func (exp *Exporter) Hangup(name string) os.Error { // TODO drop all instances of channel from client sets exp.mu.Unlock() if !ok { - return os.NewError("netchan export: hangup: no such channel: " + name) + return errors.New("netchan export: hangup: no such channel: " + name) } chDir.ch.Close() return nil diff --git a/src/pkg/old/netchan/import.go b/src/pkg/old/netchan/import.go index 5a459e0d5a..0c00e1574e 100644 --- a/src/pkg/old/netchan/import.go +++ b/src/pkg/old/netchan/import.go @@ -5,10 +5,10 @@ package netchan import ( + "errors" "io" "log" "net" - "os" "reflect" "sync" "time" @@ -30,7 +30,7 @@ type Importer struct { chanLock sync.Mutex // protects access to channel map names map[string]*netChan chans map[int]*netChan - errors chan os.Error + errors chan error maxId int mu sync.Mutex // protects remaining fields unacked int64 // number of unacknowledged sends. @@ -45,14 +45,14 @@ func NewImporter(conn io.ReadWriter) *Importer { imp.encDec = newEncDec(conn) imp.chans = make(map[int]*netChan) imp.names = make(map[string]*netChan) - imp.errors = make(chan os.Error, 10) + imp.errors = make(chan error, 10) imp.unacked = 0 go imp.run() return imp } // Import imports a set of channels from the given network and address. -func Import(network, remoteaddr string) (*Importer, os.Error) { +func Import(network, remoteaddr string) (*Importer, error) { conn, err := net.Dial(network, remoteaddr) if err != nil { return nil, err @@ -80,12 +80,12 @@ func (imp *Importer) run() { hdr := new(header) hdrValue := reflect.ValueOf(hdr) ackHdr := new(header) - err := new(error) + err := new(error_) errValue := reflect.ValueOf(err) for { *hdr = header{} if e := imp.decode(hdrValue); e != nil { - if e != os.EOF { + if e != io.EOF { impLog("header:", e) imp.shutdown() } @@ -102,7 +102,7 @@ func (imp *Importer) run() { if err.Error != "" { impLog("response error:", err.Error) select { - case imp.errors <- os.NewError(err.Error): + case imp.errors <- errors.New(err.Error): continue // errors are not acknowledged default: imp.shutdown() @@ -169,13 +169,13 @@ func (imp *Importer) getChan(id int, errOk bool) *netChan { // can be read. Clients of the importer are not required to read the error // channel for correct execution. However, if too many errors occur // without being read from the error channel, the importer will shut down. -func (imp *Importer) Errors() chan os.Error { +func (imp *Importer) Errors() chan error { return imp.errors } // Import imports a channel of the given type, size and specified direction. // It is equivalent to ImportNValues with a count of -1, meaning unbounded. -func (imp *Importer) Import(name string, chT interface{}, dir Dir, size int) os.Error { +func (imp *Importer) Import(name string, chT interface{}, dir Dir, size int) error { return imp.ImportNValues(name, chT, dir, size, -1) } @@ -194,7 +194,7 @@ func (imp *Importer) Import(name string, chT interface{}, dir Dir, size int) os. // err = imp.ImportNValues("name", ch, Recv, 1, 1) // if err != nil { log.Fatal(err) } // fmt.Printf("%+v\n", <-ch) -func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size, n int) os.Error { +func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size, n int) error { ch, err := checkChan(chT, dir) if err != nil { return err @@ -203,7 +203,7 @@ func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size, defer imp.chanLock.Unlock() _, present := imp.names[name] if present { - return os.NewError("channel name already being imported:" + name) + return errors.New("channel name already being imported:" + name) } if size < 1 { size = 1 @@ -249,12 +249,12 @@ func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, size, // Hangup disassociates the named channel from the Importer and closes // the channel. Messages in flight for the channel may be dropped. -func (imp *Importer) Hangup(name string) os.Error { +func (imp *Importer) Hangup(name string) error { imp.chanLock.Lock() defer imp.chanLock.Unlock() nc := imp.names[name] if nc == nil { - return os.NewError("netchan import: hangup: no such channel: " + name) + return errors.New("netchan import: hangup: no such channel: " + name) } delete(imp.names, name) delete(imp.chans, nc.id) @@ -275,11 +275,11 @@ func (imp *Importer) unackedCount() int64 { // waits until all the importer's messages have been received. // If the timeout (measured in nanoseconds) is positive and Drain takes // longer than that to complete, an error is returned. -func (imp *Importer) Drain(timeout int64) os.Error { +func (imp *Importer) Drain(timeout int64) error { startTime := time.Nanoseconds() for imp.unackedCount() > 0 { if timeout > 0 && time.Nanoseconds()-startTime >= timeout { - return os.NewError("timeout") + return errors.New("timeout") } time.Sleep(100 * 1e6) } diff --git a/src/pkg/old/netchan/netchan_test.go b/src/pkg/old/netchan/netchan_test.go index 8c0f9a6e4b..d11a670866 100644 --- a/src/pkg/old/netchan/netchan_test.go +++ b/src/pkg/old/netchan/netchan_test.go @@ -156,7 +156,7 @@ func TestErrorForIllegalChannel(t *testing.T) { }() select { case err = <-imp.Errors(): - if strings.Index(err.String(), "no such channel") < 0 { + if strings.Index(err.Error(), "no such channel") < 0 { t.Error("wrong error for nonexistent channel:", err) } case <-timeout: diff --git a/src/pkg/old/regexp/all_test.go b/src/pkg/old/regexp/all_test.go index 71edc4d18d..9a04360dd1 100644 --- a/src/pkg/old/regexp/all_test.go +++ b/src/pkg/old/regexp/all_test.go @@ -5,7 +5,6 @@ package regexp import ( - "os" "strings" "testing" ) @@ -33,7 +32,7 @@ var good_re = []string{ type stringError struct { re string - err os.Error + err error } var bad_re = []stringError{ @@ -52,10 +51,10 @@ var bad_re = []stringError{ {`\x`, ErrBadBackslash}, } -func compileTest(t *testing.T, expr string, error os.Error) *Regexp { +func compileTest(t *testing.T, expr string, error error) *Regexp { re, err := Compile(expr) if err != error { - t.Error("compiling `", expr, "`; unexpected error: ", err.String()) + t.Error("compiling `", expr, "`; unexpected error: ", err.Error()) } return re } diff --git a/src/pkg/old/regexp/regexp.go b/src/pkg/old/regexp/regexp.go index f18d9c8f59..720aaf36e4 100644 --- a/src/pkg/old/regexp/regexp.go +++ b/src/pkg/old/regexp/regexp.go @@ -71,7 +71,6 @@ package regexp import ( "bytes" "io" - "os" "strings" "utf8" ) @@ -81,7 +80,7 @@ var debug = false // Error is the local type for a parsing error. type Error string -func (e Error) String() string { +func (e Error) Error() string { return string(e) } @@ -616,7 +615,7 @@ func (re *Regexp) String() string { // Compile parses a regular expression and returns, if successful, a Regexp // object that can be used to match against text. -func Compile(str string) (regexp *Regexp, error os.Error) { +func Compile(str string) (regexp *Regexp, error error) { regexp = new(Regexp) // doParse will panic if there is a parse error. defer func() { @@ -637,7 +636,7 @@ func Compile(str string) (regexp *Regexp, error os.Error) { func MustCompile(str string) *Regexp { regexp, error := Compile(str) if error != nil { - panic(`regexp: compiling "` + str + `": ` + error.String()) + panic(`regexp: compiling "` + str + `": ` + error.Error()) } return regexp } @@ -998,7 +997,7 @@ func (re *Regexp) Match(b []byte) bool { return len(re.doExecute(newInputBytes(b // MatchReader checks whether a textual regular expression matches the text // read by the RuneReader. More complicated queries need to use Compile and // the full Regexp interface. -func MatchReader(pattern string, r io.RuneReader) (matched bool, error os.Error) { +func MatchReader(pattern string, r io.RuneReader) (matched bool, error error) { re, err := Compile(pattern) if err != nil { return false, err @@ -1009,7 +1008,7 @@ func MatchReader(pattern string, r io.RuneReader) (matched bool, error os.Error) // MatchString checks whether a textual regular expression // matches a string. More complicated queries need // to use Compile and the full Regexp interface. -func MatchString(pattern string, s string) (matched bool, error os.Error) { +func MatchString(pattern string, s string) (matched bool, error error) { re, err := Compile(pattern) if err != nil { return false, err @@ -1020,7 +1019,7 @@ func MatchString(pattern string, s string) (matched bool, error os.Error) { // Match checks whether a textual regular expression // matches a byte slice. More complicated queries need // to use Compile and the full Regexp interface. -func Match(pattern string, b []byte) (matched bool, error os.Error) { +func Match(pattern string, b []byte) (matched bool, error error) { re, err := Compile(pattern) if err != nil { return false, err diff --git a/src/pkg/old/template/parse.go b/src/pkg/old/template/parse.go index 9f8d1eba33..fc9885feef 100644 --- a/src/pkg/old/template/parse.go +++ b/src/pkg/old/template/parse.go @@ -10,7 +10,6 @@ import ( "fmt" "io" "io/ioutil" - "os" "reflect" "strconv" "strings" @@ -25,11 +24,11 @@ type Error struct { Msg string } -func (e *Error) String() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) } +func (e *Error) Error() string { return fmt.Sprintf("line %d: %s", e.Line, e.Msg) } // checkError is a deferred function to turn a panic with type *Error into a plain error return. // Other panics are unexpected and so are re-enabled. -func checkError(error *os.Error) { +func checkError(error *error) { if v := recover(); v != nil { if e, ok := v.(*Error); ok { *error = e @@ -414,7 +413,7 @@ func (t *Template) newVariable(words []string) *variableElement { // Build argument list, processing any literals for i, word := range words { - var lerr os.Error + var lerr error switch word[0] { case '"', '`', '\'': v, err := strconv.Unquote(word) @@ -650,7 +649,7 @@ func (t *Template) parse() { // Parse initializes a Template by parsing its definition. The string // s contains the template text. If any errors occur, Parse returns // the error. -func (t *Template) Parse(s string) (err os.Error) { +func (t *Template) Parse(s string) (err error) { if t.elems == nil { return &Error{1, "template not allocated with New"} } @@ -667,7 +666,7 @@ func (t *Template) Parse(s string) (err os.Error) { // ParseFile is like Parse but reads the template definition from the // named file. -func (t *Template) ParseFile(filename string) (err os.Error) { +func (t *Template) ParseFile(filename string) (err error) { b, err := ioutil.ReadFile(filename) if err != nil { return err @@ -677,7 +676,7 @@ func (t *Template) ParseFile(filename string) (err os.Error) { // Execute applies a parsed template to the specified data object, // generating output to wr. -func (t *Template) Execute(wr io.Writer, data interface{}) (err os.Error) { +func (t *Template) Execute(wr io.Writer, data interface{}) (err error) { // Extract the driver data. val := reflect.ValueOf(data) defer checkError(&err) @@ -701,7 +700,7 @@ func (t *Template) SetDelims(left, right string) { // the formatter map fmap, which may be nil, defines auxiliary functions // for formatting variables. The template is returned. If any errors // occur, err will be non-nil. -func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) { +func Parse(s string, fmap FormatterMap) (t *Template, err error) { t = New(fmap) err = t.Parse(s) if err != nil { @@ -715,7 +714,7 @@ func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) { // a file containing the template text, while the formatter map fmap, which // may be nil, defines auxiliary functions for formatting variables. // The template is returned. If any errors occur, err will be non-nil. -func ParseFile(filename string, fmap FormatterMap) (t *Template, err os.Error) { +func ParseFile(filename string, fmap FormatterMap) (t *Template, err error) { b, err := ioutil.ReadFile(filename) if err != nil { return nil, err @@ -727,7 +726,7 @@ func ParseFile(filename string, fmap FormatterMap) (t *Template, err os.Error) { func MustParse(s string, fmap FormatterMap) *Template { t, err := Parse(s, fmap) if err != nil { - panic("template.MustParse error: " + err.String()) + panic("template.MustParse error: " + err.Error()) } return t } @@ -737,7 +736,7 @@ func MustParse(s string, fmap FormatterMap) *Template { func MustParseFile(filename string, fmap FormatterMap) *Template { b, err := ioutil.ReadFile(filename) if err != nil { - panic("template.MustParseFile error: " + err.String()) + panic("template.MustParseFile error: " + err.Error()) } return MustParse(string(b), fmap) } diff --git a/src/pkg/old/template/template_test.go b/src/pkg/old/template/template_test.go index 9595eb189b..c88346995a 100644 --- a/src/pkg/old/template/template_test.go +++ b/src/pkg/old/template/template_test.go @@ -10,7 +10,6 @@ import ( "io" "io/ioutil" "json" - "os" "strings" "testing" ) @@ -462,9 +461,9 @@ var tests = []*Test{ func TestAll(t *testing.T) { // Parse - testAll(t, func(test *Test) (*Template, os.Error) { return Parse(test.in, formatters) }) + testAll(t, func(test *Test) (*Template, error) { return Parse(test.in, formatters) }) // ParseFile - testAll(t, func(test *Test) (*Template, os.Error) { + testAll(t, func(test *Test) (*Template, error) { err := ioutil.WriteFile("_test/test.tmpl", []byte(test.in), 0600) if err != nil { t.Error("unexpected write error:", err) @@ -473,7 +472,7 @@ func TestAll(t *testing.T) { return ParseFile("_test/test.tmpl", formatters) }) // tmpl.ParseFile - testAll(t, func(test *Test) (*Template, os.Error) { + testAll(t, func(test *Test) (*Template, error) { err := ioutil.WriteFile("_test/test.tmpl", []byte(test.in), 0600) if err != nil { t.Error("unexpected write error:", err) @@ -484,7 +483,7 @@ func TestAll(t *testing.T) { }) } -func testAll(t *testing.T, parseFunc func(*Test) (*Template, os.Error)) { +func testAll(t *testing.T, parseFunc func(*Test) (*Template, error)) { s := new(S) // initialized by hand for clarity. s.Header = "Header" @@ -530,8 +529,8 @@ func testAll(t *testing.T, parseFunc func(*Test) (*Template, os.Error)) { } else { if err == nil { t.Errorf("expected execute error %q, got nil", test.err) - } else if err.String() != test.err { - t.Errorf("expected execute error %q, got %q", test.err, err.String()) + } else if err.Error() != test.err { + t.Errorf("expected execute error %q, got %q", test.err, err.Error()) } } if buf.String() != test.out { @@ -703,7 +702,7 @@ func TestReferenceToUnexported(t *testing.T) { if err == nil { t.Fatal("expected execute error, got none") } - if strings.Index(err.String(), "not exported") < 0 { + if strings.Index(err.Error(), "not exported") < 0 { t.Fatal("expected unexported error; got", err) } } @@ -777,8 +776,8 @@ func TestFormatters(t *testing.T) { t.Error("unexpected parse error:", err) continue } - if strings.Index(err.String(), c.err) < 0 { - t.Errorf("unexpected error: expected %q, got %q", c.err, err.String()) + if strings.Index(err.Error(), c.err) < 0 { + t.Errorf("unexpected error: expected %q, got %q", c.err, err.Error()) continue } } else { diff --git a/src/pkg/os/user/lookup_stubs.go b/src/pkg/os/user/lookup_stubs.go index 2d2de989f0..0999dedbb9 100644 --- a/src/pkg/os/user/lookup_stubs.go +++ b/src/pkg/os/user/lookup_stubs.go @@ -8,14 +8,13 @@ package user import ( "fmt" - "os" "runtime" ) -func Lookup(username string) (*User, os.Error) { +func Lookup(username string) (*User, error) { return nil, fmt.Errorf("user: Lookup not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } -func LookupId(int) (*User, os.Error) { +func LookupId(int) (*User, error) { return nil, fmt.Errorf("user: LookupId not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } diff --git a/src/pkg/os/user/lookup_unix.go b/src/pkg/os/user/lookup_unix.go index 817eb791cb..87cd197a3f 100644 --- a/src/pkg/os/user/lookup_unix.go +++ b/src/pkg/os/user/lookup_unix.go @@ -33,17 +33,17 @@ func init() { // Lookup looks up a user by username. If the user cannot be found, // the returned error is of type UnknownUserError. -func Lookup(username string) (*User, os.Error) { +func Lookup(username string) (*User, error) { return lookup(-1, username, true) } // LookupId looks up a user by userid. If the user cannot be found, // the returned error is of type UnknownUserIdError. -func LookupId(uid int) (*User, os.Error) { +func LookupId(uid int) (*User, error) { return lookup(uid, "", false) } -func lookup(uid int, username string, lookupByName bool) (*User, os.Error) { +func lookup(uid int, username string, lookupByName bool) (*User, error) { var pwd C.struct_passwd var result *C.struct_passwd diff --git a/src/pkg/os/user/user.go b/src/pkg/os/user/user.go index f71e11d8b2..a019537776 100644 --- a/src/pkg/os/user/user.go +++ b/src/pkg/os/user/user.go @@ -24,7 +24,7 @@ type User struct { // a user cannot be found. type UnknownUserIdError int -func (e UnknownUserIdError) String() string { +func (e UnknownUserIdError) Error() string { return "user: unknown userid " + strconv.Itoa(int(e)) } @@ -32,6 +32,6 @@ func (e UnknownUserIdError) String() string { // a user cannot be found. type UnknownUserError string -func (e UnknownUserError) String() string { +func (e UnknownUserError) Error() string { return "user: unknown user " + string(e) } diff --git a/src/pkg/patch/apply.go b/src/pkg/patch/apply.go index 0dd9080bf3..7c4f4ada41 100644 --- a/src/pkg/patch/apply.go +++ b/src/pkg/patch/apply.go @@ -23,7 +23,7 @@ type Op struct { // The function readFile should return the contents of the named file. // Typically this function will be io.ReadFile. // -func (set *Set) Apply(readFile func(string) ([]byte, os.Error)) ([]Op, os.Error) { +func (set *Set) Apply(readFile func(string) ([]byte, error)) ([]Op, error) { op := make([]Op, len(set.File)) for i, f := range set.File { @@ -36,7 +36,7 @@ func (set *Set) Apply(readFile func(string) ([]byte, os.Error)) ([]Op, os.Error) // Clients assume o.Data == nil means no data diff. // Start with a non-nil data. var old []byte = make([]byte, 0) // not nil - var err os.Error + var err error if f.Src != "" { old, err = readFile(f.Src) if err != nil { diff --git a/src/pkg/patch/git.go b/src/pkg/patch/git.go index 6516097260..454eadecec 100644 --- a/src/pkg/patch/git.go +++ b/src/pkg/patch/git.go @@ -9,9 +9,9 @@ import ( "compress/zlib" "crypto/sha1" "encoding/git85" + "errors" "fmt" "io" - "os" ) func gitSHA1(data []byte) []byte { @@ -34,7 +34,7 @@ type GitBinaryLiteral struct { } // Apply implements the Diff interface's Apply method. -func (d *GitBinaryLiteral) Apply(old []byte) ([]byte, os.Error) { +func (d *GitBinaryLiteral) Apply(old []byte) ([]byte, error) { if sum := gitSHA1(old); !bytes.HasPrefix(sum, d.OldSHA1) { return nil, ErrPatchFailure } @@ -68,7 +68,7 @@ func getHex(s []byte) (data []byte, rest []byte) { } // ParseGitBinary parses raw as a Git binary patch. -func ParseGitBinary(raw []byte) (Diff, os.Error) { +func ParseGitBinary(raw []byte) (Diff, error) { var oldSHA1, newSHA1 []byte var sawBinary bool @@ -97,24 +97,24 @@ func ParseGitBinary(raw []byte) (Diff, os.Error) { } defer z.Close() if _, err = io.ReadFull(z, data); err != nil { - if err == os.EOF { + if err == io.EOF { err = io.ErrUnexpectedEOF } return nil, err } var buf [1]byte m, err := z.Read(buf[0:]) - if m != 0 || err != os.EOF { - return nil, os.NewError("Git binary literal longer than expected") + if m != 0 || err != io.EOF { + return nil, errors.New("Git binary literal longer than expected") } if sum := gitSHA1(data); !bytes.HasPrefix(sum, newSHA1) { - return nil, os.NewError("Git binary literal SHA1 mismatch") + return nil, errors.New("Git binary literal SHA1 mismatch") } return &GitBinaryLiteral{oldSHA1, data}, nil } if !sawBinary { - return nil, os.NewError("unexpected Git patch header: " + string(first)) + return nil, errors.New("unexpected Git patch header: " + string(first)) } } panic("unreachable") diff --git a/src/pkg/patch/patch.go b/src/pkg/patch/patch.go index fcc8307e09..1d804f3362 100644 --- a/src/pkg/patch/patch.go +++ b/src/pkg/patch/patch.go @@ -9,7 +9,6 @@ package patch import ( "bytes" - "os" "path" "strings" ) @@ -47,7 +46,7 @@ type Diff interface { // Apply applies the changes listed in the diff // to the string s, returning the new version of the string. // Note that the string s need not be a text string. - Apply(old []byte) (new []byte, err os.Error) + Apply(old []byte) (new []byte, err error) } // NoDiff is a no-op Diff implementation: it passes the @@ -56,14 +55,14 @@ var NoDiff Diff = noDiffType(0) type noDiffType int -func (noDiffType) Apply(old []byte) ([]byte, os.Error) { +func (noDiffType) Apply(old []byte) ([]byte, error) { return old, nil } // A SyntaxError represents a syntax error encountered while parsing a patch. type SyntaxError string -func (e SyntaxError) String() string { return string(e) } +func (e SyntaxError) Error() string { return string(e) } var newline = []byte{'\n'} @@ -71,7 +70,7 @@ var newline = []byte{'\n'} // The patch text typically comprises a textual header and a sequence // of file patches, as would be generated by CVS, Subversion, // Mercurial, or Git. -func Parse(text []byte) (*Set, os.Error) { +func Parse(text []byte) (*Set, error) { // Split text into files. // CVS and Subversion begin new files with // Index: file name. diff --git a/src/pkg/patch/textdiff.go b/src/pkg/patch/textdiff.go index 482bd67816..adb629a293 100644 --- a/src/pkg/patch/textdiff.go +++ b/src/pkg/patch/textdiff.go @@ -2,7 +2,7 @@ package patch import ( "bytes" - "os" + "errors" ) type TextDiff []TextChunk @@ -16,7 +16,7 @@ type TextChunk struct { New []byte } -func ParseTextDiff(raw []byte) (TextDiff, os.Error) { +func ParseTextDiff(raw []byte) (TextDiff, error) { var chunkHeader []byte // Copy raw so it is safe to keep references to slices. @@ -151,11 +151,11 @@ ErrChunkHdr: return nil, SyntaxError("unexpected chunk header line: " + string(chunkHeader)) } -var ErrPatchFailure = os.NewError("patch did not apply cleanly") +var ErrPatchFailure = errors.New("patch did not apply cleanly") // Apply applies the changes listed in the diff // to the data, returning the new version. -func (d TextDiff) Apply(data []byte) ([]byte, os.Error) { +func (d TextDiff) Apply(data []byte) ([]byte, error) { var buf bytes.Buffer line := 1 for _, c := range d { diff --git a/src/pkg/path/filepath/match.go b/src/pkg/path/filepath/match.go index 15c84a7e98..bc0930e98b 100644 --- a/src/pkg/path/filepath/match.go +++ b/src/pkg/path/filepath/match.go @@ -5,13 +5,14 @@ package filepath import ( + "errors" "os" "sort" "strings" "utf8" ) -var ErrBadPattern = os.NewError("syntax error in pattern") +var ErrBadPattern = errors.New("syntax error in pattern") // Match returns true if name matches the shell file name pattern. // The pattern syntax is: @@ -34,7 +35,7 @@ var ErrBadPattern = os.NewError("syntax error in pattern") // Match requires pattern to match all of name, not just a substring. // The only possible error return occurs when the pattern is malformed. // -func Match(pattern, name string) (matched bool, err os.Error) { +func Match(pattern, name string) (matched bool, err error) { Pattern: for len(pattern) > 0 { var star bool @@ -112,7 +113,7 @@ Scan: // matchChunk checks whether chunk matches the beginning of s. // If so, it returns the remainder of s (after the match). // Chunk is all single-character operators: literals, char classes, and ?. -func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) { +func matchChunk(chunk, s string) (rest string, ok bool, err error) { for len(chunk) > 0 { if len(s) == 0 { return @@ -183,7 +184,7 @@ func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) { } // getEsc gets a possibly-escaped character from chunk, for a character class. -func getEsc(chunk string) (r rune, nchunk string, err os.Error) { +func getEsc(chunk string) (r rune, nchunk string, err error) { if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' { err = ErrBadPattern return @@ -212,7 +213,7 @@ func getEsc(chunk string) (r rune, nchunk string, err os.Error) { // /usr/*/bin/ed (assuming the Separator is '/'). // The only possible error return occurs when the pattern is malformed. // -func Glob(pattern string) (matches []string, err os.Error) { +func Glob(pattern string) (matches []string, err error) { if !hasMeta(pattern) { if _, err = os.Stat(pattern); err != nil { return nil, nil @@ -253,7 +254,7 @@ func Glob(pattern string) (matches []string, err os.Error) { // opened, it returns the existing matches. New matches are // added in lexicographical order. // The only possible error return occurs when the pattern is malformed. -func glob(dir, pattern string, matches []string) (m []string, e os.Error) { +func glob(dir, pattern string, matches []string) (m []string, e error) { m = matches fi, err := os.Stat(dir) if err != nil { diff --git a/src/pkg/path/filepath/match_test.go b/src/pkg/path/filepath/match_test.go index 711e835fb7..cdf3b66a88 100644 --- a/src/pkg/path/filepath/match_test.go +++ b/src/pkg/path/filepath/match_test.go @@ -5,7 +5,6 @@ package filepath_test import ( - "os" . "path/filepath" "testing" "runtime" @@ -14,7 +13,7 @@ import ( type MatchTest struct { pattern, s string match bool - err os.Error + err error } var matchTests = []MatchTest{ @@ -69,11 +68,11 @@ var matchTests = []MatchTest{ {"*x", "xxx", true, nil}, } -func errp(e os.Error) string { +func errp(e error) string { if e == nil { return "" } - return e.String() + return e.Error() } func TestMatch(t *testing.T) { diff --git a/src/pkg/path/filepath/path.go b/src/pkg/path/filepath/path.go index afb8f102d5..1b5d6c3649 100644 --- a/src/pkg/path/filepath/path.go +++ b/src/pkg/path/filepath/path.go @@ -8,6 +8,7 @@ package filepath import ( "bytes" + "errors" "os" "runtime" "sort" @@ -182,7 +183,7 @@ func Ext(path string) string { // EvalSymlinks returns the path name after the evaluation of any symbolic // links. // If path is relative it will be evaluated relative to the current directory. -func EvalSymlinks(path string) (string, os.Error) { +func EvalSymlinks(path string) (string, error) { if runtime.GOOS == "windows" { // Symlinks are not supported under windows. _, err := os.Lstat(path) @@ -198,7 +199,7 @@ func EvalSymlinks(path string) (string, os.Error) { var b bytes.Buffer for n := 0; path != ""; n++ { if n > maxIter { - return "", os.NewError("EvalSymlinks: too many links in " + originalPath) + return "", errors.New("EvalSymlinks: too many links in " + originalPath) } // find next path component, p @@ -247,7 +248,7 @@ func EvalSymlinks(path string) (string, os.Error) { // If the path is not absolute it will be joined with the current // working directory to turn it into an absolute path. The absolute // path name for a given file is not guaranteed to be unique. -func Abs(path string) (string, os.Error) { +func Abs(path string) (string, error) { if IsAbs(path) { return Clean(path), nil } @@ -263,7 +264,7 @@ func Abs(path string) (string, os.Error) { // Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. // An error is returned if targpath can't be made relative to basepath or if // knowing the current working directory would be necessary to compute it. -func Rel(basepath, targpath string) (string, os.Error) { +func Rel(basepath, targpath string) (string, error) { baseVol := VolumeName(basepath) targVol := VolumeName(targpath) base := Clean(basepath) @@ -280,7 +281,7 @@ func Rel(basepath, targpath string) (string, os.Error) { baseSlashed := len(base) > 0 && base[0] == Separator targSlashed := len(targ) > 0 && targ[0] == Separator if baseSlashed != targSlashed || baseVol != targVol { - return "", os.NewError("Rel: can't make " + targ + " relative to " + base) + return "", errors.New("Rel: can't make " + targ + " relative to " + base) } // Position base[b0:bi] and targ[t0:ti] at the first differing elements. bl := len(base) @@ -306,7 +307,7 @@ func Rel(basepath, targpath string) (string, os.Error) { t0 = ti } if base[b0:bi] == ".." { - return "", os.NewError("Rel: can't make " + targ + " relative to " + base) + return "", errors.New("Rel: can't make " + targ + " relative to " + base) } if b0 != bl { // Base elements left. Must go up before going down. @@ -330,7 +331,7 @@ func Rel(basepath, targpath string) (string, os.Error) { // SkipDir is used as a return value from WalkFuncs to indicate that // the directory named in the call is to be skipped. It is not returned // as an error by any function. -var SkipDir = os.NewError("skip this directory") +var SkipDir = errors.New("skip this directory") // WalkFunc is the type of the function called for each file or directory // visited by Walk. If there was a problem walking to the file or directory @@ -340,10 +341,10 @@ var SkipDir = os.NewError("skip this directory") // sole exception is that if path is a directory and the function returns the // special value SkipDir, the contents of the directory are skipped // and processing continues as usual on the next file. -type WalkFunc func(path string, info *os.FileInfo, err os.Error) os.Error +type WalkFunc func(path string, info *os.FileInfo, err error) error // walk recursively descends path, calling w. -func walk(path string, info *os.FileInfo, walkFn WalkFunc) os.Error { +func walk(path string, info *os.FileInfo, walkFn WalkFunc) error { err := walkFn(path, info, nil) if err != nil { if info.IsDirectory() && err == SkipDir { @@ -374,7 +375,7 @@ func walk(path string, info *os.FileInfo, walkFn WalkFunc) os.Error { // and directories are filtered by walkFn. The files are walked in lexical // order, which makes the output deterministic but means that for very // large directories Walk can be inefficient. -func Walk(root string, walkFn WalkFunc) os.Error { +func Walk(root string, walkFn WalkFunc) error { info, err := os.Lstat(root) if err != nil { return walkFn(root, nil, err) @@ -385,7 +386,7 @@ func Walk(root string, walkFn WalkFunc) os.Error { // readDir reads the directory named by dirname and returns // a sorted list of directory entries. // Copied from io/ioutil to avoid the circular import. -func readDir(dirname string) ([]*os.FileInfo, os.Error) { +func readDir(dirname string) ([]*os.FileInfo, error) { f, err := os.Open(dirname) if err != nil { return nil, err diff --git a/src/pkg/path/filepath/path_test.go b/src/pkg/path/filepath/path_test.go index 9234c0df6c..bc5e85a6e0 100644 --- a/src/pkg/path/filepath/path_test.go +++ b/src/pkg/path/filepath/path_test.go @@ -318,7 +318,7 @@ func checkMarks(t *testing.T, report bool) { // Assumes that each node name is unique. Good enough for a test. // If clear is true, any incoming error is cleared before return. The errors // are always accumulated, though. -func mark(path string, info *os.FileInfo, err os.Error, errors *[]os.Error, clear bool) os.Error { +func mark(path string, info *os.FileInfo, err error, errors *[]error, clear bool) error { if err != nil { *errors = append(*errors, err) if clear { @@ -336,9 +336,9 @@ func mark(path string, info *os.FileInfo, err os.Error, errors *[]os.Error, clea func TestWalk(t *testing.T) { makeTree(t) - errors := make([]os.Error, 0, 10) + errors := make([]error, 0, 10) clear := true - markFn := func(path string, info *os.FileInfo, err os.Error) os.Error { + markFn := func(path string, info *os.FileInfo, err error) error { return mark(path, info, err, &errors, clear) } // Expect no errors. @@ -523,7 +523,7 @@ func testEvalSymlinks(t *testing.T, tests []EvalSymlinksTest) { func TestEvalSymlinks(t *testing.T) { defer os.RemoveAll("test") for _, d := range EvalSymlinksTestDirs { - var err os.Error + var err error if d.dest == "" { err = os.Mkdir(d.path, 0755) } else { @@ -582,7 +582,7 @@ var abstests = []string{ func TestAbs(t *testing.T) { oldwd, err := os.Getwd() if err != nil { - t.Fatal("Getwd failed: " + err.String()) + t.Fatal("Getwd failed: " + err.Error()) } defer os.Chdir(oldwd) goroot := os.Getenv("GOROOT") diff --git a/src/pkg/path/match.go b/src/pkg/path/match.go index e9d032799f..bc685f48fb 100644 --- a/src/pkg/path/match.go +++ b/src/pkg/path/match.go @@ -5,12 +5,12 @@ package path import ( - "os" + "errors" "strings" "utf8" ) -var ErrBadPattern = os.NewError("syntax error in pattern") +var ErrBadPattern = errors.New("syntax error in pattern") // Match returns true if name matches the shell file name pattern. // The pattern syntax is: @@ -33,7 +33,7 @@ var ErrBadPattern = os.NewError("syntax error in pattern") // Match requires pattern to match all of name, not just a substring. // The only possible error return is when pattern is malformed. // -func Match(pattern, name string) (matched bool, err os.Error) { +func Match(pattern, name string) (matched bool, err error) { Pattern: for len(pattern) > 0 { var star bool @@ -111,7 +111,7 @@ Scan: // matchChunk checks whether chunk matches the beginning of s. // If so, it returns the remainder of s (after the match). // Chunk is all single-character operators: literals, char classes, and ?. -func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) { +func matchChunk(chunk, s string) (rest string, ok bool, err error) { for len(chunk) > 0 { if len(s) == 0 { return @@ -183,7 +183,7 @@ func matchChunk(chunk, s string) (rest string, ok bool, err os.Error) { } // getEsc gets a possibly-escaped character from chunk, for a character class. -func getEsc(chunk string) (r rune, nchunk string, err os.Error) { +func getEsc(chunk string) (r rune, nchunk string, err error) { if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' { err = ErrBadPattern return diff --git a/src/pkg/path/match_test.go b/src/pkg/path/match_test.go index f377f1083b..730b6b9039 100644 --- a/src/pkg/path/match_test.go +++ b/src/pkg/path/match_test.go @@ -4,15 +4,12 @@ package path -import ( - "os" - "testing" -) +import "testing" type MatchTest struct { pattern, s string match bool - err os.Error + err error } var matchTests = []MatchTest{ diff --git a/src/pkg/rand/rand_test.go b/src/pkg/rand/rand_test.go index f997ff56c7..66ffa58cd5 100644 --- a/src/pkg/rand/rand_test.go +++ b/src/pkg/rand/rand_test.go @@ -5,9 +5,9 @@ package rand import ( + "errors" "math" "fmt" - "os" "testing" ) @@ -41,16 +41,16 @@ var testSeeds = []int64{1, 1754801282, 1698661970, 1550503961} // checkSimilarDistribution returns success if the mean and stddev of the // two statsResults are similar. -func (this *statsResults) checkSimilarDistribution(expected *statsResults) os.Error { +func (this *statsResults) checkSimilarDistribution(expected *statsResults) error { if !nearEqual(this.mean, expected.mean, expected.closeEnough, expected.maxError) { s := fmt.Sprintf("mean %v != %v (allowed error %v, %v)", this.mean, expected.mean, expected.closeEnough, expected.maxError) fmt.Println(s) - return os.NewError(s) + return errors.New(s) } if !nearEqual(this.stddev, expected.stddev, 0, expected.maxError) { s := fmt.Sprintf("stddev %v != %v (allowed error %v, %v)", this.stddev, expected.stddev, expected.closeEnough, expected.maxError) fmt.Println(s) - return os.NewError(s) + return errors.New(s) } return nil } @@ -74,7 +74,7 @@ func checkSampleDistribution(t *testing.T, samples []float64, expected *statsRes actual := getStatsResults(samples) err := actual.checkSimilarDistribution(expected) if err != nil { - t.Errorf(err.String()) + t.Errorf(err.Error()) } } diff --git a/src/pkg/reflect/all_test.go b/src/pkg/reflect/all_test.go index 136b6e7411..271a651147 100644 --- a/src/pkg/reflect/all_test.go +++ b/src/pkg/reflect/all_test.go @@ -631,7 +631,7 @@ var deepEqualTests = []DeepEqualTest{ {make([]int, 10), make([]int, 10), true}, {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true}, {Basic{1, 0.5}, Basic{1, 0.5}, true}, - {os.Error(nil), os.Error(nil), true}, + {error(nil), error(nil), true}, {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true}, // Inequalities diff --git a/src/pkg/reflect/value.go b/src/pkg/reflect/value.go index 9ddbee0e2e..a9a7e0901f 100644 --- a/src/pkg/reflect/value.go +++ b/src/pkg/reflect/value.go @@ -71,7 +71,7 @@ type ValueError struct { Kind Kind } -func (e *ValueError) String() string { +func (e *ValueError) Error() string { if e.Kind == 0 { return "reflect: call of " + e.Method + " on zero Value" } diff --git a/src/pkg/regexp/all_test.go b/src/pkg/regexp/all_test.go index 77f32ca1a5..c707b119bd 100644 --- a/src/pkg/regexp/all_test.go +++ b/src/pkg/regexp/all_test.go @@ -5,7 +5,6 @@ package regexp import ( - "os" "strings" "testing" ) @@ -53,10 +52,10 @@ var bad_re = []stringError{ } */ -func compileTest(t *testing.T, expr string, error os.Error) *Regexp { +func compileTest(t *testing.T, expr string, error error) *Regexp { re, err := Compile(expr) if err != error { - t.Error("compiling `", expr, "`; unexpected error: ", err.String()) + t.Error("compiling `", expr, "`; unexpected error: ", err.Error()) } return re } diff --git a/src/pkg/regexp/exec_test.go b/src/pkg/regexp/exec_test.go index 905fd4ef12..499d1a529f 100644 --- a/src/pkg/regexp/exec_test.go +++ b/src/pkg/regexp/exec_test.go @@ -104,7 +104,7 @@ func testRE2(t *testing.T, file string) { for { line, err := r.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } t.Fatalf("%s:%d: %v", file, lineno, err) @@ -141,7 +141,7 @@ func testRE2(t *testing.T, file string) { } re, err = tryCompile(q) if err != nil { - if err.String() == "error parsing regexp: invalid escape sequence: `\\C`" { + if err.Error() == "error parsing regexp: invalid escape sequence: `\\C`" { // We don't and likely never will support \C; keep going. continue } @@ -275,7 +275,7 @@ func isSingleBytes(s string) bool { return true } -func tryCompile(s string) (re *Regexp, err os.Error) { +func tryCompile(s string) (re *Regexp, err error) { // Protect against panic during Compile. defer func() { if r := recover(); r != nil { @@ -370,7 +370,7 @@ Reading: lineno++ line, err := b.ReadString('\n') if err != nil { - if err != os.EOF { + if err != io.EOF { t.Errorf("%s:%d: %v", file, lineno, err) } break Reading @@ -629,7 +629,7 @@ func parseFowlerResult(s string) (ok, compiled, matched bool, pos []int) { return } var v = -1 - var err os.Error + var err error if s[:i] != "?" { v, err = strconv.Atoi(s[:i]) if err != nil { diff --git a/src/pkg/regexp/regexp.go b/src/pkg/regexp/regexp.go index a1b7951bfe..9e9fb856dc 100644 --- a/src/pkg/regexp/regexp.go +++ b/src/pkg/regexp/regexp.go @@ -56,7 +56,6 @@ package regexp import ( "bytes" "io" - "os" "regexp/syntax" "strconv" "strings" @@ -69,7 +68,7 @@ var debug = false // Error is the local type for a parsing error. type Error string -func (e Error) String() string { +func (e Error) Error() string { return string(e) } @@ -108,7 +107,7 @@ func (re *Regexp) String() string { // that Perl, Python, and other implementations use, although this // package implements it without the expense of backtracking. // For POSIX leftmost-longest matching, see CompilePOSIX. -func Compile(expr string) (*Regexp, os.Error) { +func Compile(expr string) (*Regexp, error) { return compile(expr, syntax.Perl, false) } @@ -131,11 +130,11 @@ func Compile(expr string) (*Regexp, os.Error) { // subexpression, then the second, and so on from left to right. // The POSIX rule is computationally prohibitive and not even well-defined. // See http://swtch.com/~rsc/regexp/regexp2.html#posix for details. -func CompilePOSIX(expr string) (*Regexp, os.Error) { +func CompilePOSIX(expr string) (*Regexp, error) { return compile(expr, syntax.POSIX, true) } -func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, os.Error) { +func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, error) { re, err := syntax.Parse(expr, mode) if err != nil { return nil, err @@ -196,7 +195,7 @@ func (re *Regexp) put(z *machine) { func MustCompile(str string) *Regexp { regexp, error := Compile(str) if error != nil { - panic(`regexp: Compile(` + quote(str) + `): ` + error.String()) + panic(`regexp: Compile(` + quote(str) + `): ` + error.Error()) } return regexp } @@ -207,7 +206,7 @@ func MustCompile(str string) *Regexp { func MustCompilePOSIX(str string) *Regexp { regexp, error := CompilePOSIX(str) if error != nil { - panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.String()) + panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.Error()) } return regexp } @@ -392,7 +391,7 @@ func (re *Regexp) Match(b []byte) bool { // MatchReader checks whether a textual regular expression matches the text // read by the RuneReader. More complicated queries need to use Compile and // the full Regexp interface. -func MatchReader(pattern string, r io.RuneReader) (matched bool, error os.Error) { +func MatchReader(pattern string, r io.RuneReader) (matched bool, error error) { re, err := Compile(pattern) if err != nil { return false, err @@ -403,7 +402,7 @@ func MatchReader(pattern string, r io.RuneReader) (matched bool, error os.Error) // MatchString checks whether a textual regular expression // matches a string. More complicated queries need // to use Compile and the full Regexp interface. -func MatchString(pattern string, s string) (matched bool, error os.Error) { +func MatchString(pattern string, s string) (matched bool, error error) { re, err := Compile(pattern) if err != nil { return false, err @@ -414,7 +413,7 @@ func MatchString(pattern string, s string) (matched bool, error os.Error) { // Match checks whether a textual regular expression // matches a byte slice. More complicated queries need // to use Compile and the full Regexp interface. -func Match(pattern string, b []byte) (matched bool, error os.Error) { +func Match(pattern string, b []byte) (matched bool, error error) { re, err := Compile(pattern) if err != nil { return false, err diff --git a/src/pkg/regexp/syntax/compile.go b/src/pkg/regexp/syntax/compile.go index c90de3fe99..21c6565b99 100644 --- a/src/pkg/regexp/syntax/compile.go +++ b/src/pkg/regexp/syntax/compile.go @@ -1,9 +1,6 @@ package syntax -import ( - "os" - "unicode" -) +import "unicode" // A patchList is a list of instruction pointers that need to be filled in (patched). // Because the pointers haven't been filled in yet, we can reuse their storage @@ -76,7 +73,7 @@ type compiler struct { // Compile compiles the regexp into a program to be executed. // The regexp should have been simplified already (returned from re.Simplify). -func Compile(re *Regexp) (*Prog, os.Error) { +func Compile(re *Regexp) (*Prog, error) { var c compiler c.init() f := c.compile(re) diff --git a/src/pkg/regexp/syntax/parse.go b/src/pkg/regexp/syntax/parse.go index f5602628e7..29ad4d2f89 100644 --- a/src/pkg/regexp/syntax/parse.go +++ b/src/pkg/regexp/syntax/parse.go @@ -5,7 +5,6 @@ package syntax import ( - "os" "sort" "strings" "unicode" @@ -19,7 +18,7 @@ type Error struct { Expr string } -func (e *Error) String() string { +func (e *Error) Error() string { return "error parsing regexp: " + e.Code.String() + ": `" + e.Expr + "`" } @@ -222,7 +221,7 @@ func (p *parser) op(op Op) *Regexp { // before is the regexp suffix starting at the repetition operator. // after is the regexp suffix following after the repetition operator. // repeat returns an updated 'after' and an error, if any. -func (p *parser) repeat(op Op, min, max int, before, after, lastRepeat string) (string, os.Error) { +func (p *parser) repeat(op Op, min, max int, before, after, lastRepeat string) (string, error) { flags := p.flags if p.flags&PerlX != 0 { if len(after) > 0 && after[0] == '?' { @@ -649,7 +648,7 @@ func literalRegexp(s string, flags Flags) *Regexp { // Parsing. -func Parse(s string, flags Flags) (*Regexp, os.Error) { +func Parse(s string, flags Flags) (*Regexp, error) { if flags&Literal != 0 { // Trivial parser for literal string. if err := checkUTF8(s); err != nil { @@ -661,7 +660,7 @@ func Parse(s string, flags Flags) (*Regexp, os.Error) { // Otherwise, must do real work. var ( p parser - err os.Error + err error c rune op Op lastRepeat string @@ -889,7 +888,7 @@ func (p *parser) parseRepeat(s string) (min, max int, rest string, ok bool) { // parsePerlFlags parses a Perl flag setting or non-capturing group or both, // like (?i) or (?: or (?i:. It removes the prefix from s and updates the parse state. // The caller must have ensured that s begins with "(?". -func (p *parser) parsePerlFlags(s string) (rest string, err os.Error) { +func (p *parser) parsePerlFlags(s string) (rest string, err error) { t := s // Check for named captures, first introduced in Python's regexp library. @@ -1069,7 +1068,7 @@ func matchRune(re *Regexp, r rune) bool { } // parseVerticalBar handles a | in the input. -func (p *parser) parseVerticalBar() os.Error { +func (p *parser) parseVerticalBar() error { p.concat() // The concatenation we just parsed is on top of the stack. @@ -1152,7 +1151,7 @@ func (p *parser) swapVerticalBar() bool { } // parseRightParen handles a ) in the input. -func (p *parser) parseRightParen() os.Error { +func (p *parser) parseRightParen() error { p.concat() if p.swapVerticalBar() { // pop vertical bar @@ -1186,7 +1185,7 @@ func (p *parser) parseRightParen() os.Error { // parseEscape parses an escape sequence at the beginning of s // and returns the rune. -func (p *parser) parseEscape(s string) (r rune, rest string, err os.Error) { +func (p *parser) parseEscape(s string) (r rune, rest string, err error) { t := s[1:] if t == "" { return 0, "", &Error{ErrTrailingBackslash, ""} @@ -1302,7 +1301,7 @@ Switch: // parseClassChar parses a character class character at the beginning of s // and returns it. -func (p *parser) parseClassChar(s, wholeClass string) (r rune, rest string, err os.Error) { +func (p *parser) parseClassChar(s, wholeClass string) (r rune, rest string, err error) { if s == "" { return 0, "", &Error{Code: ErrMissingBracket, Expr: wholeClass} } @@ -1338,7 +1337,7 @@ func (p *parser) parsePerlClassEscape(s string, r []rune) (out []rune, rest stri // parseNamedClass parses a leading POSIX named character class like [:alnum:] // from the beginning of s. If one is present, it appends the characters to r // and returns the new slice r and the remainder of the string. -func (p *parser) parseNamedClass(s string, r []rune) (out []rune, rest string, err os.Error) { +func (p *parser) parseNamedClass(s string, r []rune) (out []rune, rest string, err error) { if len(s) < 2 || s[0] != '[' || s[1] != ':' { return } @@ -1401,7 +1400,7 @@ func unicodeTable(name string) (*unicode.RangeTable, *unicode.RangeTable) { // parseUnicodeClass parses a leading Unicode character class like \p{Han} // from the beginning of s. If one is present, it appends the characters to r // and returns the new slice r and the remainder of the string. -func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, err os.Error) { +func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, err error) { if p.flags&UnicodeGroups == 0 || len(s) < 2 || s[0] != '\\' || s[1] != 'p' && s[1] != 'P' { return } @@ -1474,7 +1473,7 @@ func (p *parser) parseUnicodeClass(s string, r []rune) (out []rune, rest string, // parseClass parses a character class at the beginning of s // and pushes it onto the parse stack. -func (p *parser) parseClass(s string) (rest string, err os.Error) { +func (p *parser) parseClass(s string) (rest string, err error) { t := s[1:] // chop [ re := p.newRegexp(OpCharClass) re.Flags = p.flags @@ -1824,7 +1823,7 @@ func (ra ranges) Swap(i, j int) { p[i], p[i+1], p[j], p[j+1] = p[j], p[j+1], p[i], p[i+1] } -func checkUTF8(s string) os.Error { +func checkUTF8(s string) error { for s != "" { rune, size := utf8.DecodeRuneInString(s) if rune == utf8.RuneError && size == 1 { @@ -1835,7 +1834,7 @@ func checkUTF8(s string) os.Error { return nil } -func nextRune(s string) (c rune, t string, err os.Error) { +func nextRune(s string) (c rune, t string, err error) { c, size := utf8.DecodeRuneInString(s) if c == utf8.RuneError && size == 1 { return 0, "", &Error{Code: ErrInvalidUTF8, Expr: s} diff --git a/src/pkg/rpc/client.go b/src/pkg/rpc/client.go index 3dc6df1c4b..ecc84decf2 100644 --- a/src/pkg/rpc/client.go +++ b/src/pkg/rpc/client.go @@ -6,12 +6,12 @@ package rpc import ( "bufio" + "errors" "gob" "http" "io" "log" "net" - "os" "sync" ) @@ -19,18 +19,18 @@ import ( // the remote side of the RPC connection. type ServerError string -func (e ServerError) String() string { +func (e ServerError) Error() string { return string(e) } -var ErrShutdown = os.NewError("connection is shut down") +var ErrShutdown = errors.New("connection is shut down") // Call represents an active RPC. type Call struct { ServiceMethod string // The name of the service and method to call. Args interface{} // The argument to the function (*struct). Reply interface{} // The reply from the function (*struct). - Error os.Error // After completion, the error status. + Error error // After completion, the error status. Done chan *Call // Strobes when call is complete; value is the error status. seq uint64 } @@ -58,11 +58,11 @@ type Client struct { // argument to force the body of the response to be read and then // discarded. type ClientCodec interface { - WriteRequest(*Request, interface{}) os.Error - ReadResponseHeader(*Response) os.Error - ReadResponseBody(interface{}) os.Error + WriteRequest(*Request, interface{}) error + ReadResponseHeader(*Response) error + ReadResponseBody(interface{}) error - Close() os.Error + Close() error } func (client *Client) send(c *Call) { @@ -91,13 +91,13 @@ func (client *Client) send(c *Call) { } func (client *Client) input() { - var err os.Error + var err error var response Response for err == nil { response = Response{} err = client.codec.ReadResponseHeader(&response) if err != nil { - if err == os.EOF && !client.closing { + if err == io.EOF && !client.closing { err = io.ErrUnexpectedEOF } break @@ -111,7 +111,7 @@ func (client *Client) input() { if response.Error == "" { err = client.codec.ReadResponseBody(c.Reply) if err != nil { - c.Error = os.NewError("reading body " + err.String()) + c.Error = errors.New("reading body " + err.Error()) } } else { // We've got an error response. Give this to the request; @@ -120,7 +120,7 @@ func (client *Client) input() { c.Error = ServerError(response.Error) err = client.codec.ReadResponseBody(nil) if err != nil { - err = os.NewError("reading error body: " + err.String()) + err = errors.New("reading error body: " + err.Error()) } } c.done() @@ -133,7 +133,7 @@ func (client *Client) input() { call.done() } client.mutex.Unlock() - if err != os.EOF || !client.closing { + if err != io.EOF || !client.closing { log.Println("rpc: client protocol error:", err) } } @@ -176,7 +176,7 @@ type gobClientCodec struct { encBuf *bufio.Writer } -func (c *gobClientCodec) WriteRequest(r *Request, body interface{}) (err os.Error) { +func (c *gobClientCodec) WriteRequest(r *Request, body interface{}) (err error) { if err = c.enc.Encode(r); err != nil { return } @@ -186,28 +186,28 @@ func (c *gobClientCodec) WriteRequest(r *Request, body interface{}) (err os.Erro return c.encBuf.Flush() } -func (c *gobClientCodec) ReadResponseHeader(r *Response) os.Error { +func (c *gobClientCodec) ReadResponseHeader(r *Response) error { return c.dec.Decode(r) } -func (c *gobClientCodec) ReadResponseBody(body interface{}) os.Error { +func (c *gobClientCodec) ReadResponseBody(body interface{}) error { return c.dec.Decode(body) } -func (c *gobClientCodec) Close() os.Error { +func (c *gobClientCodec) Close() error { return c.rwc.Close() } // DialHTTP connects to an HTTP RPC server at the specified network address // listening on the default HTTP RPC path. -func DialHTTP(network, address string) (*Client, os.Error) { +func DialHTTP(network, address string) (*Client, error) { return DialHTTPPath(network, address, DefaultRPCPath) } // DialHTTPPath connects to an HTTP RPC server // at the specified network address and path. -func DialHTTPPath(network, address, path string) (*Client, os.Error) { - var err os.Error +func DialHTTPPath(network, address, path string) (*Client, error) { + var err error conn, err := net.Dial(network, address) if err != nil { return nil, err @@ -221,14 +221,14 @@ func DialHTTPPath(network, address, path string) (*Client, os.Error) { return NewClient(conn), nil } if err == nil { - err = os.NewError("unexpected HTTP response: " + resp.Status) + err = errors.New("unexpected HTTP response: " + resp.Status) } conn.Close() return nil, &net.OpError{"dial-http", network + " " + address, nil, err} } // Dial connects to an RPC server at the specified network address. -func Dial(network, address string) (*Client, os.Error) { +func Dial(network, address string) (*Client, error) { conn, err := net.Dial(network, address) if err != nil { return nil, err @@ -236,7 +236,7 @@ func Dial(network, address string) (*Client, os.Error) { return NewClient(conn), nil } -func (client *Client) Close() os.Error { +func (client *Client) Close() error { client.mutex.Lock() if client.shutdown || client.closing { client.mutex.Unlock() @@ -278,7 +278,7 @@ func (client *Client) Go(serviceMethod string, args interface{}, reply interface } // Call invokes the named function, waits for it to complete, and returns its error status. -func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) os.Error { +func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error { if client.shutdown { return ErrShutdown } diff --git a/src/pkg/rpc/debug.go b/src/pkg/rpc/debug.go index 7e3e6f6e5b..f29ea8dba0 100644 --- a/src/pkg/rpc/debug.go +++ b/src/pkg/rpc/debug.go @@ -85,6 +85,6 @@ func (server debugHTTP) ServeHTTP(w http.ResponseWriter, req *http.Request) { sort.Sort(services) err := debug.Execute(w, services) if err != nil { - fmt.Fprintln(w, "rpc: error executing template:", err.String()) + fmt.Fprintln(w, "rpc: error executing template:", err.Error()) } } diff --git a/src/pkg/rpc/jsonrpc/all_test.go b/src/pkg/rpc/jsonrpc/all_test.go index 99253baf3c..1451a0fed8 100644 --- a/src/pkg/rpc/jsonrpc/all_test.go +++ b/src/pkg/rpc/jsonrpc/all_test.go @@ -5,11 +5,11 @@ package jsonrpc import ( + "errors" "fmt" "io" "json" "net" - "os" "rpc" "testing" ) @@ -24,25 +24,25 @@ type Reply struct { type Arith int -func (t *Arith) Add(args *Args, reply *Reply) os.Error { +func (t *Arith) Add(args *Args, reply *Reply) error { reply.C = args.A + args.B return nil } -func (t *Arith) Mul(args *Args, reply *Reply) os.Error { +func (t *Arith) Mul(args *Args, reply *Reply) error { reply.C = args.A * args.B return nil } -func (t *Arith) Div(args *Args, reply *Reply) os.Error { +func (t *Arith) Div(args *Args, reply *Reply) error { if args.B == 0 { - return os.NewError("divide by zero") + return errors.New("divide by zero") } reply.C = args.A / args.B return nil } -func (t *Arith) Error(args *Args, reply *Reply) os.Error { +func (t *Arith) Error(args *Args, reply *Reply) error { panic("ERROR") } @@ -105,7 +105,7 @@ func TestClient(t *testing.T) { reply := new(Reply) err := client.Call("Arith.Add", args, reply) if err != nil { - t.Errorf("Add: expected no error but got string %q", err.String()) + t.Errorf("Add: expected no error but got string %q", err.Error()) } if reply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B) @@ -115,7 +115,7 @@ func TestClient(t *testing.T) { reply = new(Reply) err = client.Call("Arith.Mul", args, reply) if err != nil { - t.Errorf("Mul: expected no error but got string %q", err.String()) + t.Errorf("Mul: expected no error but got string %q", err.Error()) } if reply.C != args.A*args.B { t.Errorf("Mul: expected %d got %d", reply.C, args.A*args.B) @@ -130,7 +130,7 @@ func TestClient(t *testing.T) { addCall = <-addCall.Done if addCall.Error != nil { - t.Errorf("Add: expected no error but got string %q", addCall.Error.String()) + t.Errorf("Add: expected no error but got string %q", addCall.Error.Error()) } if addReply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", addReply.C, args.A+args.B) @@ -138,7 +138,7 @@ func TestClient(t *testing.T) { mulCall = <-mulCall.Done if mulCall.Error != nil { - t.Errorf("Mul: expected no error but got string %q", mulCall.Error.String()) + t.Errorf("Mul: expected no error but got string %q", mulCall.Error.Error()) } if mulReply.C != args.A*args.B { t.Errorf("Mul: expected %d got %d", mulReply.C, args.A*args.B) @@ -151,7 +151,7 @@ func TestClient(t *testing.T) { // expect an error: zero divide if err == nil { t.Error("Div: expected error") - } else if err.String() != "divide by zero" { + } else if err.Error() != "divide by zero" { t.Error("Div: expected divide by zero error; got", err) } } @@ -164,8 +164,8 @@ func TestMalformedInput(t *testing.T) { func TestUnexpectedError(t *testing.T) { cli, srv := myPipe() - go cli.PipeWriter.CloseWithError(os.NewError("unexpected error!")) // reader will get this error - ServeConn(srv) // must return, not loop + go cli.PipeWriter.CloseWithError(errors.New("unexpected error!")) // reader will get this error + ServeConn(srv) // must return, not loop } // Copied from package net. @@ -191,7 +191,7 @@ func (pipeAddr) String() string { return "pipe" } -func (p *pipe) Close() os.Error { +func (p *pipe) Close() error { err := p.PipeReader.Close() err1 := p.PipeWriter.Close() if err == nil { @@ -208,14 +208,14 @@ func (p *pipe) RemoteAddr() net.Addr { return pipeAddr(0) } -func (p *pipe) SetTimeout(nsec int64) os.Error { - return os.NewError("net.Pipe does not support timeouts") +func (p *pipe) SetTimeout(nsec int64) error { + return errors.New("net.Pipe does not support timeouts") } -func (p *pipe) SetReadTimeout(nsec int64) os.Error { - return os.NewError("net.Pipe does not support timeouts") +func (p *pipe) SetReadTimeout(nsec int64) error { + return errors.New("net.Pipe does not support timeouts") } -func (p *pipe) SetWriteTimeout(nsec int64) os.Error { - return os.NewError("net.Pipe does not support timeouts") +func (p *pipe) SetWriteTimeout(nsec int64) error { + return errors.New("net.Pipe does not support timeouts") } diff --git a/src/pkg/rpc/jsonrpc/client.go b/src/pkg/rpc/jsonrpc/client.go index 17e9b9388a..f0475f060a 100644 --- a/src/pkg/rpc/jsonrpc/client.go +++ b/src/pkg/rpc/jsonrpc/client.go @@ -11,7 +11,6 @@ import ( "io" "json" "net" - "os" "rpc" "sync" ) @@ -49,7 +48,7 @@ type clientRequest struct { Id uint64 `json:"id"` } -func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) os.Error { +func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) error { c.mutex.Lock() c.pending[r.Seq] = r.ServiceMethod c.mutex.Unlock() @@ -71,7 +70,7 @@ func (r *clientResponse) reset() { r.Error = nil } -func (c *clientCodec) ReadResponseHeader(r *rpc.Response) os.Error { +func (c *clientCodec) ReadResponseHeader(r *rpc.Response) error { c.resp.reset() if err := c.dec.Decode(&c.resp); err != nil { return err @@ -97,14 +96,14 @@ func (c *clientCodec) ReadResponseHeader(r *rpc.Response) os.Error { return nil } -func (c *clientCodec) ReadResponseBody(x interface{}) os.Error { +func (c *clientCodec) ReadResponseBody(x interface{}) error { if x == nil { return nil } return json.Unmarshal(*c.resp.Result, x) } -func (c *clientCodec) Close() os.Error { +func (c *clientCodec) Close() error { return c.c.Close() } @@ -115,7 +114,7 @@ func NewClient(conn io.ReadWriteCloser) *rpc.Client { } // Dial connects to a JSON-RPC server at the specified network address. -func Dial(network, address string) (*rpc.Client, os.Error) { +func Dial(network, address string) (*rpc.Client, error) { conn, err := net.Dial(network, address) if err != nil { return nil, err diff --git a/src/pkg/rpc/jsonrpc/server.go b/src/pkg/rpc/jsonrpc/server.go index 61b5abff55..9fe3470c02 100644 --- a/src/pkg/rpc/jsonrpc/server.go +++ b/src/pkg/rpc/jsonrpc/server.go @@ -5,9 +5,9 @@ package jsonrpc import ( + "errors" "io" "json" - "os" "rpc" "sync" ) @@ -64,7 +64,7 @@ type serverResponse struct { Error interface{} `json:"error"` } -func (c *serverCodec) ReadRequestHeader(r *rpc.Request) os.Error { +func (c *serverCodec) ReadRequestHeader(r *rpc.Request) error { c.req.reset() if err := c.dec.Decode(&c.req); err != nil { return err @@ -84,7 +84,7 @@ func (c *serverCodec) ReadRequestHeader(r *rpc.Request) os.Error { return nil } -func (c *serverCodec) ReadRequestBody(x interface{}) os.Error { +func (c *serverCodec) ReadRequestBody(x interface{}) error { if x == nil { return nil } @@ -99,13 +99,13 @@ func (c *serverCodec) ReadRequestBody(x interface{}) os.Error { var null = json.RawMessage([]byte("null")) -func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) os.Error { +func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) error { var resp serverResponse c.mutex.Lock() b, ok := c.pending[r.Seq] if !ok { c.mutex.Unlock() - return os.NewError("invalid sequence number in response") + return errors.New("invalid sequence number in response") } delete(c.pending, r.Seq) c.mutex.Unlock() @@ -124,7 +124,7 @@ func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) os.Error { return c.enc.Encode(resp) } -func (c *serverCodec) Close() os.Error { +func (c *serverCodec) Close() error { return c.c.Close() } diff --git a/src/pkg/rpc/server.go b/src/pkg/rpc/server.go index 142bf8a529..39652b9f41 100644 --- a/src/pkg/rpc/server.go +++ b/src/pkg/rpc/server.go @@ -114,12 +114,12 @@ package rpc import ( "bufio" + "errors" "gob" "http" "log" "io" "net" - "os" "reflect" "strings" "sync" @@ -135,7 +135,7 @@ const ( // Precompute the reflect type for os.Error. Can't use os.Error directly // because Typeof takes an empty interface value. This is annoying. -var unusedError *os.Error +var unusedError *error var typeOfOsError = reflect.TypeOf(unusedError).Elem() type methodType struct { @@ -215,17 +215,17 @@ func isExportedOrBuiltinType(t reflect.Type) bool { // suitable methods. // The client accesses each method using a string of the form "Type.Method", // where Type is the receiver's concrete type. -func (server *Server) Register(rcvr interface{}) os.Error { +func (server *Server) Register(rcvr interface{}) error { return server.register(rcvr, "", false) } // RegisterName is like Register but uses the provided name for the type // instead of the receiver's concrete type. -func (server *Server) RegisterName(name string, rcvr interface{}) os.Error { +func (server *Server) RegisterName(name string, rcvr interface{}) error { return server.register(rcvr, name, true) } -func (server *Server) register(rcvr interface{}, name string, useName bool) os.Error { +func (server *Server) register(rcvr interface{}, name string, useName bool) error { server.mu.Lock() defer server.mu.Unlock() if server.serviceMap == nil { @@ -244,10 +244,10 @@ func (server *Server) register(rcvr interface{}, name string, useName bool) os.E if !isExported(sname) && !useName { s := "rpc Register: type " + sname + " is not exported" log.Print(s) - return os.NewError(s) + return errors.New(s) } if _, present := server.serviceMap[sname]; present { - return os.NewError("rpc: service already defined: " + sname) + return errors.New("rpc: service already defined: " + sname) } s.name = sname s.method = make(map[string]*methodType) @@ -296,7 +296,7 @@ func (server *Server) register(rcvr interface{}, name string, useName bool) os.E if len(s.method) == 0 { s := "rpc Register: type " + sname + " has no exported methods of suitable type" log.Print(s) - return os.NewError(s) + return errors.New(s) } server.serviceMap[s.name] = s return nil @@ -343,7 +343,7 @@ func (s *service) call(server *Server, sending *sync.Mutex, mtype *methodType, r errInter := returnValues[0].Interface() errmsg := "" if errInter != nil { - errmsg = errInter.(os.Error).String() + errmsg = errInter.(error).Error() } server.sendResponse(sending, req, replyv.Interface(), codec, errmsg) server.freeRequest(req) @@ -356,15 +356,15 @@ type gobServerCodec struct { encBuf *bufio.Writer } -func (c *gobServerCodec) ReadRequestHeader(r *Request) os.Error { +func (c *gobServerCodec) ReadRequestHeader(r *Request) error { return c.dec.Decode(r) } -func (c *gobServerCodec) ReadRequestBody(body interface{}) os.Error { +func (c *gobServerCodec) ReadRequestBody(body interface{}) error { return c.dec.Decode(body) } -func (c *gobServerCodec) WriteResponse(r *Response, body interface{}) (err os.Error) { +func (c *gobServerCodec) WriteResponse(r *Response, body interface{}) (err error) { if err = c.enc.Encode(r); err != nil { return } @@ -374,7 +374,7 @@ func (c *gobServerCodec) WriteResponse(r *Response, body interface{}) (err os.Er return c.encBuf.Flush() } -func (c *gobServerCodec) Close() os.Error { +func (c *gobServerCodec) Close() error { return c.rwc.Close() } @@ -396,7 +396,7 @@ func (server *Server) ServeCodec(codec ServerCodec) { for { service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec) if err != nil { - if err != os.EOF { + if err != io.EOF { log.Println("rpc:", err) } if !keepReading { @@ -404,7 +404,7 @@ func (server *Server) ServeCodec(codec ServerCodec) { } // send a response if we actually managed to read a header. if req != nil { - server.sendResponse(sending, req, invalidRequest, codec, err.String()) + server.sendResponse(sending, req, invalidRequest, codec, err.Error()) server.freeRequest(req) } continue @@ -416,7 +416,7 @@ func (server *Server) ServeCodec(codec ServerCodec) { // ServeRequest is like ServeCodec but synchronously serves a single request. // It does not close the codec upon completion. -func (server *Server) ServeRequest(codec ServerCodec) os.Error { +func (server *Server) ServeRequest(codec ServerCodec) error { sending := new(sync.Mutex) service, mtype, req, argv, replyv, keepReading, err := server.readRequest(codec) if err != nil { @@ -425,7 +425,7 @@ func (server *Server) ServeRequest(codec ServerCodec) os.Error { } // send a response if we actually managed to read a header. if req != nil { - server.sendResponse(sending, req, invalidRequest, codec, err.String()) + server.sendResponse(sending, req, invalidRequest, codec, err.Error()) server.freeRequest(req) } return err @@ -474,7 +474,7 @@ func (server *Server) freeResponse(resp *Response) { server.respLock.Unlock() } -func (server *Server) readRequest(codec ServerCodec) (service *service, mtype *methodType, req *Request, argv, replyv reflect.Value, keepReading bool, err os.Error) { +func (server *Server) readRequest(codec ServerCodec) (service *service, mtype *methodType, req *Request, argv, replyv reflect.Value, keepReading bool, err error) { service, mtype, req, keepReading, err = server.readRequestHeader(codec) if err != nil { if !keepReading { @@ -505,16 +505,16 @@ func (server *Server) readRequest(codec ServerCodec) (service *service, mtype *m return } -func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mtype *methodType, req *Request, keepReading bool, err os.Error) { +func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mtype *methodType, req *Request, keepReading bool, err error) { // Grab the request header. req = server.getRequest() err = codec.ReadRequestHeader(req) if err != nil { req = nil - if err == os.EOF || err == io.ErrUnexpectedEOF { + if err == io.EOF || err == io.ErrUnexpectedEOF { return } - err = os.NewError("rpc: server cannot decode request: " + err.String()) + err = errors.New("rpc: server cannot decode request: " + err.Error()) return } @@ -524,7 +524,7 @@ func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mt serviceMethod := strings.Split(req.ServiceMethod, ".") if len(serviceMethod) != 2 { - err = os.NewError("rpc: service/method request ill-formed: " + req.ServiceMethod) + err = errors.New("rpc: service/method request ill-formed: " + req.ServiceMethod) return } // Look up the request. @@ -532,12 +532,12 @@ func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mt service = server.serviceMap[serviceMethod[0]] server.mu.Unlock() if service == nil { - err = os.NewError("rpc: can't find service " + req.ServiceMethod) + err = errors.New("rpc: can't find service " + req.ServiceMethod) return } mtype = service.method[serviceMethod[1]] if mtype == nil { - err = os.NewError("rpc: can't find method " + req.ServiceMethod) + err = errors.New("rpc: can't find method " + req.ServiceMethod) } return } @@ -549,18 +549,18 @@ func (server *Server) Accept(lis net.Listener) { for { conn, err := lis.Accept() if err != nil { - log.Fatal("rpc.Serve: accept:", err.String()) // TODO(r): exit? + log.Fatal("rpc.Serve: accept:", err.Error()) // TODO(r): exit? } go server.ServeConn(conn) } } // Register publishes the receiver's methods in the DefaultServer. -func Register(rcvr interface{}) os.Error { return DefaultServer.Register(rcvr) } +func Register(rcvr interface{}) error { return DefaultServer.Register(rcvr) } // RegisterName is like Register but uses the provided name for the type // instead of the receiver's concrete type. -func RegisterName(name string, rcvr interface{}) os.Error { +func RegisterName(name string, rcvr interface{}) error { return DefaultServer.RegisterName(name, rcvr) } @@ -572,11 +572,11 @@ func RegisterName(name string, rcvr interface{}) os.Error { // connection. ReadRequestBody may be called with a nil // argument to force the body of the request to be read and discarded. type ServerCodec interface { - ReadRequestHeader(*Request) os.Error - ReadRequestBody(interface{}) os.Error - WriteResponse(*Response, interface{}) os.Error + ReadRequestHeader(*Request) error + ReadRequestBody(interface{}) error + WriteResponse(*Response, interface{}) error - Close() os.Error + Close() error } // ServeConn runs the DefaultServer on a single connection. @@ -596,7 +596,7 @@ func ServeCodec(codec ServerCodec) { // ServeRequest is like ServeCodec but synchronously serves a single request. // It does not close the codec upon completion. -func ServeRequest(codec ServerCodec) os.Error { +func ServeRequest(codec ServerCodec) error { return DefaultServer.ServeRequest(codec) } @@ -618,7 +618,7 @@ func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { } conn, _, err := w.(http.Hijacker).Hijack() if err != nil { - log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.String()) + log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error()) return } io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n") diff --git a/src/pkg/rpc/server_test.go b/src/pkg/rpc/server_test.go index 3e9fe297d4..119de7f89b 100644 --- a/src/pkg/rpc/server_test.go +++ b/src/pkg/rpc/server_test.go @@ -5,12 +5,12 @@ package rpc import ( + "errors" "fmt" "http/httptest" "io" "log" "net" - "os" "runtime" "strings" "sync" @@ -43,35 +43,35 @@ type Arith int // Some of Arith's methods have value args, some have pointer args. That's deliberate. -func (t *Arith) Add(args Args, reply *Reply) os.Error { +func (t *Arith) Add(args Args, reply *Reply) error { reply.C = args.A + args.B return nil } -func (t *Arith) Mul(args *Args, reply *Reply) os.Error { +func (t *Arith) Mul(args *Args, reply *Reply) error { reply.C = args.A * args.B return nil } -func (t *Arith) Div(args Args, reply *Reply) os.Error { +func (t *Arith) Div(args Args, reply *Reply) error { if args.B == 0 { - return os.NewError("divide by zero") + return errors.New("divide by zero") } reply.C = args.A / args.B return nil } -func (t *Arith) String(args *Args, reply *string) os.Error { +func (t *Arith) String(args *Args, reply *string) error { *reply = fmt.Sprintf("%d+%d=%d", args.A, args.B, args.A+args.B) return nil } -func (t *Arith) Scan(args string, reply *Reply) (err os.Error) { +func (t *Arith) Scan(args string, reply *Reply) (err error) { _, err = fmt.Sscan(args, &reply.C) return } -func (t *Arith) Error(args *Args, reply *Reply) os.Error { +func (t *Arith) Error(args *Args, reply *Reply) error { panic("ERROR") } @@ -132,7 +132,7 @@ func testRPC(t *testing.T, addr string) { reply := new(Reply) err = client.Call("Arith.Add", args, reply) if err != nil { - t.Errorf("Add: expected no error but got string %q", err.String()) + t.Errorf("Add: expected no error but got string %q", err.Error()) } if reply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B) @@ -145,7 +145,7 @@ func testRPC(t *testing.T, addr string) { // expect an error if err == nil { t.Error("BadOperation: expected error") - } else if !strings.HasPrefix(err.String(), "rpc: can't find method ") { + } else if !strings.HasPrefix(err.Error(), "rpc: can't find method ") { t.Errorf("BadOperation: expected can't find method error; got %q", err) } @@ -155,7 +155,7 @@ func testRPC(t *testing.T, addr string) { err = client.Call("Arith.Unknown", args, reply) if err == nil { t.Error("expected error calling unknown service") - } else if strings.Index(err.String(), "method") < 0 { + } else if strings.Index(err.Error(), "method") < 0 { t.Error("expected error about method; got", err) } @@ -168,7 +168,7 @@ func testRPC(t *testing.T, addr string) { addCall = <-addCall.Done if addCall.Error != nil { - t.Errorf("Add: expected no error but got string %q", addCall.Error.String()) + t.Errorf("Add: expected no error but got string %q", addCall.Error.Error()) } if addReply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", addReply.C, args.A+args.B) @@ -176,7 +176,7 @@ func testRPC(t *testing.T, addr string) { mulCall = <-mulCall.Done if mulCall.Error != nil { - t.Errorf("Mul: expected no error but got string %q", mulCall.Error.String()) + t.Errorf("Mul: expected no error but got string %q", mulCall.Error.Error()) } if mulReply.C != args.A*args.B { t.Errorf("Mul: expected %d got %d", mulReply.C, args.A*args.B) @@ -189,7 +189,7 @@ func testRPC(t *testing.T, addr string) { // expect an error: zero divide if err == nil { t.Error("Div: expected error") - } else if err.String() != "divide by zero" { + } else if err.Error() != "divide by zero" { t.Error("Div: expected divide by zero error; got", err) } @@ -198,7 +198,7 @@ func testRPC(t *testing.T, addr string) { err = client.Call("Arith.Add", reply, reply) // args, reply would be the correct thing to use if err == nil { t.Error("expected error calling Arith.Add with wrong arg type") - } else if strings.Index(err.String(), "type") < 0 { + } else if strings.Index(err.Error(), "type") < 0 { t.Error("expected error about type; got", err) } @@ -208,7 +208,7 @@ func testRPC(t *testing.T, addr string) { reply = new(Reply) err = client.Call("Arith.Scan", &str, reply) if err != nil { - t.Errorf("Scan: expected no error but got string %q", err.String()) + t.Errorf("Scan: expected no error but got string %q", err.Error()) } else if reply.C != Val { t.Errorf("Scan: expected %d got %d", Val, reply.C) } @@ -218,7 +218,7 @@ func testRPC(t *testing.T, addr string) { str = "" err = client.Call("Arith.String", args, &str) if err != nil { - t.Errorf("String: expected no error but got string %q", err.String()) + t.Errorf("String: expected no error but got string %q", err.Error()) } expect := fmt.Sprintf("%d+%d=%d", args.A, args.B, args.A+args.B) if str != expect { @@ -229,7 +229,7 @@ func testRPC(t *testing.T, addr string) { reply = new(Reply) err = client.Call("Arith.Mul", args, reply) if err != nil { - t.Errorf("Mul: expected no error but got string %q", err.String()) + t.Errorf("Mul: expected no error but got string %q", err.Error()) } if reply.C != args.A*args.B { t.Errorf("Mul: expected %d got %d", reply.C, args.A*args.B) @@ -245,7 +245,7 @@ func TestHTTP(t *testing.T) { func testHTTPRPC(t *testing.T, path string) { var client *Client - var err os.Error + var err error if path == "" { client, err = DialHTTP("tcp", httpServerAddr) } else { @@ -260,7 +260,7 @@ func testHTTPRPC(t *testing.T, path string) { reply := new(Reply) err = client.Call("Arith.Add", args, reply) if err != nil { - t.Errorf("Add: expected no error but got string %q", err.String()) + t.Errorf("Add: expected no error but got string %q", err.Error()) } if reply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B) @@ -274,15 +274,15 @@ type CodecEmulator struct { serviceMethod string args *Args reply *Reply - err os.Error + err error } -func (codec *CodecEmulator) Call(serviceMethod string, args *Args, reply *Reply) os.Error { +func (codec *CodecEmulator) Call(serviceMethod string, args *Args, reply *Reply) error { codec.serviceMethod = serviceMethod codec.args = args codec.reply = reply codec.err = nil - var serverError os.Error + var serverError error if codec.server == nil { serverError = ServeRequest(codec) } else { @@ -294,13 +294,13 @@ func (codec *CodecEmulator) Call(serviceMethod string, args *Args, reply *Reply) return codec.err } -func (codec *CodecEmulator) ReadRequestHeader(req *Request) os.Error { +func (codec *CodecEmulator) ReadRequestHeader(req *Request) error { req.ServiceMethod = codec.serviceMethod req.Seq = 0 return nil } -func (codec *CodecEmulator) ReadRequestBody(argv interface{}) os.Error { +func (codec *CodecEmulator) ReadRequestBody(argv interface{}) error { if codec.args == nil { return io.ErrUnexpectedEOF } @@ -308,16 +308,16 @@ func (codec *CodecEmulator) ReadRequestBody(argv interface{}) os.Error { return nil } -func (codec *CodecEmulator) WriteResponse(resp *Response, reply interface{}) os.Error { +func (codec *CodecEmulator) WriteResponse(resp *Response, reply interface{}) error { if resp.Error != "" { - codec.err = os.NewError(resp.Error) + codec.err = errors.New(resp.Error) } else { *codec.reply = *(reply.(*Reply)) } return nil } -func (codec *CodecEmulator) Close() os.Error { +func (codec *CodecEmulator) Close() error { return nil } @@ -335,7 +335,7 @@ func testServeRequest(t *testing.T, server *Server) { reply := new(Reply) err := client.Call("Arith.Add", args, reply) if err != nil { - t.Errorf("Add: expected no error but got string %q", err.String()) + t.Errorf("Add: expected no error but got string %q", err.Error()) } if reply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B) @@ -352,15 +352,15 @@ type ArgNotPublic int type ReplyNotPublic int type local struct{} -func (t *ReplyNotPointer) ReplyNotPointer(args *Args, reply Reply) os.Error { +func (t *ReplyNotPointer) ReplyNotPointer(args *Args, reply Reply) error { return nil } -func (t *ArgNotPublic) ArgNotPublic(args *local, reply *Reply) os.Error { +func (t *ArgNotPublic) ArgNotPublic(args *local, reply *Reply) error { return nil } -func (t *ReplyNotPublic) ReplyNotPublic(args *Args, reply *local) os.Error { +func (t *ReplyNotPublic) ReplyNotPublic(args *Args, reply *local) error { return nil } @@ -382,22 +382,22 @@ func TestRegistrationError(t *testing.T) { type WriteFailCodec int -func (WriteFailCodec) WriteRequest(*Request, interface{}) os.Error { +func (WriteFailCodec) WriteRequest(*Request, interface{}) error { // the panic caused by this error used to not unlock a lock. - return os.NewError("fail") + return errors.New("fail") } -func (WriteFailCodec) ReadResponseHeader(*Response) os.Error { +func (WriteFailCodec) ReadResponseHeader(*Response) error { time.Sleep(120e9) panic("unreachable") } -func (WriteFailCodec) ReadResponseBody(interface{}) os.Error { +func (WriteFailCodec) ReadResponseBody(interface{}) error { time.Sleep(120e9) panic("unreachable") } -func (WriteFailCodec) Close() os.Error { +func (WriteFailCodec) Close() error { return nil } @@ -427,15 +427,15 @@ func testSendDeadlock(client *Client) { client.Call("Arith.Add", args, reply) } -func dialDirect() (*Client, os.Error) { +func dialDirect() (*Client, error) { return Dial("tcp", serverAddr) } -func dialHTTP() (*Client, os.Error) { +func dialHTTP() (*Client, error) { return DialHTTP("tcp", httpServerAddr) } -func countMallocs(dial func() (*Client, os.Error), t *testing.T) uint64 { +func countMallocs(dial func() (*Client, error), t *testing.T) uint64 { once.Do(startServer) client, err := dial() if err != nil { @@ -449,7 +449,7 @@ func countMallocs(dial func() (*Client, os.Error), t *testing.T) uint64 { for i := 0; i < count; i++ { err := client.Call("Arith.Add", args, reply) if err != nil { - t.Errorf("Add: expected no error but got string %q", err.String()) + t.Errorf("Add: expected no error but got string %q", err.Error()) } if reply.C != args.A+args.B { t.Errorf("Add: expected %d got %d", reply.C, args.A+args.B) @@ -470,16 +470,16 @@ func TestCountMallocsOverHTTP(t *testing.T) { type writeCrasher struct{} -func (writeCrasher) Close() os.Error { +func (writeCrasher) Close() error { return nil } -func (writeCrasher) Read(p []byte) (int, os.Error) { - return 0, os.EOF +func (writeCrasher) Read(p []byte) (int, error) { + return 0, io.EOF } -func (writeCrasher) Write(p []byte) (int, os.Error) { - return 0, os.NewError("fake write failure") +func (writeCrasher) Write(p []byte) (int, error) { + return 0, errors.New("fake write failure") } func TestClientWriteError(t *testing.T) { @@ -489,12 +489,12 @@ func TestClientWriteError(t *testing.T) { if err == nil { t.Fatal("expected error") } - if err.String() != "fake write failure" { + if err.Error() != "fake write failure" { t.Error("unexpected value of error:", err) } } -func benchmarkEndToEnd(dial func() (*Client, os.Error), b *testing.B) { +func benchmarkEndToEnd(dial func() (*Client, error), b *testing.B) { b.StopTimer() once.Do(startServer) client, err := dial() @@ -517,7 +517,7 @@ func benchmarkEndToEnd(dial func() (*Client, os.Error), b *testing.B) { for atomic.AddInt32(&N, -1) >= 0 { err = client.Call("Arith.Add", args, reply) if err != nil { - fmt.Printf("Add: expected no error but got string %q", err.String()) + fmt.Printf("Add: expected no error but got string %q", err.Error()) panic("rpc error") } if reply.C != args.A+args.B { @@ -531,7 +531,7 @@ func benchmarkEndToEnd(dial func() (*Client, os.Error), b *testing.B) { wg.Wait() } -func benchmarkEndToEndAsync(dial func() (*Client, os.Error), b *testing.B) { +func benchmarkEndToEndAsync(dial func() (*Client, error), b *testing.B) { const MaxConcurrentCalls = 100 b.StopTimer() once.Do(startServer) diff --git a/src/pkg/runtime/pprof/pprof.go b/src/pkg/runtime/pprof/pprof.go index 7022896454..d14bb141c4 100644 --- a/src/pkg/runtime/pprof/pprof.go +++ b/src/pkg/runtime/pprof/pprof.go @@ -12,7 +12,6 @@ import ( "bufio" "fmt" "io" - "os" "runtime" "sync" ) @@ -23,7 +22,7 @@ import ( // WriteHeapProfile writes a pprof-formatted heap profile to w. // If a write to w returns an error, WriteHeapProfile returns that error. // Otherwise, WriteHeapProfile returns nil. -func WriteHeapProfile(w io.Writer) os.Error { +func WriteHeapProfile(w io.Writer) error { // Find out how many records there are (MemProfile(nil, false)), // allocate that many records, and get the data. // There's a race—more records might be added between @@ -119,7 +118,7 @@ var cpu struct { // StartCPUProfile enables CPU profiling for the current process. // While profiling, the profile will be buffered and written to w. // StartCPUProfile returns an error if profiling is already enabled. -func StartCPUProfile(w io.Writer) os.Error { +func StartCPUProfile(w io.Writer) error { // The runtime routines allow a variable profiling rate, // but in practice operating systems cannot trigger signals // at more than about 500 Hz, and our processing of the diff --git a/src/pkg/scanner/scanner.go b/src/pkg/scanner/scanner.go index 3594db997d..5ab37792d4 100644 --- a/src/pkg/scanner/scanner.go +++ b/src/pkg/scanner/scanner.go @@ -253,8 +253,8 @@ func (s *Scanner) next() rune { s.lastCharLen = 0 return EOF } - if err != os.EOF { - s.error(err.String()) + if err != io.EOF { + s.error(err.Error()) } // If err == EOF, we won't be getting more // bytes; break to avoid infinite loop. If diff --git a/src/pkg/scanner/scanner_test.go b/src/pkg/scanner/scanner_test.go index fb398831e1..b07e559e1a 100644 --- a/src/pkg/scanner/scanner_test.go +++ b/src/pkg/scanner/scanner_test.go @@ -7,7 +7,7 @@ package scanner import ( "bytes" "fmt" - "os" + "io" "strings" "testing" "utf8" @@ -19,13 +19,13 @@ type StringReader struct { step int } -func (r *StringReader) Read(p []byte) (n int, err os.Error) { +func (r *StringReader) Read(p []byte) (n int, err error) { if r.step < len(r.data) { s := r.data[r.step] n = copy(p, s) r.step++ } else { - err = os.EOF + err = io.EOF } return } diff --git a/src/pkg/smtp/auth.go b/src/pkg/smtp/auth.go index dd27f8e936..c4cdcb130d 100644 --- a/src/pkg/smtp/auth.go +++ b/src/pkg/smtp/auth.go @@ -4,9 +4,7 @@ package smtp -import ( - "os" -) +import "errors" // Auth is implemented by an SMTP authentication mechanism. type Auth interface { @@ -17,7 +15,7 @@ type Auth interface { // that the authentication should be skipped. // If it returns a non-nil os.Error, the SMTP client aborts // the authentication attempt and closes the connection. - Start(server *ServerInfo) (proto string, toServer []byte, err os.Error) + Start(server *ServerInfo) (proto string, toServer []byte, err error) // Next continues the authentication. The server has just sent // the fromServer data. If more is true, the server expects a @@ -25,7 +23,7 @@ type Auth interface { // Next should return toServer == nil. // If Next returns a non-nil os.Error, the SMTP client aborts // the authentication attempt and closes the connection. - Next(fromServer []byte, more bool) (toServer []byte, err os.Error) + Next(fromServer []byte, more bool) (toServer []byte, err error) } // ServerInfo records information about an SMTP server. @@ -49,21 +47,21 @@ func PlainAuth(identity, username, password, host string) Auth { return &plainAuth{identity, username, password, host} } -func (a *plainAuth) Start(server *ServerInfo) (string, []byte, os.Error) { +func (a *plainAuth) Start(server *ServerInfo) (string, []byte, error) { if !server.TLS { - return "", nil, os.NewError("unencrypted connection") + return "", nil, errors.New("unencrypted connection") } if server.Name != a.host { - return "", nil, os.NewError("wrong host name") + return "", nil, errors.New("wrong host name") } resp := []byte(a.identity + "\x00" + a.username + "\x00" + a.password) return "PLAIN", resp, nil } -func (a *plainAuth) Next(fromServer []byte, more bool) ([]byte, os.Error) { +func (a *plainAuth) Next(fromServer []byte, more bool) ([]byte, error) { if more { // We've already sent everything. - return nil, os.NewError("unexpected server challenge") + return nil, errors.New("unexpected server challenge") } return nil, nil } diff --git a/src/pkg/smtp/smtp.go b/src/pkg/smtp/smtp.go index 2d5e862471..8d935ffb7a 100644 --- a/src/pkg/smtp/smtp.go +++ b/src/pkg/smtp/smtp.go @@ -14,7 +14,6 @@ import ( "crypto/tls" "encoding/base64" "io" - "os" "net" "net/textproto" "strings" @@ -38,7 +37,7 @@ type Client struct { } // Dial returns a new Client connected to an SMTP server at addr. -func Dial(addr string) (*Client, os.Error) { +func Dial(addr string) (*Client, error) { conn, err := net.Dial("tcp", addr) if err != nil { return nil, err @@ -49,7 +48,7 @@ func Dial(addr string) (*Client, os.Error) { // NewClient returns a new Client using an existing connection and host as a // server name to be used when authenticating. -func NewClient(conn net.Conn, host string) (*Client, os.Error) { +func NewClient(conn net.Conn, host string) (*Client, error) { text := textproto.NewConn(conn) _, msg, err := text.ReadResponse(220) if err != nil { @@ -66,7 +65,7 @@ func NewClient(conn net.Conn, host string) (*Client, os.Error) { } // cmd is a convenience function that sends a command and returns the response -func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, os.Error) { +func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) { id, err := c.Text.Cmd(format, args...) if err != nil { return 0, "", err @@ -79,7 +78,7 @@ func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, s // helo sends the HELO greeting to the server. It should be used only when the // server does not support ehlo. -func (c *Client) helo() os.Error { +func (c *Client) helo() error { c.ext = nil _, _, err := c.cmd(250, "HELO localhost") return err @@ -87,7 +86,7 @@ func (c *Client) helo() os.Error { // ehlo sends the EHLO (extended hello) greeting to the server. It // should be the preferred greeting for servers that support it. -func (c *Client) ehlo() os.Error { +func (c *Client) ehlo() error { _, msg, err := c.cmd(250, "EHLO localhost") if err != nil { return err @@ -114,7 +113,7 @@ func (c *Client) ehlo() os.Error { // StartTLS sends the STARTTLS command and encrypts all further communication. // Only servers that advertise the STARTTLS extension support this function. -func (c *Client) StartTLS(config *tls.Config) os.Error { +func (c *Client) StartTLS(config *tls.Config) error { _, _, err := c.cmd(220, "STARTTLS") if err != nil { return err @@ -129,7 +128,7 @@ func (c *Client) StartTLS(config *tls.Config) os.Error { // If Verify returns nil, the address is valid. A non-nil return // does not necessarily indicate an invalid address. Many servers // will not verify addresses for security reasons. -func (c *Client) Verify(addr string) os.Error { +func (c *Client) Verify(addr string) error { _, _, err := c.cmd(250, "VRFY %s", addr) return err } @@ -137,7 +136,7 @@ func (c *Client) Verify(addr string) os.Error { // Auth authenticates a client using the provided authentication mechanism. // A failed authentication closes the connection. // Only servers that advertise the AUTH extension support this function. -func (c *Client) Auth(a Auth) os.Error { +func (c *Client) Auth(a Auth) error { encoding := base64.StdEncoding mech, resp, err := a.Start(&ServerInfo{c.serverName, c.tls, c.auth}) if err != nil { @@ -179,7 +178,7 @@ func (c *Client) Auth(a Auth) os.Error { // If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME // parameter. // This initiates a mail transaction and is followed by one or more Rcpt calls. -func (c *Client) Mail(from string) os.Error { +func (c *Client) Mail(from string) error { cmdStr := "MAIL FROM:<%s>" if c.ext != nil { if _, ok := c.ext["8BITMIME"]; ok { @@ -193,7 +192,7 @@ func (c *Client) Mail(from string) os.Error { // Rcpt issues a RCPT command to the server using the provided email address. // A call to Rcpt must be preceded by a call to Mail and may be followed by // a Data call or another Rcpt call. -func (c *Client) Rcpt(to string) os.Error { +func (c *Client) Rcpt(to string) error { _, _, err := c.cmd(25, "RCPT TO:<%s>", to) return err } @@ -203,7 +202,7 @@ type dataCloser struct { io.WriteCloser } -func (d *dataCloser) Close() os.Error { +func (d *dataCloser) Close() error { d.WriteCloser.Close() _, _, err := d.c.Text.ReadResponse(250) return err @@ -213,7 +212,7 @@ func (d *dataCloser) Close() os.Error { // can be used to write the data. The caller should close the writer // before calling any more methods on c. // A call to Data must be preceded by one or more calls to Rcpt. -func (c *Client) Data() (io.WriteCloser, os.Error) { +func (c *Client) Data() (io.WriteCloser, error) { _, _, err := c.cmd(354, "DATA") if err != nil { return nil, err @@ -224,7 +223,7 @@ func (c *Client) Data() (io.WriteCloser, os.Error) { // SendMail connects to the server at addr, switches to TLS if possible, // authenticates with mechanism a if possible, and then sends an email from // address from, to addresses to, with message msg. -func SendMail(addr string, a Auth, from string, to []string, msg []byte) os.Error { +func SendMail(addr string, a Auth, from string, to []string, msg []byte) error { c, err := Dial(addr) if err != nil { return err @@ -279,13 +278,13 @@ func (c *Client) Extension(ext string) (bool, string) { // Reset sends the RSET command to the server, aborting the current mail // transaction. -func (c *Client) Reset() os.Error { +func (c *Client) Reset() error { _, _, err := c.cmd(250, "RSET") return err } // Quit sends the QUIT command and closes the connection to the server. -func (c *Client) Quit() os.Error { +func (c *Client) Quit() error { _, _, err := c.cmd(221, "QUIT") if err != nil { return err diff --git a/src/pkg/smtp/smtp_test.go b/src/pkg/smtp/smtp_test.go index 553d3ae099..d4e9c38bf4 100644 --- a/src/pkg/smtp/smtp_test.go +++ b/src/pkg/smtp/smtp_test.go @@ -9,7 +9,6 @@ import ( "bytes" "io" "net/textproto" - "os" "strings" "testing" ) @@ -59,7 +58,7 @@ type faker struct { io.ReadWriter } -func (f faker) Close() os.Error { +func (f faker) Close() error { return nil } diff --git a/src/pkg/strconv/atob.go b/src/pkg/strconv/atob.go index 720819490c..e2d87bc0f2 100644 --- a/src/pkg/strconv/atob.go +++ b/src/pkg/strconv/atob.go @@ -4,12 +4,10 @@ package strconv -import "os" - // Atob returns the boolean value represented by the string. // It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. // Any other value returns an error. -func Atob(str string) (value bool, err os.Error) { +func Atob(str string) (value bool, err error) { switch str { case "1", "t", "T", "true", "TRUE", "True": return true, nil diff --git a/src/pkg/strconv/atob_test.go b/src/pkg/strconv/atob_test.go index d9db6c7c0a..2f31eb5e07 100644 --- a/src/pkg/strconv/atob_test.go +++ b/src/pkg/strconv/atob_test.go @@ -5,7 +5,6 @@ package strconv_test import ( - "os" . "strconv" "testing" ) @@ -13,7 +12,7 @@ import ( type atobTest struct { in string out bool - err os.Error + err error } var atobtests = []atobTest{ @@ -42,7 +41,7 @@ func TestAtob(t *testing.T) { t.Errorf("%s: expected %s but got nil", test.in, test.err) } else { // NumError assertion must succeed; it's the only thing we return. - if test.err != e.(*NumError).Error { + if test.err != e.(*NumError).Err { t.Errorf("%s: expected %s but got %s", test.in, test.err, e) } } diff --git a/src/pkg/strconv/atof.go b/src/pkg/strconv/atof.go index 4a4b1b43ce..06dae8564d 100644 --- a/src/pkg/strconv/atof.go +++ b/src/pkg/strconv/atof.go @@ -12,10 +12,7 @@ package strconv // 2) Multiply/divide decimal by powers of two until in range [0.5, 1) // 3) Multiply by 2^precision and round to get mantissa. -import ( - "math" - "os" -) +import "math" var optimize = true // can change for testing @@ -355,7 +352,7 @@ func (d *decimal) atof32() (f float32, ok bool) { // If s is syntactically well-formed but is more than 1/2 ULP // away from the largest floating point number of the given size, // Atof32 returns f = ±Inf, err.Error = ErrRange. -func Atof32(s string) (f float32, err os.Error) { +func Atof32(s string) (f float32, err error) { if val, ok := special(s); ok { return float32(val), nil } @@ -380,7 +377,7 @@ func Atof32(s string) (f float32, err os.Error) { // Atof64 converts the string s to a 64-bit floating-point number. // Except for the type of its result, its definition is the same as that // of Atof32. -func Atof64(s string) (f float64, err os.Error) { +func Atof64(s string) (f float64, err error) { if val, ok := special(s); ok { return val, nil } @@ -405,7 +402,7 @@ func Atof64(s string) (f float64, err os.Error) { // AtofN converts the string s to a 64-bit floating-point number, // but it rounds the result assuming that it will be stored in a value // of n bits (32 or 64). -func AtofN(s string, n int) (f float64, err os.Error) { +func AtofN(s string, n int) (f float64, err error) { if n == 32 { f1, err1 := Atof32(s) return float64(f1), err1 diff --git a/src/pkg/strconv/atof_test.go b/src/pkg/strconv/atof_test.go index 33f881c7fd..871bf0cd5e 100644 --- a/src/pkg/strconv/atof_test.go +++ b/src/pkg/strconv/atof_test.go @@ -5,7 +5,6 @@ package strconv_test import ( - "os" "reflect" . "strconv" "testing" @@ -14,7 +13,7 @@ import ( type atofTest struct { in string out string - err os.Error + err error } var atoftests = []atofTest{ diff --git a/src/pkg/strconv/atoi.go b/src/pkg/strconv/atoi.go index 92ba89daea..2c6c3d58de 100644 --- a/src/pkg/strconv/atoi.go +++ b/src/pkg/strconv/atoi.go @@ -4,21 +4,21 @@ package strconv -import "os" +import "errors" // ErrRange indicates that a value is out of range for the target type. -var ErrRange = os.NewError("value out of range") +var ErrRange = errors.New("value out of range") // ErrSyntax indicates that a value does not have the right syntax for the target type. -var ErrSyntax = os.NewError("invalid syntax") +var ErrSyntax = errors.New("invalid syntax") // A NumError records a failed conversion. type NumError struct { - Num string // the input - Error os.Error // the reason the conversion failed (ErrRange, ErrSyntax) + Num string // the input + Err error // the reason the conversion failed (ErrRange, ErrSyntax) } -func (e *NumError) String() string { return `parsing "` + e.Num + `": ` + e.Error.String() } +func (e *NumError) Error() string { return `parsing "` + e.Num + `": ` + e.Err.Error() } func computeIntsize() uint { siz := uint(8) @@ -47,7 +47,7 @@ func cutoff64(base int) uint64 { // and include err.Num = s. If s is empty or contains invalid // digits, err.Error = ErrSyntax; if the value corresponding // to s cannot be represented by a uint64, err.Error = ErrRange. -func Btoui64(s string, b int) (n uint64, err os.Error) { +func Btoui64(s string, b int) (n uint64, err error) { var cutoff uint64 s0 := s @@ -76,7 +76,7 @@ func Btoui64(s string, b int) (n uint64, err os.Error) { } default: - err = os.NewError("invalid base " + Itoa(b)) + err = errors.New("invalid base " + Itoa(b)) goto Error } @@ -133,13 +133,13 @@ Error: // // Atoui64 returns err.Error = ErrSyntax if s is empty or contains invalid digits. // It returns err.Error = ErrRange if s cannot be represented by a uint64. -func Atoui64(s string) (n uint64, err os.Error) { +func Atoui64(s string) (n uint64, err error) { return Btoui64(s, 10) } // Btoi64 is like Btoui64 but allows signed numbers and // returns its result in an int64. -func Btoi64(s string, base int) (i int64, err os.Error) { +func Btoi64(s string, base int) (i int64, err error) { // Empty string bad. if len(s) == 0 { return 0, &NumError{s, ErrSyntax} @@ -158,7 +158,7 @@ func Btoi64(s string, base int) (i int64, err os.Error) { // Convert unsigned and check range. var un uint64 un, err = Btoui64(s, base) - if err != nil && err.(*NumError).Error != ErrRange { + if err != nil && err.(*NumError).Err != ErrRange { err.(*NumError).Num = s0 return 0, err } @@ -177,12 +177,12 @@ func Btoi64(s string, base int) (i int64, err os.Error) { // Atoi64 is like Atoui64 but allows signed numbers and // returns its result in an int64. -func Atoi64(s string) (i int64, err os.Error) { return Btoi64(s, 10) } +func Atoi64(s string) (i int64, err error) { return Btoi64(s, 10) } // Atoui is like Atoui64 but returns its result as a uint. -func Atoui(s string) (i uint, err os.Error) { +func Atoui(s string) (i uint, err error) { i1, e1 := Atoui64(s) - if e1 != nil && e1.(*NumError).Error != ErrRange { + if e1 != nil && e1.(*NumError).Err != ErrRange { return 0, e1 } i = uint(i1) @@ -193,9 +193,9 @@ func Atoui(s string) (i uint, err os.Error) { } // Atoi is like Atoi64 but returns its result as an int. -func Atoi(s string) (i int, err os.Error) { +func Atoi(s string) (i int, err error) { i1, e1 := Atoi64(s) - if e1 != nil && e1.(*NumError).Error != ErrRange { + if e1 != nil && e1.(*NumError).Err != ErrRange { return 0, e1 } i = int(i1) diff --git a/src/pkg/strconv/atoi_test.go b/src/pkg/strconv/atoi_test.go index 0d2e38117a..9ee11b7102 100644 --- a/src/pkg/strconv/atoi_test.go +++ b/src/pkg/strconv/atoi_test.go @@ -5,7 +5,6 @@ package strconv_test import ( - "os" "reflect" . "strconv" "testing" @@ -14,7 +13,7 @@ import ( type atoui64Test struct { in string out uint64 - err os.Error + err error } var atoui64tests = []atoui64Test{ @@ -54,7 +53,7 @@ var btoui64tests = []atoui64Test{ type atoi64Test struct { in string out int64 - err os.Error + err error } var atoi64tests = []atoi64Test{ @@ -104,7 +103,7 @@ var btoi64tests = []atoi64Test{ type atoui32Test struct { in string out uint32 - err os.Error + err error } var atoui32tests = []atoui32Test{ @@ -122,7 +121,7 @@ var atoui32tests = []atoui32Test{ type atoi32Test struct { in string out int32 - err os.Error + err error } var atoi32tests = []atoi32Test{ diff --git a/src/pkg/strconv/fp_test.go b/src/pkg/strconv/fp_test.go index 991d3ac1e4..9785ca6916 100644 --- a/src/pkg/strconv/fp_test.go +++ b/src/pkg/strconv/fp_test.go @@ -7,6 +7,7 @@ package strconv_test import ( "bufio" "fmt" + "io" "os" "strconv" "strings" @@ -105,11 +106,11 @@ func TestFp(t *testing.T) { lineno := 0 for { line, err2 := b.ReadString('\n') - if err2 == os.EOF { + if err2 == io.EOF { break } if err2 != nil { - t.Fatal("testfp: read testfp.txt: " + err2.String()) + t.Fatal("testfp: read testfp.txt: " + err2.Error()) } line = line[0 : len(line)-1] lineno++ diff --git a/src/pkg/strconv/quote.go b/src/pkg/strconv/quote.go index 7efdcfedb2..24b19be383 100644 --- a/src/pkg/strconv/quote.go +++ b/src/pkg/strconv/quote.go @@ -6,7 +6,6 @@ package strconv import ( "bytes" - "os" "strings" "unicode" "utf8" @@ -157,7 +156,7 @@ func unhex(b byte) (v rune, ok bool) { // If set to a single quote, it permits the sequence \' and disallows unescaped '. // If set to a double quote, it permits \" and disallows unescaped ". // If set to zero, it does not permit either escape and allows both quote characters to appear unescaped. -func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err os.Error) { +func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error) { // easy cases switch c := s[0]; { case c == quote && (quote == '\'' || quote == '"'): @@ -268,7 +267,7 @@ func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, // that s quotes. (If s is single-quoted, it would be a Go // character literal; Unquote returns the corresponding // one-character string.) -func Unquote(s string) (t string, err os.Error) { +func Unquote(s string) (t string, err error) { n := len(s) if n < 2 { return "", ErrSyntax diff --git a/src/pkg/strings/reader.go b/src/pkg/strings/reader.go index f4385a437a..ac8d9dcdf8 100644 --- a/src/pkg/strings/reader.go +++ b/src/pkg/strings/reader.go @@ -5,7 +5,8 @@ package strings import ( - "os" + "errors" + "io" "utf8" ) @@ -23,9 +24,9 @@ func (r *Reader) Len() int { return len(r.s) - r.i } -func (r *Reader) Read(b []byte) (n int, err os.Error) { +func (r *Reader) Read(b []byte) (n int, err error) { if r.i >= len(r.s) { - return 0, os.EOF + return 0, io.EOF } n = copy(b, r.s[r.i:]) r.i += n @@ -33,9 +34,9 @@ func (r *Reader) Read(b []byte) (n int, err os.Error) { return } -func (r *Reader) ReadByte() (b byte, err os.Error) { +func (r *Reader) ReadByte() (b byte, err error) { if r.i >= len(r.s) { - return 0, os.EOF + return 0, io.EOF } b = r.s[r.i] r.i++ @@ -46,9 +47,9 @@ func (r *Reader) ReadByte() (b byte, err os.Error) { // UnreadByte moves the reading position back by one byte. // It is an error to call UnreadByte if nothing has been // read yet. -func (r *Reader) UnreadByte() os.Error { +func (r *Reader) UnreadByte() error { if r.i <= 0 { - return os.NewError("strings.Reader: at beginning of string") + return errors.New("strings.Reader: at beginning of string") } r.i-- r.prevRune = -1 @@ -60,9 +61,9 @@ func (r *Reader) UnreadByte() os.Error { // If no bytes are available, the error returned is os.EOF. // If the bytes are an erroneous UTF-8 encoding, it // consumes one byte and returns U+FFFD, 1. -func (r *Reader) ReadRune() (ch rune, size int, err os.Error) { +func (r *Reader) ReadRune() (ch rune, size int, err error) { if r.i >= len(r.s) { - return 0, 0, os.EOF + return 0, 0, io.EOF } r.prevRune = r.i if c := r.s[r.i]; c < utf8.RuneSelf { @@ -77,9 +78,9 @@ func (r *Reader) ReadRune() (ch rune, size int, err os.Error) { // UnreadRune causes the next call to ReadRune to return the same rune // as the previous call to ReadRune. // The last method called on r must have been ReadRune. -func (r *Reader) UnreadRune() os.Error { +func (r *Reader) UnreadRune() error { if r.prevRune < 0 { - return os.NewError("strings.Reader: previous operation was not ReadRune") + return errors.New("strings.Reader: previous operation was not ReadRune") } r.i = r.prevRune r.prevRune = -1 diff --git a/src/pkg/strings/replace.go b/src/pkg/strings/replace.go index 64a7f208b9..f53a96ee0f 100644 --- a/src/pkg/strings/replace.go +++ b/src/pkg/strings/replace.go @@ -4,10 +4,7 @@ package strings -import ( - "io" - "os" -) +import "io" // A Replacer replaces a list of strings with replacements. type Replacer struct { @@ -17,7 +14,7 @@ type Replacer struct { // replacer is the interface that a replacement algorithm needs to implement. type replacer interface { Replace(s string) string - WriteString(w io.Writer, s string) (n int, err os.Error) + WriteString(w io.Writer, s string) (n int, err error) } // byteBitmap represents bytes which are sought for replacement. @@ -85,7 +82,7 @@ func (r *Replacer) Replace(s string) string { } // WriteString writes s to w with all replacements performed. -func (r *Replacer) WriteString(w io.Writer, s string) (n int, err os.Error) { +func (r *Replacer) WriteString(w io.Writer, s string) (n int, err error) { return r.r.WriteString(w, s) } @@ -101,7 +98,7 @@ type appendSliceWriter struct { b []byte } -func (w *appendSliceWriter) Write(p []byte) (int, os.Error) { +func (w *appendSliceWriter) Write(p []byte) (int, error) { w.b = append(w.b, p...) return len(p), nil } @@ -114,7 +111,7 @@ func (r *genericReplacer) Replace(s string) string { return string(w.b) } -func (r *genericReplacer) WriteString(w io.Writer, s string) (n int, err os.Error) { +func (r *genericReplacer) WriteString(w io.Writer, s string) (n int, err error) { lastEmpty := false // the last replacement was of the empty string Input: // TODO(bradfitz): optimized version @@ -192,7 +189,7 @@ func (r *byteReplacer) Replace(s string) string { return string(buf) } -func (r *byteReplacer) WriteString(w io.Writer, s string) (n int, err os.Error) { +func (r *byteReplacer) WriteString(w io.Writer, s string) (n int, err error) { // TODO(bradfitz): use io.WriteString with slices of s, avoiding allocation. bufsize := 32 << 10 if len(s) < bufsize { @@ -262,7 +259,7 @@ func (r *byteStringReplacer) Replace(s string) string { // WriteString maintains one buffer that's at most 32KB. The bytes in // s are enumerated and the buffer is filled. If it reaches its // capacity or a byte has a replacement, the buffer is flushed to w. -func (r *byteStringReplacer) WriteString(w io.Writer, s string) (n int, err os.Error) { +func (r *byteStringReplacer) WriteString(w io.Writer, s string) (n int, err error) { // TODO(bradfitz): use io.WriteString with slices of s instead. bufsize := 32 << 10 if len(s) < bufsize { @@ -310,6 +307,6 @@ var discard io.Writer = devNull(0) type devNull int -func (devNull) Write(p []byte) (int, os.Error) { +func (devNull) Write(p []byte) (int, error) { return len(p), nil } diff --git a/src/pkg/strings/strings_test.go b/src/pkg/strings/strings_test.go index 4132996c19..2cf4bdec13 100644 --- a/src/pkg/strings/strings_test.go +++ b/src/pkg/strings/strings_test.go @@ -6,7 +6,7 @@ package strings_test import ( "bytes" - "os" + "io" "reflect" "strconv" . "strings" @@ -759,7 +759,7 @@ func TestReadByte(t *testing.T) { var res bytes.Buffer for { b, e := reader.ReadByte() - if e == os.EOF { + if e == io.EOF { break } if e != nil { @@ -799,7 +799,7 @@ func TestReadRune(t *testing.T) { res := "" for { r, z, e := reader.ReadRune() - if e == os.EOF { + if e == io.EOF { break } if e != nil { diff --git a/src/pkg/syscall/dll_windows.go b/src/pkg/syscall/dll_windows.go index f305bba3df..1873d0c90d 100644 --- a/src/pkg/syscall/dll_windows.go +++ b/src/pkg/syscall/dll_windows.go @@ -25,7 +25,7 @@ type DLLError struct { Msg string } -func (e *DLLError) String() string { return e.Msg } +func (e *DLLError) Error() string { return e.Msg } // Implemented in ../runtime/windows/syscall.goc. func Syscall(trap, nargs, a1, a2, a3 uintptr) (r1, r2, err uintptr) diff --git a/src/pkg/syslog/syslog.go b/src/pkg/syslog/syslog.go index 6933372127..26a2f736b1 100644 --- a/src/pkg/syslog/syslog.go +++ b/src/pkg/syslog/syslog.go @@ -37,9 +37,9 @@ type Writer struct { } type serverConn interface { - writeBytes(p Priority, prefix string, b []byte) (int, os.Error) - writeString(p Priority, prefix string, s string) (int, os.Error) - close() os.Error + writeBytes(p Priority, prefix string, b []byte) (int, error) + writeString(p Priority, prefix string, s string) (int, error) + close() error } type netConn struct { @@ -49,7 +49,7 @@ type netConn struct { // New establishes a new connection to the system log daemon. // Each write to the returned writer sends a log message with // the given priority and prefix. -func New(priority Priority, prefix string) (w *Writer, err os.Error) { +func New(priority Priority, prefix string) (w *Writer, err error) { return Dial("", "", priority, prefix) } @@ -57,7 +57,7 @@ func New(priority Priority, prefix string) (w *Writer, err os.Error) { // to address raddr on the network net. // Each write to the returned writer sends a log message with // the given priority and prefix. -func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, err os.Error) { +func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, err error) { if prefix == "" { prefix = os.Args[0] } @@ -73,66 +73,66 @@ func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, e } // Write sends a log message to the syslog daemon. -func (w *Writer) Write(b []byte) (int, os.Error) { +func (w *Writer) Write(b []byte) (int, error) { if w.priority > LOG_DEBUG || w.priority < LOG_EMERG { return 0, os.EINVAL } return w.conn.writeBytes(w.priority, w.prefix, b) } -func (w *Writer) writeString(p Priority, s string) (int, os.Error) { +func (w *Writer) writeString(p Priority, s string) (int, error) { return w.conn.writeString(p, w.prefix, s) } -func (w *Writer) Close() os.Error { return w.conn.close() } +func (w *Writer) Close() error { return w.conn.close() } // Emerg logs a message using the LOG_EMERG priority. -func (w *Writer) Emerg(m string) (err os.Error) { +func (w *Writer) Emerg(m string) (err error) { _, err = w.writeString(LOG_EMERG, m) return err } // Crit logs a message using the LOG_CRIT priority. -func (w *Writer) Crit(m string) (err os.Error) { +func (w *Writer) Crit(m string) (err error) { _, err = w.writeString(LOG_CRIT, m) return err } // ERR logs a message using the LOG_ERR priority. -func (w *Writer) Err(m string) (err os.Error) { +func (w *Writer) Err(m string) (err error) { _, err = w.writeString(LOG_ERR, m) return err } // Warning logs a message using the LOG_WARNING priority. -func (w *Writer) Warning(m string) (err os.Error) { +func (w *Writer) Warning(m string) (err error) { _, err = w.writeString(LOG_WARNING, m) return err } // Notice logs a message using the LOG_NOTICE priority. -func (w *Writer) Notice(m string) (err os.Error) { +func (w *Writer) Notice(m string) (err error) { _, err = w.writeString(LOG_NOTICE, m) return err } // Info logs a message using the LOG_INFO priority. -func (w *Writer) Info(m string) (err os.Error) { +func (w *Writer) Info(m string) (err error) { _, err = w.writeString(LOG_INFO, m) return err } // Debug logs a message using the LOG_DEBUG priority. -func (w *Writer) Debug(m string) (err os.Error) { +func (w *Writer) Debug(m string) (err error) { _, err = w.writeString(LOG_DEBUG, m) return err } -func (n netConn) writeBytes(p Priority, prefix string, b []byte) (int, os.Error) { +func (n netConn) writeBytes(p Priority, prefix string, b []byte) (int, error) { return fmt.Fprintf(n.conn, "<%d>%s: %s\n", p, prefix, b) } -func (n netConn) writeString(p Priority, prefix string, s string) (int, os.Error) { +func (n netConn) writeString(p Priority, prefix string, s string) (int, error) { return fmt.Fprintf(n.conn, "<%d>%s: %s\n", p, prefix, s) } -func (n netConn) close() os.Error { +func (n netConn) close() error { return n.conn.Close() } diff --git a/src/pkg/syslog/syslog_unix.go b/src/pkg/syslog/syslog_unix.go index b1516715bc..b1c929ad2f 100644 --- a/src/pkg/syslog/syslog_unix.go +++ b/src/pkg/syslog/syslog_unix.go @@ -5,14 +5,14 @@ package syslog import ( + "errors" "net" - "os" ) // unixSyslog opens a connection to the syslog daemon running on the // local machine using a Unix domain socket. -func unixSyslog() (conn serverConn, err os.Error) { +func unixSyslog() (conn serverConn, err error) { logTypes := []string{"unixgram", "unix"} logPaths := []string{"/dev/log", "/var/run/syslog"} var raddr string @@ -27,5 +27,5 @@ func unixSyslog() (conn serverConn, err os.Error) { } } } - return nil, os.NewError("Unix syslog delivery error") + return nil, errors.New("Unix syslog delivery error") } diff --git a/src/pkg/tabwriter/tabwriter.go b/src/pkg/tabwriter/tabwriter.go index 2f35d961eb..670e3c5390 100644 --- a/src/pkg/tabwriter/tabwriter.go +++ b/src/pkg/tabwriter/tabwriter.go @@ -215,7 +215,7 @@ func (b *Writer) dump() { // local error wrapper so we can distinguish os.Errors we want to return // as errors from genuine panics (which we don't want to return as errors) type osError struct { - err os.Error + err error } func (b *Writer) write0(buf []byte) { @@ -441,7 +441,7 @@ func (b *Writer) terminateCell(htab bool) int { return len(*line) } -func handlePanic(err *os.Error) { +func handlePanic(err *error) { if e := recover(); e != nil { *err = e.(osError).err // re-panics if it's not a local osError } @@ -452,7 +452,7 @@ func handlePanic(err *os.Error) { // incomplete escape sequence at the end is simply considered // complete for formatting purposes. // -func (b *Writer) Flush() (err os.Error) { +func (b *Writer) Flush() (err error) { defer b.reset() // even in the presence of errors defer handlePanic(&err) @@ -477,7 +477,7 @@ var hbar = []byte("---\n") // The only errors returned are ones encountered // while writing to the underlying output stream. // -func (b *Writer) Write(buf []byte) (n int, err os.Error) { +func (b *Writer) Write(buf []byte) (n int, err error) { defer handlePanic(&err) // split text into cells diff --git a/src/pkg/tabwriter/tabwriter_test.go b/src/pkg/tabwriter/tabwriter_test.go index 6ef7e808ef..1ffb330d43 100644 --- a/src/pkg/tabwriter/tabwriter_test.go +++ b/src/pkg/tabwriter/tabwriter_test.go @@ -6,7 +6,6 @@ package tabwriter import ( "io" - "os" "testing" ) @@ -18,7 +17,7 @@ func (b *buffer) init(n int) { b.a = make([]byte, n)[0:0] } func (b *buffer) clear() { b.a = b.a[0:0] } -func (b *buffer) Write(buf []byte) (written int, err os.Error) { +func (b *buffer) Write(buf []byte) (written int, err error) { n := len(b.a) m := len(buf) if n+m <= cap(b.a) { diff --git a/src/pkg/template/exec.go b/src/pkg/template/exec.go index 34c6633232..7850f6daf5 100644 --- a/src/pkg/template/exec.go +++ b/src/pkg/template/exec.go @@ -7,7 +7,6 @@ package template import ( "fmt" "io" - "os" "reflect" "runtime" "strings" @@ -70,25 +69,25 @@ func (s *state) errorf(format string, args ...interface{}) { } // error terminates processing. -func (s *state) error(err os.Error) { +func (s *state) error(err error) { s.errorf("%s", err) } // errRecover is the handler that turns panics into returns from the top // level of Parse. -func errRecover(errp *os.Error) { +func errRecover(errp *error) { e := recover() if e != nil { if _, ok := e.(runtime.Error); ok { panic(e) } - *errp = e.(os.Error) + *errp = e.(error) } } // Execute applies a parsed template to the specified data object, // writing the output to wr. -func (t *Template) Execute(wr io.Writer, data interface{}) (err os.Error) { +func (t *Template) Execute(wr io.Writer, data interface{}) (err error) { defer errRecover(&err) value := reflect.ValueOf(data) state := &state{ @@ -446,7 +445,7 @@ func methodByName(receiver reflect.Value, name string) (reflect.Value, bool) { } var ( - osErrorType = reflect.TypeOf((*os.Error)(nil)).Elem() + osErrorType = reflect.TypeOf((*error)(nil)).Elem() fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem() ) @@ -495,7 +494,7 @@ func (s *state) evalCall(dot, fun reflect.Value, name string, args []parse.Node, result := fun.Call(argv) // If we have an os.Error that is not nil, stop execution and return that error to the caller. if len(result) == 2 && !result[1].IsNil() { - s.errorf("error calling %s: %s", name, result[1].Interface().(os.Error)) + s.errorf("error calling %s: %s", name, result[1].Interface().(error)) } return result[0] } diff --git a/src/pkg/template/exec_test.go b/src/pkg/template/exec_test.go index 2d2b402942..20839c3e34 100644 --- a/src/pkg/template/exec_test.go +++ b/src/pkg/template/exec_test.go @@ -159,7 +159,7 @@ func (t *T) MSort(m map[string]int) []string { } // EPERM returns a value and an os.Error according to its argument. -func (t *T) EPERM(error bool) (bool, os.Error) { +func (t *T) EPERM(error bool) (bool, error) { if error { return true, os.EPERM } @@ -548,7 +548,7 @@ func TestExecuteError(t *testing.T) { err = tmpl.Execute(b, tVal) if err == nil { t.Errorf("expected error; got none") - } else if !strings.Contains(err.String(), os.EPERM.String()) { + } else if !strings.Contains(err.Error(), os.EPERM.Error()) { if *debug { fmt.Printf("test execute error: %s\n", err) } diff --git a/src/pkg/template/funcs.go b/src/pkg/template/funcs.go index 938559eec9..59c2ee708c 100644 --- a/src/pkg/template/funcs.go +++ b/src/pkg/template/funcs.go @@ -8,7 +8,6 @@ import ( "bytes" "fmt" "io" - "os" "reflect" "strings" "unicode" @@ -102,7 +101,7 @@ func findFunction(name string, tmpl *Template, set *Set) (reflect.Value, bool) { // index returns the result of indexing its first argument by the following // arguments. Thus "index x 1 2 3" is, in Go syntax, x[1][2][3]. Each // indexed item must be a map, slice, or array. -func index(item interface{}, indices ...interface{}) (interface{}, os.Error) { +func index(item interface{}, indices ...interface{}) (interface{}, error) { v := reflect.ValueOf(item) for _, i := range indices { index := reflect.ValueOf(i) @@ -144,7 +143,7 @@ func index(item interface{}, indices ...interface{}) (interface{}, os.Error) { // Length // length returns the length of the item, with an error if it has no defined length. -func length(item interface{}) (int, os.Error) { +func length(item interface{}) (int, error) { v, isNil := indirect(reflect.ValueOf(item)) if isNil { return 0, fmt.Errorf("len of nil pointer") diff --git a/src/pkg/template/helper.go b/src/pkg/template/helper.go index 1dc90f7ff4..b7a9deeba9 100644 --- a/src/pkg/template/helper.go +++ b/src/pkg/template/helper.go @@ -9,7 +9,6 @@ package template import ( "fmt" "io/ioutil" - "os" "path/filepath" ) @@ -19,7 +18,7 @@ import ( // and panics if the error is non-nil. It is intended for use in variable initializations // such as // var t = template.Must(template.New("name").Parse("text")) -func Must(t *Template, err os.Error) *Template { +func Must(t *Template, err error) *Template { if err != nil { panic(err) } @@ -28,7 +27,7 @@ func Must(t *Template, err os.Error) *Template { // ParseFile creates a new Template and parses the template definition from // the named file. The template name is the base name of the file. -func ParseFile(filename string) (*Template, os.Error) { +func ParseFile(filename string) (*Template, error) { t := New(filepath.Base(filename)) return t.ParseFile(filename) } @@ -37,7 +36,7 @@ func ParseFile(filename string) (*Template, os.Error) { // definition from the named file. The template name is the base name // of the file. It also adds the template to the set. Function bindings are // checked against those in the set. -func parseFileInSet(filename string, set *Set) (*Template, os.Error) { +func parseFileInSet(filename string, set *Set) (*Template, error) { t := New(filepath.Base(filename)) return t.parseFileInSet(filename, set) } @@ -45,7 +44,7 @@ func parseFileInSet(filename string, set *Set) (*Template, os.Error) { // ParseFile reads the template definition from a file and parses it to // construct an internal representation of the template for execution. // The returned template will be nil if an error occurs. -func (t *Template) ParseFile(filename string) (*Template, os.Error) { +func (t *Template) ParseFile(filename string) (*Template, error) { b, err := ioutil.ReadFile(filename) if err != nil { return nil, err @@ -57,7 +56,7 @@ func (t *Template) ParseFile(filename string) (*Template, os.Error) { // are checked against those in the set and the template is added // to the set. // The returned template will be nil if an error occurs. -func (t *Template) parseFileInSet(filename string, set *Set) (*Template, os.Error) { +func (t *Template) parseFileInSet(filename string, set *Set) (*Template, error) { b, err := ioutil.ReadFile(filename) if err != nil { return nil, err @@ -71,7 +70,7 @@ func (t *Template) parseFileInSet(filename string, set *Set) (*Template, os.Erro // and panics if the error is non-nil. It is intended for use in variable initializations // such as // var s = template.SetMust(template.ParseSetFiles("file")) -func SetMust(s *Set, err os.Error) *Set { +func SetMust(s *Set, err error) *Set { if err != nil { panic(err) } @@ -81,7 +80,7 @@ func SetMust(s *Set, err os.Error) *Set { // ParseFiles parses the named files into a set of named templates. // Each file must be parseable by itself. // If an error occurs, parsing stops and the returned set is nil. -func (s *Set) ParseFiles(filenames ...string) (*Set, os.Error) { +func (s *Set) ParseFiles(filenames ...string) (*Set, error) { for _, filename := range filenames { b, err := ioutil.ReadFile(filename) if err != nil { @@ -97,7 +96,7 @@ func (s *Set) ParseFiles(filenames ...string) (*Set, os.Error) { // ParseSetFiles creates a new Set and parses the set definition from the // named files. Each file must be individually parseable. -func ParseSetFiles(filenames ...string) (*Set, os.Error) { +func ParseSetFiles(filenames ...string) (*Set, error) { s := new(Set) for _, filename := range filenames { b, err := ioutil.ReadFile(filename) @@ -116,7 +115,7 @@ func ParseSetFiles(filenames ...string) (*Set, os.Error) { // pattern. The pattern is processed by filepath.Glob and must match at // least one file. // If an error occurs, parsing stops and the returned set is nil. -func (s *Set) ParseGlob(pattern string) (*Set, os.Error) { +func (s *Set) ParseGlob(pattern string) (*Set, error) { filenames, err := filepath.Glob(pattern) if err != nil { return nil, err @@ -130,7 +129,7 @@ func (s *Set) ParseGlob(pattern string) (*Set, os.Error) { // ParseSetGlob creates a new Set and parses the set definition from the // files identified by the pattern. The pattern is processed by filepath.Glob // and must match at least one file. -func ParseSetGlob(pattern string) (*Set, os.Error) { +func ParseSetGlob(pattern string) (*Set, error) { set, err := new(Set).ParseGlob(pattern) if err != nil { return nil, err @@ -150,7 +149,7 @@ func ParseSetGlob(pattern string) (*Set, os.Error) { // individual templates, which are then added to the set. // Each file must be parseable by itself. // If an error occurs, parsing stops and the returned set is nil. -func (s *Set) ParseTemplateFiles(filenames ...string) (*Set, os.Error) { +func (s *Set) ParseTemplateFiles(filenames ...string) (*Set, error) { for _, filename := range filenames { _, err := parseFileInSet(filename, s) if err != nil { @@ -170,7 +169,7 @@ func (s *Set) ParseTemplateFiles(filenames ...string) (*Set, os.Error) { // individual templates, which are then added to the set. // Each file must be parseable by itself. // If an error occurs, parsing stops and the returned set is nil. -func (s *Set) ParseTemplateGlob(pattern string) (*Set, os.Error) { +func (s *Set) ParseTemplateGlob(pattern string) (*Set, error) { filenames, err := filepath.Glob(pattern) if err != nil { return nil, err @@ -194,7 +193,7 @@ func (s *Set) ParseTemplateGlob(pattern string) (*Set, os.Error) { // individual templates, which are then added to the set. // Each file must be parseable by itself. Parsing stops if an error is // encountered. -func ParseTemplateFiles(filenames ...string) (*Set, os.Error) { +func ParseTemplateFiles(filenames ...string) (*Set, error) { set := new(Set) set.init() for _, filename := range filenames { @@ -220,7 +219,7 @@ func ParseTemplateFiles(filenames ...string) (*Set, os.Error) { // individual templates, which are then added to the set. // Each file must be parseable by itself. Parsing stops if an error is // encountered. -func ParseTemplateGlob(pattern string) (*Set, os.Error) { +func ParseTemplateGlob(pattern string) (*Set, error) { set := new(Set) filenames, err := filepath.Glob(pattern) if err != nil { diff --git a/src/pkg/template/parse.go b/src/pkg/template/parse.go index 3068a77bed..2fbd37ffa9 100644 --- a/src/pkg/template/parse.go +++ b/src/pkg/template/parse.go @@ -5,7 +5,6 @@ package template import ( - "os" "reflect" "template/parse" ) @@ -62,7 +61,7 @@ func (t *Template) Funcs(funcMap FuncMap) *Template { // Parse parses the template definition string to construct an internal // representation of the template for execution. -func (t *Template) Parse(s string) (tmpl *Template, err os.Error) { +func (t *Template) Parse(s string) (tmpl *Template, err error) { t.Tree, err = parse.New(t.name).Parse(s, t.leftDelim, t.rightDelim, t.parseFuncs, builtins) if err != nil { return nil, err @@ -74,7 +73,7 @@ func (t *Template) Parse(s string) (tmpl *Template, err os.Error) { // representation of the template for execution. It also adds the template // to the set. // Function bindings are checked against those in the set. -func (t *Template) ParseInSet(s string, set *Set) (tmpl *Template, err os.Error) { +func (t *Template) ParseInSet(s string, set *Set) (tmpl *Template, err error) { var setFuncs FuncMap if set != nil { setFuncs = set.parseFuncs diff --git a/src/pkg/template/parse/node.go b/src/pkg/template/parse/node.go index 7411327a65..a4e5514768 100644 --- a/src/pkg/template/parse/node.go +++ b/src/pkg/template/parse/node.go @@ -9,7 +9,6 @@ package parse import ( "bytes" "fmt" - "os" "strconv" "strings" ) @@ -239,7 +238,7 @@ type NumberNode struct { Text string // The original textual representation from the input. } -func newNumber(text string, typ itemType) (*NumberNode, os.Error) { +func newNumber(text string, typ itemType) (*NumberNode, error) { n := &NumberNode{NodeType: NodeNumber, Text: text} switch typ { case itemCharConstant: diff --git a/src/pkg/template/parse/parse.go b/src/pkg/template/parse/parse.go index 9934d8221d..1b6ab3af4f 100644 --- a/src/pkg/template/parse/parse.go +++ b/src/pkg/template/parse/parse.go @@ -8,7 +8,6 @@ package parse import ( "fmt" - "os" "runtime" "strconv" "unicode" @@ -75,7 +74,7 @@ func (t *Tree) errorf(format string, args ...interface{}) { } // error terminates processing. -func (t *Tree) error(err os.Error) { +func (t *Tree) error(err error) { t.errorf("%s", err) } @@ -94,7 +93,7 @@ func (t *Tree) unexpected(token item, context string) { } // recover is the handler that turns panics into returns from the top level of Parse. -func (t *Tree) recover(errp *os.Error) { +func (t *Tree) recover(errp *error) { e := recover() if e != nil { if _, ok := e.(runtime.Error); ok { @@ -103,7 +102,7 @@ func (t *Tree) recover(errp *os.Error) { if t != nil { t.stopParse() } - *errp = e.(os.Error) + *errp = e.(error) } return } @@ -147,7 +146,7 @@ func (t *Tree) atEOF() bool { // Parse parses the template definition string to construct an internal // representation of the template for execution. If either action delimiter // string is empty, the default ("{{" or "}}") is used. -func (t *Tree) Parse(s, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree *Tree, err os.Error) { +func (t *Tree) Parse(s, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree *Tree, err error) { defer t.recover(&err) t.startParse(funcs, lex(t.Name, s, leftDelim, rightDelim)) t.parse(true) diff --git a/src/pkg/template/parse/set.go b/src/pkg/template/parse/set.go index b909f71cd7..d363eeff08 100644 --- a/src/pkg/template/parse/set.go +++ b/src/pkg/template/parse/set.go @@ -6,14 +6,13 @@ package parse import ( "fmt" - "os" "strconv" ) // Set returns a slice of Trees created by parsing the template set // definition in the argument string. If an error is encountered, // parsing stops and an empty slice is returned with the error. -func Set(text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree map[string]*Tree, err os.Error) { +func Set(text, leftDelim, rightDelim string, funcs ...map[string]interface{}) (tree map[string]*Tree, err error) { tree = make(map[string]*Tree) defer (*Tree)(nil).recover(&err) lex := lex("set", text, leftDelim, rightDelim) diff --git a/src/pkg/template/set.go b/src/pkg/template/set.go index 712961b731..bd0dfc6b36 100644 --- a/src/pkg/template/set.go +++ b/src/pkg/template/set.go @@ -7,7 +7,6 @@ package template import ( "fmt" "io" - "os" "reflect" "template/parse" ) @@ -66,7 +65,7 @@ func (s *Set) Add(templates ...*Template) *Set { } // add adds the argument template to the set. -func (s *Set) add(t *Template) os.Error { +func (s *Set) add(t *Template) error { s.init() if t.set != nil { return fmt.Errorf("template: %q already in a set", t.name) @@ -92,7 +91,7 @@ func (s *Set) FuncMap() FuncMap { // Execute applies the named template to the specified data object, writing // the output to wr. -func (s *Set) Execute(wr io.Writer, name string, data interface{}) os.Error { +func (s *Set) Execute(wr io.Writer, name string, data interface{}) error { tmpl := s.tmpl[name] if tmpl == nil { return fmt.Errorf("template: no template %q in set", name) @@ -104,7 +103,7 @@ func (s *Set) Execute(wr io.Writer, name string, data interface{}) os.Error { // multiple times for a given set, adding the templates defined in the string // to the set. If a template is redefined, the element in the set is // overwritten with the new definition. -func (s *Set) Parse(text string) (*Set, os.Error) { +func (s *Set) Parse(text string) (*Set, error) { trees, err := parse.Set(text, s.leftDelim, s.rightDelim, s.parseFuncs, builtins) if err != nil { return nil, err diff --git a/src/pkg/testing/benchmark.go b/src/pkg/testing/benchmark.go index fd0bd86657..df4c4a1a29 100644 --- a/src/pkg/testing/benchmark.go +++ b/src/pkg/testing/benchmark.go @@ -197,7 +197,7 @@ func (r BenchmarkResult) String() string { // An internal function but exported because it is cross-package; part of the implementation // of gotest. -func RunBenchmarks(matchString func(pat, str string) (bool, os.Error), benchmarks []InternalBenchmark) { +func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark) { // If no flag was specified, don't run benchmarks. if len(*matchBenchmarks) == 0 { return @@ -205,7 +205,7 @@ func RunBenchmarks(matchString func(pat, str string) (bool, os.Error), benchmark for _, Benchmark := range benchmarks { matched, err := matchString(*matchBenchmarks, Benchmark.Name) if err != nil { - println("invalid regexp for -test.bench:", err.String()) + println("invalid regexp for -test.bench:", err.Error()) os.Exit(1) } if !matched { diff --git a/src/pkg/testing/example.go b/src/pkg/testing/example.go index f148951d4f..5b3e322b59 100644 --- a/src/pkg/testing/example.go +++ b/src/pkg/testing/example.go @@ -25,7 +25,7 @@ func RunExamples(examples []InternalExample) (ok bool) { defer func() { os.Stdout, os.Stderr = stdout, stderr if e := recover(); e != nil { - if err, ok := e.(os.Error); ok { + if err, ok := e.(error); ok { fmt.Fprintln(os.Stderr, err) os.Exit(1) } diff --git a/src/pkg/testing/iotest/logger.go b/src/pkg/testing/iotest/logger.go index c3bf5df3c3..1475d9b0c6 100644 --- a/src/pkg/testing/iotest/logger.go +++ b/src/pkg/testing/iotest/logger.go @@ -7,7 +7,6 @@ package iotest import ( "io" "log" - "os" ) type writeLogger struct { @@ -15,7 +14,7 @@ type writeLogger struct { w io.Writer } -func (l *writeLogger) Write(p []byte) (n int, err os.Error) { +func (l *writeLogger) Write(p []byte) (n int, err error) { n, err = l.w.Write(p) if err != nil { log.Printf("%s %x: %v", l.prefix, p[0:n], err) @@ -37,7 +36,7 @@ type readLogger struct { r io.Reader } -func (l *readLogger) Read(p []byte) (n int, err os.Error) { +func (l *readLogger) Read(p []byte) (n int, err error) { n, err = l.r.Read(p) if err != nil { log.Printf("%s %x: %v", l.prefix, p[0:n], err) diff --git a/src/pkg/testing/iotest/reader.go b/src/pkg/testing/iotest/reader.go index dcf5565e07..ab8dc31a1f 100644 --- a/src/pkg/testing/iotest/reader.go +++ b/src/pkg/testing/iotest/reader.go @@ -6,8 +6,8 @@ package iotest import ( + "errors" "io" - "os" ) // OneByteReader returns a Reader that implements @@ -18,7 +18,7 @@ type oneByteReader struct { r io.Reader } -func (r *oneByteReader) Read(p []byte) (int, os.Error) { +func (r *oneByteReader) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } @@ -33,7 +33,7 @@ type halfReader struct { r io.Reader } -func (r *halfReader) Read(p []byte) (int, os.Error) { +func (r *halfReader) Read(p []byte) (int, error) { return r.r.Read(p[0 : (len(p)+1)/2]) } @@ -48,7 +48,7 @@ type dataErrReader struct { data []byte } -func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { +func (r *dataErrReader) Read(p []byte) (n int, err error) { // loop because first call needs two reads: // one to get data and a second to look for an error. for { @@ -66,7 +66,7 @@ func (r *dataErrReader) Read(p []byte) (n int, err os.Error) { return } -var ErrTimeout = os.NewError("timeout") +var ErrTimeout = errors.New("timeout") // TimeoutReader returns ErrTimeout on the second read // with no data. Subsequent calls to read succeed. @@ -77,7 +77,7 @@ type timeoutReader struct { count int } -func (r *timeoutReader) Read(p []byte) (int, os.Error) { +func (r *timeoutReader) Read(p []byte) (int, error) { r.count++ if r.count == 2 { return 0, ErrTimeout diff --git a/src/pkg/testing/iotest/writer.go b/src/pkg/testing/iotest/writer.go index 71f504ce2a..af61ab8584 100644 --- a/src/pkg/testing/iotest/writer.go +++ b/src/pkg/testing/iotest/writer.go @@ -4,10 +4,7 @@ package iotest -import ( - "io" - "os" -) +import "io" // TruncateWriter returns a Writer that writes to w // but stops silently after n bytes. @@ -20,7 +17,7 @@ type truncateWriter struct { n int64 } -func (t *truncateWriter) Write(p []byte) (n int, err os.Error) { +func (t *truncateWriter) Write(p []byte) (n int, err error) { if t.n <= 0 { return len(p), nil } diff --git a/src/pkg/testing/quick/quick.go b/src/pkg/testing/quick/quick.go index 9ec1925de3..9e6b84bc29 100644 --- a/src/pkg/testing/quick/quick.go +++ b/src/pkg/testing/quick/quick.go @@ -9,7 +9,6 @@ import ( "flag" "fmt" "math" - "os" "rand" "reflect" "strings" @@ -191,7 +190,7 @@ func (c *Config) getMaxCount() (maxCount int) { // used, independent of the functions being tested. type SetupError string -func (s SetupError) String() string { return string(s) } +func (s SetupError) Error() string { return string(s) } // A CheckError is the result of Check finding an error. type CheckError struct { @@ -199,7 +198,7 @@ type CheckError struct { In []interface{} } -func (s *CheckError) String() string { +func (s *CheckError) Error() string { return fmt.Sprintf("#%d: failed on input %s", s.Count, toString(s.In)) } @@ -210,7 +209,7 @@ type CheckEqualError struct { Out2 []interface{} } -func (s *CheckEqualError) String() string { +func (s *CheckEqualError) Error() string { return fmt.Sprintf("#%d: failed on input %s. Output 1: %s. Output 2: %s", s.Count, toString(s.In), toString(s.Out1), toString(s.Out2)) } @@ -229,7 +228,7 @@ func (s *CheckEqualError) String() string { // t.Error(err) // } // } -func Check(function interface{}, config *Config) (err os.Error) { +func Check(function interface{}, config *Config) (err error) { if config == nil { config = &defaultConfig } @@ -272,7 +271,7 @@ func Check(function interface{}, config *Config) (err os.Error) { // It calls f and g repeatedly with arbitrary values for each argument. // If f and g return different answers, CheckEqual returns a *CheckEqualError // describing the input and the outputs. -func CheckEqual(f, g interface{}, config *Config) (err os.Error) { +func CheckEqual(f, g interface{}, config *Config) (err error) { if config == nil { config = &defaultConfig } @@ -317,7 +316,7 @@ func CheckEqual(f, g interface{}, config *Config) (err os.Error) { // arbitraryValues writes Values to args such that args contains Values // suitable for calling f. -func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err os.Error) { +func arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) { if config.Values != nil { config.Values(args, rand) return diff --git a/src/pkg/testing/quick/quick_test.go b/src/pkg/testing/quick/quick_test.go index f2618c3c25..e9ff1aa449 100644 --- a/src/pkg/testing/quick/quick_test.go +++ b/src/pkg/testing/quick/quick_test.go @@ -8,7 +8,6 @@ import ( "rand" "reflect" "testing" - "os" ) func fBool(a bool) bool { return a } @@ -63,7 +62,7 @@ func fIntptr(a *int) *int { return &b } -func reportError(property string, err os.Error, t *testing.T) { +func reportError(property string, err error, t *testing.T) { if err != nil { t.Errorf("%s: %s", property, err) } diff --git a/src/pkg/testing/script/script.go b/src/pkg/testing/script/script.go index afb286f5b8..98f3625198 100644 --- a/src/pkg/testing/script/script.go +++ b/src/pkg/testing/script/script.go @@ -7,7 +7,6 @@ package script import ( "fmt" - "os" "rand" "reflect" "strings" @@ -171,7 +170,7 @@ type ReceivedUnexpected struct { ready []*Event } -func (r ReceivedUnexpected) String() string { +func (r ReceivedUnexpected) Error() string { names := make([]string, len(r.ready)) for i, v := range r.ready { names[i] = v.name @@ -183,7 +182,7 @@ func (r ReceivedUnexpected) String() string { // Events. type SetupError string -func (s SetupError) String() string { return string(s) } +func (s SetupError) Error() string { return string(s) } func NewEvent(name string, predecessors []*Event, action action) *Event { e := &Event{name, false, predecessors, action} @@ -223,7 +222,7 @@ func NewEvent(name string, predecessors []*Event, action action) *Event { // the other. At each receive step, all the receive channels are considered, // thus Perform may see a value from a channel that is not in the current ready // set and fail. -func Perform(seed int64, events []*Event) (err os.Error) { +func Perform(seed int64, events []*Event) (err error) { r := rand.New(rand.NewSource(seed)) channels, err := getChannels(events) @@ -269,7 +268,7 @@ Outer: } // getChannels returns all the channels listed in any receive events. -func getChannels(events []*Event) ([]interface{}, os.Error) { +func getChannels(events []*Event) ([]interface{}, error) { channels := make([]interface{}, len(events)) j := 0 @@ -326,7 +325,7 @@ type channelRecv struct { } // readyEvents returns the subset of events that are ready. -func readyEvents(events []*Event) ([]*Event, os.Error) { +func readyEvents(events []*Event) ([]*Event, error) { ready := make([]*Event, len(events)) j := 0 diff --git a/src/pkg/testing/testing.go b/src/pkg/testing/testing.go index a555cb4a15..5869642c7e 100644 --- a/src/pkg/testing/testing.go +++ b/src/pkg/testing/testing.go @@ -173,7 +173,7 @@ func tRunner(t *T, test *InternalTest) { // An internal function but exported because it is cross-package; part of the implementation // of gotest. -func Main(matchString func(pat, str string) (bool, os.Error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { +func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) { flag.Parse() parseCpuList() @@ -201,7 +201,7 @@ func report(t *T) { } } -func RunTests(matchString func(pat, str string) (bool, os.Error), tests []InternalTest) (ok bool) { +func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool) { ok = true if len(tests) == 0 { fmt.Fprintln(os.Stderr, "testing: warning: no tests to run") @@ -217,7 +217,7 @@ func RunTests(matchString func(pat, str string) (bool, os.Error), tests []Intern for i := 0; i < len(tests); i++ { matched, err := matchString(*match, tests[i].Name) if err != nil { - println("invalid regexp for -test.run:", err.String()) + println("invalid regexp for -test.run:", err.Error()) os.Exit(1) } if !matched { diff --git a/src/pkg/time/format.go b/src/pkg/time/format.go index 1a629c9188..14b712ad08 100644 --- a/src/pkg/time/format.go +++ b/src/pkg/time/format.go @@ -2,7 +2,7 @@ package time import ( "bytes" - "os" + "errors" "strconv" ) @@ -250,7 +250,7 @@ func match(s1, s2 string) bool { return true } -func lookup(tab []string, val string) (int, string, os.Error) { +func lookup(tab []string, val string) (int, string, error) { for i, v := range tab { if len(val) >= len(v) && match(val[0:len(v)], v) { return i, val[len(v):], nil @@ -413,7 +413,7 @@ func (t *Time) String() string { return t.Format(UnixDate) } -var errBad = os.NewError("bad value for field") // placeholder not passed to user +var errBad = errors.New("bad value for field") // placeholder not passed to user // ParseError describes a problem parsing a time string. type ParseError struct { @@ -425,7 +425,7 @@ type ParseError struct { } // String is the string representation of a ParseError. -func (e *ParseError) String() string { +func (e *ParseError) Error() string { if e.Message == "" { return "parsing time " + strconv.Quote(e.Value) + " as " + @@ -450,7 +450,7 @@ func isDigit(s string, i int) bool { // getnum parses s[0:1] or s[0:2] (fixed forces the latter) // as a decimal integer and returns the integer and the // remainder of the string. -func getnum(s string, fixed bool) (int, string, os.Error) { +func getnum(s string, fixed bool) (int, string, error) { if !isDigit(s, 0) { return 0, s, errBad } @@ -472,7 +472,7 @@ func cutspace(s string) string { // skip removes the given prefix from value, // treating runs of space characters as equivalent. -func skip(value, prefix string) (string, os.Error) { +func skip(value, prefix string) (string, error) { for len(prefix) > 0 { if prefix[0] == ' ' { if len(value) > 0 && value[0] != ' ' { @@ -505,7 +505,7 @@ func skip(value, prefix string) (string, os.Error) { // sane: hours in 0..23, minutes in 0..59, day of month in 1..31, etc. // Years must be in the range 0000..9999. The day of the week is checked // for syntax but it is otherwise ignored. -func Parse(alayout, avalue string) (*Time, os.Error) { +func Parse(alayout, avalue string) (*Time, error) { var t Time rangeErrString := "" // set if a value is out of range amSet := false // do we need to subtract 12 from the hour for midnight? @@ -513,7 +513,7 @@ func Parse(alayout, avalue string) (*Time, os.Error) { layout, value := alayout, avalue // Each iteration processes one std value. for { - var err os.Error + var err error prefix, std, suffix := nextStdChunk(layout) value, err = skip(value, prefix) if err != nil { @@ -730,7 +730,7 @@ func Parse(alayout, avalue string) (*Time, os.Error) { return &t, nil } -func (t *Time) parseNanoseconds(value string, nbytes int) (rangErrString string, err os.Error) { +func (t *Time) parseNanoseconds(value string, nbytes int) (rangErrString string, err error) { if value[0] != '.' { return "", errBad } diff --git a/src/pkg/time/sleep_test.go b/src/pkg/time/sleep_test.go index b6b88f6cab..5b02c8d234 100644 --- a/src/pkg/time/sleep_test.go +++ b/src/pkg/time/sleep_test.go @@ -5,8 +5,8 @@ package time_test import ( + "errors" "fmt" - "os" "testing" "sort" . "time" @@ -136,7 +136,7 @@ func TestAfterQueuing(t *testing.T) { // This test flakes out on some systems, // so we'll try it a few times before declaring it a failure. const attempts = 3 - err := os.NewError("!=nil") + err := errors.New("!=nil") for i := 0; i < attempts && err != nil; i++ { if err = testAfterQueuing(t); err != nil { t.Logf("attempt %v failed: %v", i, err) @@ -158,7 +158,7 @@ func await(slot int, result chan<- afterResult, ac <-chan int64) { result <- afterResult{slot, <-ac} } -func testAfterQueuing(t *testing.T) os.Error { +func testAfterQueuing(t *testing.T) error { const ( Delta = 100 * 1e6 ) diff --git a/src/pkg/time/sys.go b/src/pkg/time/sys.go index 9fde3b3b65..4bc9253393 100644 --- a/src/pkg/time/sys.go +++ b/src/pkg/time/sys.go @@ -29,7 +29,7 @@ func Nanoseconds() int64 { // Sleep pauses the current goroutine for at least ns nanoseconds. // Higher resolution sleeping may be provided by syscall.Nanosleep // on some operating systems. -func Sleep(ns int64) os.Error { +func Sleep(ns int64) error { _, err := sleep(Nanoseconds(), ns) return err } @@ -37,7 +37,7 @@ func Sleep(ns int64) os.Error { // sleep takes the current time and a duration, // pauses for at least ns nanoseconds, and // returns the current time and an error. -func sleep(t, ns int64) (int64, os.Error) { +func sleep(t, ns int64) (int64, error) { // TODO(cw): use monotonic-time once it's available end := t + ns for t < end { diff --git a/src/pkg/time/sys_plan9.go b/src/pkg/time/sys_plan9.go index 9ae0161ba8..a630b3ee03 100644 --- a/src/pkg/time/sys_plan9.go +++ b/src/pkg/time/sys_plan9.go @@ -9,7 +9,7 @@ import ( "syscall" ) -func sysSleep(t int64) os.Error { +func sysSleep(t int64) error { err := syscall.Sleep(t) if err != nil { return os.NewSyscallError("sleep", err) diff --git a/src/pkg/time/sys_unix.go b/src/pkg/time/sys_unix.go index 0119bdf7bf..17a6a2d63e 100644 --- a/src/pkg/time/sys_unix.go +++ b/src/pkg/time/sys_unix.go @@ -11,7 +11,7 @@ import ( "syscall" ) -func sysSleep(t int64) os.Error { +func sysSleep(t int64) error { errno := syscall.Sleep(t) if errno != 0 && errno != syscall.EINTR { return os.NewSyscallError("sleep", errno) diff --git a/src/pkg/time/sys_windows.go b/src/pkg/time/sys_windows.go index feff90b8b0..f9d6e89281 100644 --- a/src/pkg/time/sys_windows.go +++ b/src/pkg/time/sys_windows.go @@ -9,7 +9,7 @@ import ( "syscall" ) -func sysSleep(t int64) os.Error { +func sysSleep(t int64) error { errno := syscall.Sleep(t) if errno != 0 && errno != syscall.EINTR { return os.NewSyscallError("sleep", errno) diff --git a/src/pkg/time/tick.go b/src/pkg/time/tick.go index 852bae9c93..92f9eb893e 100644 --- a/src/pkg/time/tick.go +++ b/src/pkg/time/tick.go @@ -5,7 +5,7 @@ package time import ( - "os" + "errors" "sync" ) @@ -160,7 +160,7 @@ var onceStartTickerLoop sync.Once // ns must be greater than zero; if not, NewTicker will panic. func NewTicker(ns int64) *Ticker { if ns <= 0 { - panic(os.NewError("non-positive interval for NewTicker")) + panic(errors.New("non-positive interval for NewTicker")) } c := make(chan int64, 1) // See comment on send in tickerLoop t := &Ticker{ diff --git a/src/pkg/time/time_test.go b/src/pkg/time/time_test.go index e4cf51374c..8b373a13bc 100644 --- a/src/pkg/time/time_test.go +++ b/src/pkg/time/time_test.go @@ -387,7 +387,7 @@ func TestParseErrors(t *testing.T) { _, err := Parse(test.format, test.value) if err == nil { t.Errorf("expected error for %q %q", test.format, test.value) - } else if strings.Index(err.String(), test.expect) < 0 { + } else if strings.Index(err.Error(), test.expect) < 0 { t.Errorf("expected error with %q for %q %q; got %s", test.expect, test.format, test.value, err) } } diff --git a/src/pkg/time/zoneinfo_windows.go b/src/pkg/time/zoneinfo_windows.go index 41c48192dd..ba9295c65d 100644 --- a/src/pkg/time/zoneinfo_windows.go +++ b/src/pkg/time/zoneinfo_windows.go @@ -156,7 +156,7 @@ func (zi *zoneinfo) pickZone(t *Time) *zone { } var tz zoneinfo -var initError os.Error +var initError error var onceSetupZone sync.Once func setupZone() { diff --git a/src/pkg/unicode/maketables.go b/src/pkg/unicode/maketables.go index 7c7afc28bd..b7c23aed28 100644 --- a/src/pkg/unicode/maketables.go +++ b/src/pkg/unicode/maketables.go @@ -12,6 +12,7 @@ import ( "flag" "fmt" "http" + "io" "log" "os" "path/filepath" @@ -322,7 +323,7 @@ func loadChars() { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) @@ -359,7 +360,7 @@ func loadCasefold() { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) @@ -698,7 +699,7 @@ func printScriptOrProperty(doProps bool) { for { line, err := input.ReadString('\n') if err != nil { - if err == os.EOF { + if err == io.EOF { break } logger.Fatal(err) diff --git a/src/pkg/url/url.go b/src/pkg/url/url.go index dd1f93d14c..11fa18961a 100644 --- a/src/pkg/url/url.go +++ b/src/pkg/url/url.go @@ -7,19 +7,19 @@ package url import ( - "os" + "errors" "strconv" "strings" ) // Error reports an error and the operation and URL that caused it. type Error struct { - Op string - URL string - Error os.Error + Op string + URL string + Err error } -func (e *Error) String() string { return e.Op + " " + e.URL + ": " + e.Error.String() } +func (e *Error) Error() string { return e.Op + " " + e.URL + ": " + e.Err.Error() } func ishex(c byte) bool { switch { @@ -57,7 +57,7 @@ const ( type EscapeError string -func (e EscapeError) String() string { +func (e EscapeError) Error() string { return "invalid URL escape " + strconv.Quote(string(e)) } @@ -115,13 +115,13 @@ func shouldEscape(c byte, mode encoding) bool { // QueryUnescape does the inverse transformation of QueryEscape, converting // %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if // any % is not followed by two hexadecimal digits. -func QueryUnescape(s string) (string, os.Error) { +func QueryUnescape(s string) (string, error) { return unescape(s, encodeQueryComponent) } // unescape unescapes a string; the mode specifies // which section of the URL string is being unescaped. -func unescape(s string, mode encoding) (string, os.Error) { +func unescape(s string, mode encoding) (string, error) { // Count %, check that they're well-formed. n := 0 hasPlus := false @@ -226,7 +226,7 @@ func escape(s string, mode encoding) string { // ``is NOT RECOMMENDED, because the passing of authentication // information in clear text (such as URI) has proven to be a // security risk in almost every case where it has been used.'' -func UnescapeUserinfo(rawUserinfo string) (user, password string, err os.Error) { +func UnescapeUserinfo(rawUserinfo string) (user, password string, err error) { u, p := split(rawUserinfo, ':', true) if user, err = unescape(u, encodeUserPassword); err != nil { return "", "", err @@ -280,7 +280,7 @@ type URL struct { // Maybe rawurl is of the form scheme:path. // (Scheme must be [a-zA-Z][a-zA-Z0-9+-.]*) // If so, return scheme, path; else return "", rawurl. -func getscheme(rawurl string) (scheme, path string, err os.Error) { +func getscheme(rawurl string) (scheme, path string, err error) { for i := 0; i < len(rawurl); i++ { c := rawurl[i] switch { @@ -292,7 +292,7 @@ func getscheme(rawurl string) (scheme, path string, err os.Error) { } case c == ':': if i == 0 { - return "", "", os.NewError("missing protocol scheme") + return "", "", errors.New("missing protocol scheme") } return rawurl[0:i], rawurl[i+1:], nil default: @@ -323,7 +323,7 @@ func split(s string, c byte, cutc bool) (string, string) { // The string rawurl is assumed not to have a #fragment suffix. // (Web browsers strip #fragment before sending the URL to a web server.) // The rawurl may be relative or absolute. -func Parse(rawurl string) (url *URL, err os.Error) { +func Parse(rawurl string) (url *URL, err error) { return parse(rawurl, false) } @@ -332,7 +332,7 @@ func Parse(rawurl string) (url *URL, err os.Error) { // only as an absolute URI or an absolute path. // The string rawurl is assumed not to have a #fragment suffix. // (Web browsers strip #fragment before sending the URL to a web server.) -func ParseRequest(rawurl string) (url *URL, err os.Error) { +func ParseRequest(rawurl string) (url *URL, err error) { return parse(rawurl, true) } @@ -340,14 +340,14 @@ func ParseRequest(rawurl string) (url *URL, err os.Error) { // viaRequest is true, the URL is assumed to have arrived via an HTTP request, // in which case only absolute URLs or path-absolute relative URLs are allowed. // If viaRequest is false, all forms of relative URLs are allowed. -func parse(rawurl string, viaRequest bool) (url *URL, err os.Error) { +func parse(rawurl string, viaRequest bool) (url *URL, err error) { var ( leadingSlash bool path string ) if rawurl == "" { - err = os.NewError("empty url") + err = errors.New("empty url") goto Error } url = new(URL) @@ -373,7 +373,7 @@ func parse(rawurl string, viaRequest bool) (url *URL, err os.Error) { url.OpaquePath = true } else { if viaRequest && !leadingSlash { - err = os.NewError("invalid URI for request") + err = errors.New("invalid URI for request") goto Error } @@ -407,7 +407,7 @@ func parse(rawurl string, viaRequest bool) (url *URL, err os.Error) { if strings.Contains(rawHost, "%") { // Host cannot contain escaped characters. - err = os.NewError("hexadecimal escape in host") + err = errors.New("hexadecimal escape in host") goto Error } url.Host = rawHost @@ -424,7 +424,7 @@ Error: } // ParseWithReference is like Parse but allows a trailing #fragment. -func ParseWithReference(rawurlref string) (url *URL, err os.Error) { +func ParseWithReference(rawurlref string) (url *URL, err error) { // Cut off #frag. rawurl, frag := split(rawurlref, '#', false) if url, err = Parse(rawurl); err != nil { @@ -525,13 +525,13 @@ func (v Values) Del(key string) { // ParseQuery always returns a non-nil map containing all the // valid query parameters found; err describes the first decoding error // encountered, if any. -func ParseQuery(query string) (m Values, err os.Error) { +func ParseQuery(query string) (m Values, err error) { m = make(Values) err = parseQuery(m, query) return } -func parseQuery(m Values, query string) (err os.Error) { +func parseQuery(m Values, query string) (err error) { for query != "" { key := query if i := strings.IndexAny(key, "&;"); i >= 0 { @@ -615,7 +615,7 @@ func (url *URL) IsAbs() bool { // Parse parses a URL in the context of a base URL. The URL in ref // may be relative or absolute. Parse returns nil, err on parse // failure, otherwise its return value is the same as ResolveReference. -func (base *URL) Parse(ref string) (*URL, os.Error) { +func (base *URL) Parse(ref string) (*URL, error) { refurl, err := Parse(ref) if err != nil { return nil, err diff --git a/src/pkg/url/url_test.go b/src/pkg/url/url_test.go index 8c27e18e1a..dab3bfa1bb 100644 --- a/src/pkg/url/url_test.go +++ b/src/pkg/url/url_test.go @@ -6,7 +6,6 @@ package url import ( "fmt" - "os" "reflect" "testing" ) @@ -306,7 +305,7 @@ func ufmt(u *URL) string { u.Host, u.Path, u.RawQuery, u.Fragment) } -func DoTest(t *testing.T, parse func(string) (*URL, os.Error), name string, tests []URLTest) { +func DoTest(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) { for _, tt := range tests { u, err := parse(tt.in) if err != nil { @@ -364,7 +363,7 @@ func TestParseRequest(t *testing.T) { } } -func DoTestString(t *testing.T, parse func(string) (*URL, os.Error), name string, tests []URLTest) { +func DoTestString(t *testing.T, parse func(string) (*URL, error), name string, tests []URLTest) { for _, tt := range tests { u, err := parse(tt.in) if err != nil { @@ -392,7 +391,7 @@ func TestURLString(t *testing.T) { type EscapeTest struct { in string out string - err os.Error + err error } var unescapeTests = []EscapeTest{ diff --git a/src/pkg/utf8/string.go b/src/pkg/utf8/string.go index b33347950f..ce430ba4f5 100644 --- a/src/pkg/utf8/string.go +++ b/src/pkg/utf8/string.go @@ -198,14 +198,14 @@ func (s *String) At(i int) rune { // error is the type of the error returned if a user calls String.At(i) with i out of range. // It satisfies os.Error and runtime.Error. -type error string +type error_ string -func (err error) String() string { +func (err error_) String() string { return string(err) } -func (err error) RunTimeError() { +func (err error_) RunTimeError() { } -var outOfRange = error("utf8.String: index out of range") -var sliceOutOfRange = error("utf8.String: slice index out of range") +var outOfRange = error_("utf8.String: index out of range") +var sliceOutOfRange = error_("utf8.String: slice index out of range") diff --git a/src/pkg/websocket/client.go b/src/pkg/websocket/client.go index b7eaafda16..3da39a0ce4 100644 --- a/src/pkg/websocket/client.go +++ b/src/pkg/websocket/client.go @@ -9,22 +9,21 @@ import ( "crypto/tls" "io" "net" - "os" "url" ) // DialError is an error that occurs while dialling a websocket server. type DialError struct { *Config - Error os.Error + Err error } -func (e *DialError) String() string { - return "websocket.Dial " + e.Config.Location.String() + ": " + e.Error.String() +func (e *DialError) Error() string { + return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error() } // NewConfig creates a new WebSocket config for client connection. -func NewConfig(server, origin string) (config *Config, err os.Error) { +func NewConfig(server, origin string) (config *Config, err error) { config = new(Config) config.Version = ProtocolVersionHybi13 config.Location, err = url.ParseRequest(server) @@ -39,7 +38,7 @@ func NewConfig(server, origin string) (config *Config, err os.Error) { } // NewClient creates a new WebSocket client connection over rwc. -func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err os.Error) { +func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { br := bufio.NewReader(rwc) bw := bufio.NewWriter(rwc) switch config.Version { @@ -96,7 +95,7 @@ A trivial example client: // use msg[0:n] } */ -func Dial(url_, protocol, origin string) (ws *Conn, err os.Error) { +func Dial(url_, protocol, origin string) (ws *Conn, err error) { config, err := NewConfig(url_, origin) if err != nil { return nil, err @@ -105,7 +104,7 @@ func Dial(url_, protocol, origin string) (ws *Conn, err os.Error) { } // DialConfig opens a new client connection to a WebSocket with a config. -func DialConfig(config *Config) (ws *Conn, err os.Error) { +func DialConfig(config *Config) (ws *Conn, err error) { var client net.Conn if config.Location == nil { return nil, &DialError{config, ErrBadWebSocketLocation} diff --git a/src/pkg/websocket/hixie.go b/src/pkg/websocket/hixie.go index 841ff3c3ef..63eebc9502 100644 --- a/src/pkg/websocket/hixie.go +++ b/src/pkg/websocket/hixie.go @@ -16,7 +16,6 @@ import ( "http" "io" "io/ioutil" - "os" "rand" "strconv" "strings" @@ -42,14 +41,14 @@ func init() { } type byteReader interface { - ReadByte() (byte, os.Error) + ReadByte() (byte, error) } // readHixieLength reads frame length for frame type 0x80-0xFF // as defined in Hixie draft. // See section 4.2 Data framing. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-4.2 -func readHixieLength(r byteReader) (length int64, lengthFields []byte, err os.Error) { +func readHixieLength(r byteReader) (length int64, lengthFields []byte, err error) { for { c, err := r.ReadByte() if err != nil { @@ -74,7 +73,7 @@ type hixieLengthFrameReader struct { length int } -func (frame *hixieLengthFrameReader) Read(msg []byte) (n int, err os.Error) { +func (frame *hixieLengthFrameReader) Read(msg []byte) (n int, err error) { return frame.reader.Read(msg) } @@ -111,10 +110,10 @@ type hixieSentinelFrameReader struct { trailer *bytes.Buffer } -func (frame *hixieSentinelFrameReader) Read(msg []byte) (n int, err os.Error) { +func (frame *hixieSentinelFrameReader) Read(msg []byte) (n int, err error) { if len(frame.data) == 0 { if frame.seenTrailer { - return 0, os.EOF + return 0, io.EOF } frame.data, err = frame.reader.ReadSlice('\xff') if err == nil { @@ -164,7 +163,7 @@ type hixieFrameReaderFactory struct { *bufio.Reader } -func (buf hixieFrameReaderFactory) NewFrameReader() (r frameReader, err os.Error) { +func (buf hixieFrameReaderFactory) NewFrameReader() (r frameReader, err error) { var header []byte var b byte b, err = buf.ReadByte() @@ -178,7 +177,7 @@ func (buf hixieFrameReaderFactory) NewFrameReader() (r frameReader, err os.Error return nil, err } if length == 0 { - return nil, os.EOF + return nil, io.EOF } header = append(header, lengthFields...) return &hixieLengthFrameReader{ @@ -197,7 +196,7 @@ type hixiFrameWriter struct { writer *bufio.Writer } -func (frame *hixiFrameWriter) Write(msg []byte) (n int, err os.Error) { +func (frame *hixiFrameWriter) Write(msg []byte) (n int, err error) { frame.writer.WriteByte(0) frame.writer.Write(msg) frame.writer.WriteByte(0xff) @@ -205,13 +204,13 @@ func (frame *hixiFrameWriter) Write(msg []byte) (n int, err os.Error) { return len(msg), err } -func (frame *hixiFrameWriter) Close() os.Error { return nil } +func (frame *hixiFrameWriter) Close() error { return nil } type hixiFrameWriterFactory struct { *bufio.Writer } -func (buf hixiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err os.Error) { +func (buf hixiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) { if payloadType != TextFrame { return nil, ErrNotSupported } @@ -222,7 +221,7 @@ type hixiFrameHandler struct { conn *Conn } -func (handler *hixiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err os.Error) { +func (handler *hixiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err error) { if header := frame.HeaderReader(); header != nil { io.Copy(ioutil.Discard, header) } @@ -233,7 +232,7 @@ func (handler *hixiFrameHandler) HandleFrame(frame frameReader) (r frameReader, return frame, nil } -func (handler *hixiFrameHandler) WriteClose(_ int) (err os.Error) { +func (handler *hixiFrameHandler) WriteClose(_ int) (err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() closingFrame := []byte{'\xff', '\x00'} @@ -259,7 +258,7 @@ func newHixieConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, // getChallengeResponse computes the expected response from the // challenge as described in section 5.1 Opening Handshake steps 42 to // 43 of http://www.whatwg.org/specs/web-socket-protocol/ -func getChallengeResponse(number1, number2 uint32, key3 []byte) (expected []byte, err os.Error) { +func getChallengeResponse(number1, number2 uint32, key3 []byte) (expected []byte, err error) { // 41. Let /challenge/ be the concatenation of /number_1/, expressed // a big-endian 32 bit integer, /number_2/, expressed in a big- // endian 32 bit integer, and the eight bytes of /key_3/ in the @@ -336,7 +335,7 @@ func generateKey3() (key []byte) { // Cilent handhake described in (soon obsolete) // draft-ietf-hybi-thewebsocket-protocol-00 // (draft-hixie-thewebsocket-protocol-76) -func hixie76ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err os.Error) { +func hixie76ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { switch config.Version { case ProtocolVersionHixie76, ProtocolVersionHybi00: default: @@ -453,7 +452,7 @@ func hixie76ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) // Client Handshake described in (soon obsolete) // draft-hixie-thewebsocket-protocol-75. -func hixie75ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err os.Error) { +func hixie75ClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { if config.Version != ProtocolVersionHixie75 { panic("wrong protocol version.") } @@ -521,7 +520,7 @@ type hixie76ServerHandshaker struct { challengeResponse []byte } -func (c *hixie76ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) { +func (c *hixie76ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { c.Version = ProtocolVersionHybi00 if req.Method != "GET" { return http.StatusMethodNotAllowed, ErrBadRequestMethod @@ -598,7 +597,7 @@ func (c *hixie76ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Req return http.StatusSwitchingProtocols, nil } -func (c *hixie76ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err os.Error) { +func (c *hixie76ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { if len(c.Protocol) > 0 { if len(c.Protocol) != 1 { return ErrBadWebSocketProtocol @@ -632,7 +631,7 @@ type hixie75ServerHandshaker struct { *Config } -func (c *hixie75ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) { +func (c *hixie75ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { c.Version = ProtocolVersionHixie75 if req.Method != "GET" || req.Proto != "HTTP/1.1" { return http.StatusMethodNotAllowed, ErrBadRequestMethod @@ -667,7 +666,7 @@ func (c *hixie75ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Req return http.StatusSwitchingProtocols, nil } -func (c *hixie75ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err os.Error) { +func (c *hixie75ServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { if len(c.Protocol) > 0 { if len(c.Protocol) != 1 { return ErrBadWebSocketProtocol diff --git a/src/pkg/websocket/hixie_test.go b/src/pkg/websocket/hixie_test.go index 98a0de4d6f..40cb53f4ea 100644 --- a/src/pkg/websocket/hixie_test.go +++ b/src/pkg/websocket/hixie_test.go @@ -9,7 +9,7 @@ import ( "bytes" "fmt" "http" - "os" + "io" "strings" "testing" "url" @@ -46,7 +46,7 @@ Sec-WebSocket-Protocol: sample 8jKS'y:G*Co,Wxa-`)) - var err os.Error + var err error config := new(Config) config.Location, err = url.ParseRequest("ws://example.com/demo") if err != nil { @@ -195,7 +195,7 @@ func TestHixie76ClosingFrame(t *testing.T) { t.Errorf("Read: expected %q got %q", b[1:6], msg[0:n]) } n, err = ws.Read(msg) - if err != os.EOF { + if err != io.EOF { t.Errorf("read: %v", err) } } diff --git a/src/pkg/websocket/hybi.go b/src/pkg/websocket/hybi.go index fe08b3d738..d3d4258e98 100644 --- a/src/pkg/websocket/hybi.go +++ b/src/pkg/websocket/hybi.go @@ -18,7 +18,6 @@ import ( "http" "io" "io/ioutil" - "os" "strings" "url" ) @@ -69,7 +68,7 @@ type hybiFrameReader struct { length int } -func (frame *hybiFrameReader) Read(msg []byte) (n int, err os.Error) { +func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) { n, err = frame.reader.Read(msg) if err != nil { return 0, err @@ -107,7 +106,7 @@ type hybiFrameReaderFactory struct { // NewFrameReader reads a frame header from the connection, and creates new reader for the frame. // See Section 5.2 Base Frameing protocol for detail. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2 -func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err os.Error) { +func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) { hybiFrame := new(hybiFrameReader) frame = hybiFrame var header []byte @@ -174,7 +173,7 @@ type hybiFrameWriter struct { header *hybiFrameHeader } -func (frame *hybiFrameWriter) Write(msg []byte) (n int, err os.Error) { +func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) { var header []byte var b byte if frame.header.Fin { @@ -232,14 +231,14 @@ func (frame *hybiFrameWriter) Write(msg []byte) (n int, err os.Error) { return length, err } -func (frame *hybiFrameWriter) Close() os.Error { return nil } +func (frame *hybiFrameWriter) Close() error { return nil } type hybiFrameWriterFactory struct { *bufio.Writer needMaskingKey bool } -func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err os.Error) { +func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType} if buf.needMaskingKey { frameHeader.MaskingKey, err = generateMaskingKey() @@ -255,18 +254,18 @@ type hybiFrameHandler struct { payloadType byte } -func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err os.Error) { +func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (r frameReader, err error) { if handler.conn.IsServerConn() { // The client MUST mask all frames sent to the server. if frame.(*hybiFrameReader).header.MaskingKey == nil { handler.WriteClose(closeStatusProtocolError) - return nil, os.EOF + return nil, io.EOF } } else { // The server MUST NOT mask all frames. if frame.(*hybiFrameReader).header.MaskingKey != nil { handler.WriteClose(closeStatusProtocolError) - return nil, os.EOF + return nil, io.EOF } } if header := frame.HeaderReader(); header != nil { @@ -278,7 +277,7 @@ func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (r frameReader, case TextFrame, BinaryFrame: handler.payloadType = frame.PayloadType() case CloseFrame: - return nil, os.EOF + return nil, io.EOF case PingFrame: pingMsg := make([]byte, maxControlFramePayloadLength) n, err := io.ReadFull(frame, pingMsg) @@ -297,7 +296,7 @@ func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (r frameReader, return frame, nil } -func (handler *hybiFrameHandler) WriteClose(status int) (err os.Error) { +func (handler *hybiFrameHandler) WriteClose(status int) (err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame) @@ -311,7 +310,7 @@ func (handler *hybiFrameHandler) WriteClose(status int) (err os.Error) { return err } -func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err os.Error) { +func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) { handler.conn.wio.Lock() defer handler.conn.wio.Unlock() w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame) @@ -341,7 +340,7 @@ func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, } // generateMaskingKey generates a masking key for a frame. -func generateMaskingKey() (maskingKey []byte, err os.Error) { +func generateMaskingKey() (maskingKey []byte, err error) { maskingKey = make([]byte, 4) if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil { return @@ -363,7 +362,7 @@ func generateNonce() (nonce []byte) { // getNonceAccept computes the base64-encoded SHA-1 of the concatenation of // the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string. -func getNonceAccept(nonce []byte) (expected []byte, err os.Error) { +func getNonceAccept(nonce []byte) (expected []byte, err error) { h := sha1.New() if _, err = h.Write(nonce); err != nil { return @@ -386,7 +385,7 @@ func isHybiVersion(version int) bool { } // Client handhake described in draft-ietf-hybi-thewebsocket-protocol-17 -func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err os.Error) { +func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { if !isHybiVersion(config.Version) { panic("wrong protocol version.") } @@ -468,7 +467,7 @@ type hybiServerHandshaker struct { accept []byte } -func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) { +func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { c.Version = ProtocolVersionHybi13 if req.Method != "GET" { return http.StatusMethodNotAllowed, ErrBadRequestMethod @@ -522,7 +521,7 @@ func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Reques return http.StatusSwitchingProtocols, nil } -func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err os.Error) { +func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { if len(c.Protocol) > 0 { if len(c.Protocol) != 1 { return ErrBadWebSocketProtocol diff --git a/src/pkg/websocket/hybi_test.go b/src/pkg/websocket/hybi_test.go index 9db57e3f1b..df0f555265 100644 --- a/src/pkg/websocket/hybi_test.go +++ b/src/pkg/websocket/hybi_test.go @@ -9,7 +9,7 @@ import ( "bytes" "fmt" "http" - "os" + "io" "strings" "testing" "url" @@ -40,7 +40,7 @@ Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat `)) - var err os.Error + var err error config := new(Config) config.Location, err = url.ParseRequest("ws://server.example.com/chat") if err != nil { @@ -102,7 +102,7 @@ Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat `)) - var err os.Error + var err error config := new(Config) config.Location, err = url.ParseRequest("ws://server.example.com/chat") if err != nil { @@ -513,8 +513,8 @@ func TestHybiServerReadWithoutMasking(t *testing.T) { // server MUST close the connection upon receiving a non-masked frame. msg := make([]byte, 512) _, err := conn.Read(msg) - if err != os.EOF { - t.Errorf("read 1st frame, expect %q, but got %q", os.EOF, err) + if err != io.EOF { + t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) } } @@ -529,8 +529,8 @@ func TestHybiClientReadWithMasking(t *testing.T) { // client MUST close the connection upon receiving a masked frame. msg := make([]byte, 512) _, err := conn.Read(msg) - if err != os.EOF { - t.Errorf("read 1st frame, expect %q, but got %q", os.EOF, err) + if err != io.EOF { + t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) } } diff --git a/src/pkg/websocket/server.go b/src/pkg/websocket/server.go index a1d1d48600..9420c47191 100644 --- a/src/pkg/websocket/server.go +++ b/src/pkg/websocket/server.go @@ -9,10 +9,9 @@ import ( "fmt" "http" "io" - "os" ) -func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err os.Error) { +func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err error) { config := new(Config) var hs serverHandshaker = &hybiServerHandshaker{Config: config} code, err := hs.ReadHandshake(buf.Reader, req) @@ -20,7 +19,7 @@ func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Requ fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) buf.WriteString("\r\n") - buf.WriteString(err.String()) + buf.WriteString(err.Error()) return } if err != nil { @@ -34,7 +33,7 @@ func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Requ if err != nil { fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) buf.WriteString("\r\n") - buf.WriteString(err.String()) + buf.WriteString(err.Error()) return } config.Protocol = nil @@ -79,7 +78,7 @@ type Handler func(*Conn) func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { rwc, buf, err := w.(http.Hijacker).Hijack() if err != nil { - panic("Hijack failed: " + err.String()) + panic("Hijack failed: " + err.Error()) return } // The server should abort the WebSocket connection if it finds diff --git a/src/pkg/websocket/websocket.go b/src/pkg/websocket/websocket.go index a3750dde11..9732ae1173 100644 --- a/src/pkg/websocket/websocket.go +++ b/src/pkg/websocket/websocket.go @@ -42,7 +42,7 @@ type ProtocolError struct { ErrorString string } -func (err *ProtocolError) String() string { return err.ErrorString } +func (err *ProtocolError) Error() string { return err.ErrorString } var ( ErrBadProtocolVersion = &ProtocolError{"bad protocol version"} @@ -93,11 +93,11 @@ type Config struct { type serverHandshaker interface { // ReadHandshake reads handshake request message from client. // Returns http response code and error if any. - ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err os.Error) + ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) // AcceptHandshake accepts the client handshake request and sends // handshake response back to client. - AcceptHandshake(buf *bufio.Writer) (err os.Error) + AcceptHandshake(buf *bufio.Writer) (err error) // NewServerConn creates a new WebSocket connection. NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn) @@ -124,7 +124,7 @@ type frameReader interface { // frameReaderFactory is an interface to creates new frame reader. type frameReaderFactory interface { - NewFrameReader() (r frameReader, err os.Error) + NewFrameReader() (r frameReader, err error) } // frameWriter is an interface to write a WebSocket frame. @@ -135,12 +135,12 @@ type frameWriter interface { // frameWriterFactory is an interface to create new frame writer. type frameWriterFactory interface { - NewFrameWriter(payloadType byte) (w frameWriter, err os.Error) + NewFrameWriter(payloadType byte) (w frameWriter, err error) } type frameHandler interface { - HandleFrame(frame frameReader) (r frameReader, err os.Error) - WriteClose(status int) (err os.Error) + HandleFrame(frame frameReader) (r frameReader, err error) + WriteClose(status int) (err error) } // Conn represents a WebSocket connection. @@ -168,7 +168,7 @@ type Conn struct { // if msg is not large enough for the frame data, it fills the msg and next Read // will read the rest of the frame data. // it reads Text frame or Binary frame. -func (ws *Conn) Read(msg []byte) (n int, err os.Error) { +func (ws *Conn) Read(msg []byte) (n int, err error) { ws.rio.Lock() defer ws.rio.Unlock() again: @@ -186,7 +186,7 @@ again: } } n, err = ws.frameReader.Read(msg) - if err == os.EOF { + if err == io.EOF { if trailer := ws.frameReader.TrailerReader(); trailer != nil { io.Copy(ioutil.Discard, trailer) } @@ -198,7 +198,7 @@ again: // Write implements the io.Writer interface: // it writes data as a frame to the WebSocket connection. -func (ws *Conn) Write(msg []byte) (n int, err os.Error) { +func (ws *Conn) Write(msg []byte) (n int, err error) { ws.wio.Lock() defer ws.wio.Unlock() w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType) @@ -214,7 +214,7 @@ func (ws *Conn) Write(msg []byte) (n int, err os.Error) { } // Close implements the io.Closer interface. -func (ws *Conn) Close() os.Error { +func (ws *Conn) Close() error { err := ws.frameHandler.WriteClose(ws.defaultCloseStatus) if err != nil { return err @@ -244,7 +244,7 @@ func (ws *Conn) RemoteAddr() net.Addr { } // SetTimeout sets the connection's network timeout in nanoseconds. -func (ws *Conn) SetTimeout(nsec int64) os.Error { +func (ws *Conn) SetTimeout(nsec int64) error { if conn, ok := ws.rwc.(net.Conn); ok { return conn.SetTimeout(nsec) } @@ -252,7 +252,7 @@ func (ws *Conn) SetTimeout(nsec int64) os.Error { } // SetReadTimeout sets the connection's network read timeout in nanoseconds. -func (ws *Conn) SetReadTimeout(nsec int64) os.Error { +func (ws *Conn) SetReadTimeout(nsec int64) error { if conn, ok := ws.rwc.(net.Conn); ok { return conn.SetReadTimeout(nsec) } @@ -260,7 +260,7 @@ func (ws *Conn) SetReadTimeout(nsec int64) os.Error { } // SetWriteTimeout sets the connection's network write timeout in nanoseconds. -func (ws *Conn) SetWriteTimeout(nsec int64) os.Error { +func (ws *Conn) SetWriteTimeout(nsec int64) error { if conn, ok := ws.rwc.(net.Conn); ok { return conn.SetWriteTimeout(nsec) } @@ -276,12 +276,12 @@ func (ws *Conn) Request() *http.Request { return ws.request } // Codec represents a symmetric pair of functions that implement a codec. type Codec struct { - Marshal func(v interface{}) (data []byte, payloadType byte, err os.Error) - Unmarshal func(data []byte, payloadType byte, v interface{}) (err os.Error) + Marshal func(v interface{}) (data []byte, payloadType byte, err error) + Unmarshal func(data []byte, payloadType byte, v interface{}) (err error) } // Send sends v marshaled by cd.Marshal as single frame to ws. -func (cd Codec) Send(ws *Conn, v interface{}) (err os.Error) { +func (cd Codec) Send(ws *Conn, v interface{}) (err error) { if err != nil { return err } @@ -298,7 +298,7 @@ func (cd Codec) Send(ws *Conn, v interface{}) (err os.Error) { } // Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores in v. -func (cd Codec) Receive(ws *Conn, v interface{}) (err os.Error) { +func (cd Codec) Receive(ws *Conn, v interface{}) (err error) { ws.rio.Lock() defer ws.rio.Unlock() if ws.frameReader != nil { @@ -328,7 +328,7 @@ again: return cd.Unmarshal(data, payloadType, v) } -func marshal(v interface{}) (msg []byte, payloadType byte, err os.Error) { +func marshal(v interface{}) (msg []byte, payloadType byte, err error) { switch data := v.(type) { case string: return []byte(data), TextFrame, nil @@ -338,7 +338,7 @@ func marshal(v interface{}) (msg []byte, payloadType byte, err os.Error) { return nil, UnknownFrame, ErrNotSupported } -func unmarshal(msg []byte, payloadType byte, v interface{}) (err os.Error) { +func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) { switch data := v.(type) { case *string: *data = string(msg) @@ -378,12 +378,12 @@ Trivial usage: */ var Message = Codec{marshal, unmarshal} -func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err os.Error) { +func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) { msg, err = json.Marshal(v) return msg, TextFrame, err } -func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err os.Error) { +func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) { return json.Unmarshal(msg, v) } diff --git a/src/pkg/websocket/websocket_test.go b/src/pkg/websocket/websocket_test.go index 240af4e49b..69b5335cfa 100644 --- a/src/pkg/websocket/websocket_test.go +++ b/src/pkg/websocket/websocket_test.go @@ -211,7 +211,7 @@ func TestHTTP(t *testing.T) { t.Errorf("Get: not url.Error %#v", err) return } - if urlerr.Error != io.ErrUnexpectedEOF { + if urlerr.Err != io.ErrUnexpectedEOF { t.Errorf("Get: error %#v", err) return } diff --git a/src/pkg/xml/marshal.go b/src/pkg/xml/marshal.go index 8396dba27e..691b70d251 100644 --- a/src/pkg/xml/marshal.go +++ b/src/pkg/xml/marshal.go @@ -7,7 +7,6 @@ package xml import ( "bufio" "io" - "os" "reflect" "strconv" "strings" @@ -23,7 +22,7 @@ const ( // A Marshaler can produce well-formatted XML representing its internal state. // It is used by both Marshal and MarshalIndent. type Marshaler interface { - MarshalXML() ([]byte, os.Error) + MarshalXML() ([]byte, error) } type printer struct { @@ -84,14 +83,14 @@ type printer struct { // // // Marshal will return an error if asked to marshal a channel, function, or map. -func Marshal(w io.Writer, v interface{}) (err os.Error) { +func Marshal(w io.Writer, v interface{}) (err error) { p := &printer{bufio.NewWriter(w)} err = p.marshalValue(reflect.ValueOf(v), "???") p.Flush() return err } -func (p *printer) marshalValue(val reflect.Value, name string) os.Error { +func (p *printer) marshalValue(val reflect.Value, name string) error { if !val.IsValid() { return nil } @@ -300,6 +299,6 @@ type UnsupportedTypeError struct { Type reflect.Type } -func (e *UnsupportedTypeError) String() string { +func (e *UnsupportedTypeError) Error() string { return "xml: unsupported type: " + e.Type.String() } diff --git a/src/pkg/xml/marshal_test.go b/src/pkg/xml/marshal_test.go index 9c6f3dd634..59007b3645 100644 --- a/src/pkg/xml/marshal_test.go +++ b/src/pkg/xml/marshal_test.go @@ -7,8 +7,6 @@ package xml import ( "reflect" "testing" - - "os" "bytes" "strings" "strconv" @@ -39,7 +37,7 @@ type Ship struct { type RawXML string -func (rx RawXML) MarshalXML() ([]byte, os.Error) { +func (rx RawXML) MarshalXML() ([]byte, error) { return []byte(rx), nil } @@ -342,7 +340,7 @@ func TestMarshalErrors(t *testing.T) { for idx, test := range marshalErrorTests { buf := bytes.NewBuffer(nil) err := Marshal(buf, test.Value) - if err == nil || err.String() != test.Err { + if err == nil || err.Error() != test.Err { t.Errorf("#%d: marshal(%#v) = [error] %q, want %q", idx, test.Value, err, test.Err) } if kind := err.(*UnsupportedTypeError).Type.Kind(); kind != test.Kind { diff --git a/src/pkg/xml/read.go b/src/pkg/xml/read.go index 1fe20ac614..a88941c92b 100644 --- a/src/pkg/xml/read.go +++ b/src/pkg/xml/read.go @@ -6,9 +6,9 @@ package xml import ( "bytes" + "errors" "fmt" "io" - "os" "reflect" "strconv" "strings" @@ -150,10 +150,10 @@ import ( // Unmarshal maps an XML element to a pointer by setting the pointer // to a freshly allocated value and then mapping the element to that value. // -func Unmarshal(r io.Reader, val interface{}) os.Error { +func Unmarshal(r io.Reader, val interface{}) error { v := reflect.ValueOf(val) if v.Kind() != reflect.Ptr { - return os.NewError("non-pointer passed to Unmarshal") + return errors.New("non-pointer passed to Unmarshal") } p := NewParser(r) elem := v.Elem() @@ -167,7 +167,7 @@ func Unmarshal(r io.Reader, val interface{}) os.Error { // An UnmarshalError represents an error in the unmarshalling process. type UnmarshalError string -func (e UnmarshalError) String() string { return string(e) } +func (e UnmarshalError) Error() string { return string(e) } // A TagPathError represents an error in the unmarshalling process // caused by the use of field tags with conflicting paths. @@ -177,7 +177,7 @@ type TagPathError struct { Field2, Tag2 string } -func (e *TagPathError) String() string { +func (e *TagPathError) Error() string { return fmt.Sprintf("%s field %q with tag %q conflicts with field %q with tag %q", e.Struct, e.Field1, e.Tag1, e.Field2, e.Tag2) } @@ -187,10 +187,10 @@ func (e *TagPathError) String() string { // but also defers to Unmarshal for some elements. // Passing a nil start element indicates that Unmarshal should // read the token stream to find the start element. -func (p *Parser) Unmarshal(val interface{}, start *StartElement) os.Error { +func (p *Parser) Unmarshal(val interface{}, start *StartElement) error { v := reflect.ValueOf(val) if v.Kind() != reflect.Ptr { - return os.NewError("non-pointer passed to Unmarshal") + return errors.New("non-pointer passed to Unmarshal") } return p.unmarshal(v.Elem(), start) } @@ -216,7 +216,7 @@ func fieldName(original string) string { } // Unmarshal a single XML element into val. -func (p *Parser) unmarshal(val reflect.Value, start *StartElement) os.Error { +func (p *Parser) unmarshal(val reflect.Value, start *StartElement) error { // Find start element if we need it. if start == nil { for { @@ -253,7 +253,7 @@ func (p *Parser) unmarshal(val reflect.Value, start *StartElement) os.Error { switch v := val; v.Kind() { default: - return os.NewError("unknown type " + v.Type().String()) + return errors.New("unknown type " + v.Type().String()) case reflect.Slice: typ := v.Type() @@ -482,7 +482,7 @@ Loop: return nil } -func copyValue(dst reflect.Value, src []byte) (err os.Error) { +func copyValue(dst reflect.Value, src []byte) (err error) { // Helper functions for integer and unsigned integer conversions var itmp int64 getInt64 := func() bool { @@ -508,7 +508,7 @@ func copyValue(dst reflect.Value, src []byte) (err os.Error) { case reflect.Invalid: // Probably a comment, handled below default: - return os.NewError("cannot happen: unknown type " + t.Type().String()) + return errors.New("cannot happen: unknown type " + t.Type().String()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if !getInt64() { return err @@ -547,7 +547,7 @@ type pathInfo struct { // paths map with all paths leading to it ("a", "a>b", and "a>b>c"). // It is okay for paths to share a common, shorter prefix but not ok // for one path to itself be a prefix of another. -func addFieldPath(sv reflect.Value, paths map[string]pathInfo, path string, fieldIdx []int) os.Error { +func addFieldPath(sv reflect.Value, paths map[string]pathInfo, path string, fieldIdx []int) error { if info, found := paths[path]; found { return tagError(sv, info.fieldIdx, fieldIdx) } @@ -570,7 +570,7 @@ func addFieldPath(sv reflect.Value, paths map[string]pathInfo, path string, fiel } -func tagError(sv reflect.Value, idx1 []int, idx2 []int) os.Error { +func tagError(sv reflect.Value, idx1 []int, idx2 []int) error { t := sv.Type() f1 := t.FieldByIndex(idx1) f2 := t.FieldByIndex(idx2) @@ -579,7 +579,7 @@ func tagError(sv reflect.Value, idx1 []int, idx2 []int) os.Error { // unmarshalPaths walks down an XML structure looking for // wanted paths, and calls unmarshal on them. -func (p *Parser) unmarshalPaths(sv reflect.Value, paths map[string]pathInfo, path string, start *StartElement) os.Error { +func (p *Parser) unmarshalPaths(sv reflect.Value, paths map[string]pathInfo, path string, start *StartElement) error { if info, _ := paths[path]; info.complete { return p.unmarshal(sv.FieldByIndex(info.fieldIdx), start) } @@ -611,7 +611,7 @@ func (p *Parser) unmarshalPaths(sv reflect.Value, paths map[string]pathInfo, pat // Read tokens until we find the end element. // Token is taking care of making sure the // end element matches the start element we saw. -func (p *Parser) Skip() os.Error { +func (p *Parser) Skip() error { for { tok, err := p.Token() if err != nil { diff --git a/src/pkg/xml/xml.go b/src/pkg/xml/xml.go index bc03c8e0d4..d534c52c1c 100644 --- a/src/pkg/xml/xml.go +++ b/src/pkg/xml/xml.go @@ -18,7 +18,6 @@ import ( "bytes" "fmt" "io" - "os" "strconv" "strings" "unicode" @@ -31,7 +30,7 @@ type SyntaxError struct { Line int } -func (e *SyntaxError) String() string { +func (e *SyntaxError) Error() string { return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg } @@ -168,7 +167,7 @@ type Parser struct { // non-UTF-8 charset into UTF-8. If CharsetReader is nil or // returns an error, parsing stops with an error. One of the // the CharsetReader's result values must be non-nil. - CharsetReader func(charset string, input io.Reader) (io.Reader, os.Error) + CharsetReader func(charset string, input io.Reader) (io.Reader, error) r io.ByteReader buf bytes.Buffer @@ -180,7 +179,7 @@ type Parser struct { nextToken Token nextByte int ns map[string]string - err os.Error + err error line int tmp [32]byte } @@ -219,7 +218,7 @@ func NewParser(r io.Reader) *Parser { // set to the URL identifying its name space when known. // If Token encounters an unrecognized name space prefix, // it uses the prefix as the Space rather than report an error. -func (p *Parser) Token() (t Token, err os.Error) { +func (p *Parser) Token() (t Token, err error) { if p.nextToken != nil { t = p.nextToken p.nextToken = nil @@ -354,7 +353,7 @@ func (p *Parser) pushNs(local string, url string, ok bool) { } // Creates a SyntaxError with the current line number. -func (p *Parser) syntaxError(msg string) os.Error { +func (p *Parser) syntaxError(msg string) error { return &SyntaxError{Msg: msg, Line: p.line} } @@ -423,7 +422,7 @@ func (p *Parser) autoClose(t Token) (Token, bool) { // RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs. -func (p *Parser) RawToken() (Token, os.Error) { +func (p *Parser) RawToken() (Token, error) { if p.err != nil { return nil, p.err } @@ -777,7 +776,7 @@ func (p *Parser) savedOffset() int { // and return ok==false func (p *Parser) mustgetc() (b byte, ok bool) { if b, ok = p.getc(); !ok { - if p.err == os.EOF { + if p.err == io.EOF { p.err = p.syntaxError("unexpected EOF") } } @@ -813,7 +812,7 @@ Input: b, ok := p.getc() if !ok { if cdata { - if p.err == os.EOF { + if p.err == io.EOF { p.err = p.syntaxError("unexpected EOF in CDATA section") } return nil @@ -855,7 +854,7 @@ Input: var ok bool p.tmp[i], ok = p.getc() if !ok { - if p.err == os.EOF { + if p.err == io.EOF { p.err = p.syntaxError("unexpected EOF") } return nil @@ -888,7 +887,7 @@ Input: var text string if i >= 2 && s[0] == '#' { var n uint64 - var err os.Error + var err error if i >= 3 && s[1] == 'x' { n, err = strconv.Btoui64(s[2:], 16) } else { diff --git a/src/pkg/xml/xml_test.go b/src/pkg/xml/xml_test.go index 6407624055..1b40d0c4d4 100644 --- a/src/pkg/xml/xml_test.go +++ b/src/pkg/xml/xml_test.go @@ -162,9 +162,9 @@ type stringReader struct { off int } -func (r *stringReader) Read(b []byte) (n int, err os.Error) { +func (r *stringReader) Read(b []byte) (n int, err error) { if r.off >= len(r.s) { - return 0, os.EOF + return 0, io.EOF } for r.off < len(r.s) && n < len(b) { b[n] = r.s[r.off] @@ -174,9 +174,9 @@ func (r *stringReader) Read(b []byte) (n int, err os.Error) { return } -func (r *stringReader) ReadByte() (b byte, err os.Error) { +func (r *stringReader) ReadByte() (b byte, err error) { if r.off >= len(r.s) { - return 0, os.EOF + return 0, io.EOF } b = r.s[r.off] r.off++ @@ -195,7 +195,7 @@ type downCaser struct { r io.ByteReader } -func (d *downCaser) ReadByte() (c byte, err os.Error) { +func (d *downCaser) ReadByte() (c byte, err error) { c, err = d.r.ReadByte() if c >= 'A' && c <= 'Z' { c += 'a' - 'A' @@ -203,7 +203,7 @@ func (d *downCaser) ReadByte() (c byte, err os.Error) { return } -func (d *downCaser) Read(p []byte) (int, os.Error) { +func (d *downCaser) Read(p []byte) (int, error) { d.t.Fatalf("unexpected Read call on downCaser reader") return 0, os.EINVAL } @@ -211,7 +211,7 @@ func (d *downCaser) Read(p []byte) (int, os.Error) { func TestRawTokenAltEncoding(t *testing.T) { sawEncoding := "" p := NewParser(StringReader(testInputAltEncoding)) - p.CharsetReader = func(charset string, input io.Reader) (io.Reader, os.Error) { + p.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { sawEncoding = charset if charset != "x-testing-uppercase" { t.Fatalf("unexpected charset %q", charset) @@ -238,7 +238,7 @@ func TestRawTokenAltEncodingNoConverter(t *testing.T) { t.Fatalf("expected an error on second RawToken call") } const encoding = "x-testing-uppercase" - if !strings.Contains(err.String(), encoding) { + if !strings.Contains(err.Error(), encoding) { t.Errorf("expected error to contain %q; got error: %v", encoding, err) } @@ -319,7 +319,7 @@ func TestToken(t *testing.T) { func TestSyntax(t *testing.T) { for i := range xmlInput { p := NewParser(StringReader(xmlInput[i])) - var err os.Error + var err error for _, err = p.Token(); err == nil; _, err = p.Token() { } if _, ok := err.(*SyntaxError); !ok { @@ -501,7 +501,7 @@ func TestCopyTokenStartElement(t *testing.T) { func TestSyntaxErrorLineNum(t *testing.T) { testInput := "

Foo

\n\n

Bar\n" p := NewParser(StringReader(testInput)) - var err os.Error + var err error for _, err = p.Token(); err == nil; _, err = p.Token() { } synerr, ok := err.(*SyntaxError) @@ -516,10 +516,10 @@ func TestSyntaxErrorLineNum(t *testing.T) { func TestTrailingRawToken(t *testing.T) { input := ` ` p := NewParser(StringReader(input)) - var err os.Error + var err error for _, err = p.RawToken(); err == nil; _, err = p.RawToken() { } - if err != os.EOF { + if err != io.EOF { t.Fatalf("p.RawToken() = _, %v, want _, os.EOF", err) } } @@ -527,10 +527,10 @@ func TestTrailingRawToken(t *testing.T) { func TestTrailingToken(t *testing.T) { input := ` ` p := NewParser(StringReader(input)) - var err os.Error + var err error for _, err = p.Token(); err == nil; _, err = p.Token() { } - if err != os.EOF { + if err != io.EOF { t.Fatalf("p.Token() = _, %v, want _, os.EOF", err) } } @@ -538,10 +538,10 @@ func TestTrailingToken(t *testing.T) { func TestEntityInsideCDATA(t *testing.T) { input := `` p := NewParser(StringReader(input)) - var err os.Error + var err error for _, err = p.Token(); err == nil; _, err = p.Token() { } - if err != os.EOF { + if err != io.EOF { t.Fatalf("p.Token() = _, %v, want _, os.EOF", err) } } @@ -570,7 +570,7 @@ func TestDisallowedCharacters(t *testing.T) { for i, tt := range characterTests { p := NewParser(StringReader(tt.in)) - var err os.Error + var err error for err == nil { _, err = p.Token()